Python开发网站聊天机器人遇OpenAI API AttributeError问题求助
解决OpenAI API的AttributeError: module 'openai' has no attribute 'Completion'问题
报错原因
你使用的是OpenAI Python SDK的v1.x版本,该版本完全重构了API接口:
- 旧版的
openai.Completion.create接口已被移除 - 官方提示的
completions是新版补全模型的接口,而gpt-3.5-turbo属于聊天模型,需要用专门的chat.completions接口
修正方案
方案1:使用gpt-3.5-turbo(推荐,成本更低、效果更好)
gpt-3.5-turbo是聊天模型,需要传入messages参数(对话格式),而非旧版的prompt:
import openai openai.api_key = "API-KEY" def chat_with_gpt(prompt): response = openai.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "user", "content": prompt} ], max_tokens=150 ) return response.choices[0].message.content.strip() if __name__ == "__main__": while True: user_input = input("You: ") user_input = user_input.lower() if user_input in ["quit", "exit", "bye"]: break response = chat_with_gpt(user_input) print("Chatbot:", response)
方案2:使用text-davinci-003(补全模型)
如果坚持用text-davinci-003,需要改用新版的openai.completions.create接口(注意是小写的completions):
import openai openai.api_key = "API-KEY" def chat_with_gpt(prompt): response = openai.completions.create( model="text-davinci-003", prompt=prompt, max_tokens=150 ) return response.choices[0].text.strip() if __name__ == "__main__": while True: user_input = input("You: ") user_input = user_input.lower() if user_input in ["quit", "exit", "bye"]: break response = chat_with_gpt(user_input) print("Chatbot:", response)
关键改动说明
- 接口名称变化:
- 聊天模型(gpt-3.5-turbo/gpt-4):
openai.chat.completions.create - 补全模型(text-davinci-003等):
openai.completions.create
- 聊天模型(gpt-3.5-turbo/gpt-4):
- 参数格式变化:
- 聊天模型必须用
messages参数,传入包含角色和内容的字典列表
- 聊天模型必须用
- 响应解析变化:
- 聊天模型的响应内容从
response.choices[0].text改为response.choices[0].message.content
- 聊天模型的响应内容从
内容的提问来源于stack exchange,提问作者user12080214
相关产品推荐
相关产品推荐

