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

Python调用OpenAI API遇TypeError错误,如何修复?

解决OpenAI Python客户端调用ChatGPT接口的TypeError问题

问题根源

你遇到的TypeError有两个核心原因:

  1. 接口使用错误:gpt-3.5-turbo属于聊天模型,需使用chat.completions接口而非通用的completions接口。
  2. 参数名错误: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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 09:46:08