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

调用OpenAI GPT-3 API报错:Cannot specify both model and engine及KeyError问题

解决调用GPT-3 API时的KeyError及"Cannot specify both model and engine"错误

你遇到的KeyError: 'choices'是因为API返回了错误信息而非预期的结果,错误提示Cannot specify both model and engine已经明确指出核心问题——你同时通过请求URL的路径指定了engine(davinci)和请求体里的model参数(text-davinci-002),二者冲突导致请求被拒绝。

下面是两种可行的修正方案:

方案一:使用engine路径接口,移除model参数

URL中已经通过/engines/davinci指定了引擎,因此请求体里无需再添加model参数:

import json
import requests

# 替换为你的实际API密钥
apikey = "your-api-key-here"

data = {
    "prompt": "What is the meaning of life?",
    "max_tokens": 100  # 可选参数,控制生成内容的最大长度
}

response = requests.post("https://api.openai.com/v1/engines/davinci/completions", json=data, headers={
    "Content-Type": "application/json",
    "Authorization": f"Bearer {apikey}",
})

response_json = json.loads(response.text)

# 先检查是否存在错误,避免KeyError
if "error" in response_json:
    print(f"请求错误: {response_json['error']['message']}")
else:
    print(response_json['choices'][0]['text'])

方案二:使用通用completions接口,指定model参数

改用/v1/completions通用接口,仅在请求体中指定model参数(推荐这种方式,更适配OpenAI后续的模型迭代):

import json
import requests

# 替换为你的实际API密钥
apikey = "your-api-key-here"

data = {
    "prompt": "What is the meaning of life?",
    "model": "text-davinci-002",
    "max_tokens": 100  # 可选参数,控制生成内容的最大长度
}

response = requests.post("https://api.openai.com/v1/completions", json=data, headers={
    "Content-Type": "application/json",
    "Authorization": f"Bearer {apikey}",
})

response_json = json.loads(response.text)

# 先检查是否存在错误,避免KeyError
if "error" in response_json:
    print(f"请求错误: {response_json['error']['message']}")
else:
    print(response_json['choices'][0]['text'])

额外注意事项

  • 确保你的API密钥拥有访问指定模型的权限
  • 建议保留错误检查逻辑,避免后续API返回异常时再次触发KeyError
  • 若需要使用GPT-3.5或GPT-4系列模型,需更换对应的model参数(如gpt-3.5-turbo),同时接口要改为/v1/chat/completions(聊天类模型接口格式不同)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:35:20