最近升级了 OpenAI Python 包的最新版本。运行旧代码时出现编译错误:
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
openai>=1.0.0 示例
在查看了提示中迁移说明的后,写一个基本示例来调用openai>=1.0.0版本,供大家参考:
说明:代码中设置 base_url
以自定义主机,从而能够使用第三方 OpenAI 代理,这个选项的可选的,如果你使直接访问openai的服务,可以删除这一个配置。
from openai import OpenAI
client = OpenAI(
api_key="xxx",
base_url = 'xxx'
)
def get_completion(prompt, model="gpt-3.5-turbo-1106"):
messages = [{"role": "user", "content": prompt}]
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=0.7,
)
return response.choices[0].message.content
prompt = "你好,ChatGPT!"
print(get_completion(prompt))
如果要启用 OpenAI 新推出的 JSON mode:
def get_completion(prompt, model="gpt-3.5-turbo-1106"):
messages = [{"role": "user", "content": prompt}]
response = client.chat.completions.create(
model=model,
messages=messages,
response_format={"type": "json_object"},
temperature=0.7,
)
return response.choices[0].message.content
openai==0.28 示例
import openai
openai.api_key = ''
openai.api_base = ''
def get_completion(prompt, model="gpt-3.5-turbo-1106"):
messages = [{"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=0.7,
)
return response.choices[0].message["content"]
prompt = "你好,ChatGPT!"
print(get_completion(prompt))