Chrome扩展调用ChatGPT 3.5 API报错:已配置model仍提示需提供该参数
问题解决:调用ChatGPT 3.5 API提示缺少model参数的修复方案
你遇到的问题出在请求体格式和参数匹配错误,具体有三个关键问题:
- 端点与请求体不匹配:你用的是
/v1/chat/completions(对话补全端点),却使用了文本补全端点的prompt参数,这个端点要求用messages数组传递对话内容,而非单独的prompt字段。 - 参数嵌套错误:你把包含model的
prompt对象嵌套到了body的prompt属性里,导致API无法识别到顶层的model参数。 - 参数名称错误:
max_completions是文本补全端点的参数,对话补全端点对应的参数是n。
修正后的代码如下:
// Define the API key const API_KEY = "API KEY"; // Define the endpoint URL const endpointUrl = "https://api.openai.com/v1/chat/completions"; // Define the headers const headers = { "Content-Type": "application/json", Authorization: `Bearer ${API_KEY}`, }; // Define the number of completions to return const completionCount = 1; // Define the request body (符合chat completions的格式要求) const requestBody = { model: "gpt-3.5-turbo", messages: [{"role": "user", "content": "Hello, world!"}], // 替换原prompt字段为messages数组 temperature: 0.5, n: completionCount // 替换max_completions为n }; // Send a POST request to the endpoint fetch(endpointUrl, { method: "POST", headers, body: JSON.stringify(requestBody), // 直接传入正确的请求体 }) .then((response) => response.json()) .then((data) => { console.log(data); }) .catch((error) => { console.error(error); });
修改点说明:
- 去掉参数嵌套,将包含model的请求体直接传入
JSON.stringify - 用
messages数组替换原prompt字段,按照对话补全端点的标准格式传递内容 - 将
max_completions替换为对话补全对应的n参数
内容的提问来源于stack exchange,提问作者Russell Hertel
相关产品推荐
相关产品推荐

