You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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)

关键改动说明

  1. 接口名称变化:
    • 聊天模型(gpt-3.5-turbo/gpt-4):openai.chat.completions.create
    • 补全模型(text-davinci-003等):openai.completions.create
  2. 参数格式变化:
    • 聊天模型必须用messages参数,传入包含角色和内容的字典列表
  3. 响应解析变化:
    • 聊天模型的响应内容从response.choices[0].text改为response.choices[0].message.content

内容的提问来源于stack exchange,提问作者user12080214

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 17:41:07