当前位置:   article > 正文

chatgpt之api的调用问题_you tried to access openai.chatcompletion, but thi

you tried to access openai.chatcompletion, but this is no longer supported i

1.调用api过程中,出现如下报错内容

先写一个测试样例

import openai


openai.api_key = "OPEN_AI_KEY"
openai.api_base="OPEN_AI_BASE_URL" # 是否需要base根据自己所在地区和key情况进行

completion = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {
            "role": "user",
            "content": "帮我用python写topk算法"
        },
    ]
)

print(completion.choices[0].message)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

运行后,出现如下报错。

You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface.

Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28`

A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2. 解决问题

根据提示可知道,是API更新的缘故,查阅文档对代码进行修改即可。

import openai


openai.api_key = "OPEN_AI_KEY"
openai.api_base="OPEN_AI_BASE_URL" # 是否需要base根据自己所在地区和key情况进行

# 区别主要是将openai.ChatCompletion.create换成openai.chat.completions.create
completion = openai.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[
        {
            "role": "user",
            "content": "帮我用python写topk算法"
        },
    ],
)
print(completion.choices[0].message.content)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

正常运行即可,结果如下:
在这里插入图片描述

3.思考

api_base是干嘛的?其实他就是调用api过程中的镜像网站,避免连接不上或者被block。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/672935
推荐阅读
相关标签
  

闽ICP备14008679号