题意:OpenAI Python Package Error: 'ChatCompletion' object 不支持下标访问
问题背景:
After updating my OpenAI package to version 1.1.1, I got this error when trying to read the ChatGPT API response:
在将我的 OpenAI 包更新到版本 1.1.1 后,当我尝试读取 ChatGPT API 响应时遇到了这个错误:
'ChatCompletion' object is not subscriptable
Here is my code: 这是我的代码:
messages = [
{"role": "system", "content": '''You answer question about some service'''
},
{"role": "user", "content": 'The user question is ...'},
]
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=0
)
response_message = response["choices"][0]["message"]["content"]
How can I resolve this error? 我怎样处理这个错误?
问题解决:
In the latest OpenAI package the response.choices
object type is changed and in this way you must read the response:
在最新的 OpenAI 包中,response.choices
的对象类型已经发生了变化,因此你需要以这种方式来读取响应:
print(response.choices[0].message.content)
The complete working code: 完整的可工作代码(Generic Example)
from openai import OpenAI
client = OpenAI(api_key='YourKey')
GPT_MODEL = "gpt-4-1106-preview" #"gpt-3.5-turbo-1106"
messages = [
{"role": "system", "content": 'You answer question about Web services.'
},
{"role": "user", "content": 'the user message'},
]
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=0
)
response_message = response.choices[0].message.content
print(response_message )
See this example in the project README.
查看项目README中的这个示例。