Python调用OpenAI API遇TypeError错误,如何修复?
解决OpenAI Python客户端调用ChatGPT接口的TypeError问题
问题根源
你遇到的TypeError有两个核心原因:
- 接口使用错误:
gpt-3.5-turbo属于聊天模型,需使用chat.completions接口而非通用的completions接口。 - 参数名错误:OpenAI v1.x版本的客户端已将
engine参数替换为model,同时聊天模型需要特定的请求格式。
修正后的代码
from openai import OpenAI client = OpenAI(api_key="sk-proj-0Xo*******************************qOd") def chat_with_chatgpt(prompt, model="gpt-3.5-turbo"): response = client.chat.completions.create( model=model, messages=[{"role": "user", "content": prompt}], max_tokens=100, n=1, stop=None, temperature=0.5 ) message = response.choices[0].message.content.strip() return message prompt = "Tell me about yourself" response = chat_with_chatgpt(prompt) print(response)
关键修改说明
- 接口切换:将
client.completions.create改为client.chat.completions.create,适配GPT-3.5/4系列聊天模型的调用规范。 - 参数调整:
- 用
model=model替代原engine=model,符合新客户端的参数命名要求。 - 新增
messages参数,以[{"role": "user", "content": prompt}]格式传入用户提问,这是聊天模型的必填参数格式。
- 用
- 响应解析:将
response.choices[0].text改为response.choices[0].message.content.strip(),对应聊天模型返回的响应结构。
内容的提问来源于stack exchange,提问作者alexporritt
相关产品推荐
相关产品推荐

