按照 OpenAI API 文档的指示操作,但这个 POST 请求似乎出了问题… 我收到了“必须提供模型参数”的错误… 请求体有什么问题吗?
try { const response = await fetch( `https://api.openai.com/v1/completions`, { body: JSON.stringify({"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}), method: "POST", headers: { Accept: "application/json", Authorization: "Bearer [API-KEY]", }, } ).then((response) => { if (response.ok) { response.json().then((json) => { terminal.echo(json); }); } }); console.log("Completed!"); } catch (err) { console.error(`Error: ${err}`) }}```
回答:
根据API 参考,有效的请求看起来像这样:
curl https://api.openai.com/v1/completions \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer YOUR_API_KEY' \ -d '{ "model": "text-davinci-003", "prompt": "Say this is a test", "max_tokens": 7, "temperature": 0}'
我们可以看到model
作为请求体中的一个属性传递。请求体必须是一个 JSON 字符串。此外,API 需要两个请求头:content-type
和authorization
。
您示例中共享的请求体是正确的。authorization
请求头也在其中。然而,您的示例中缺少content-type
头 – 显然可能是错误地被accept
头替换了。
由于缺少content-type
头,API 无法识别请求体的内容类型(可能是 json、yaml、xml 等)。因此,API 无法处理请求体,并响应说缺少模型参数。
以下示例在 Chrome 中可以工作:
await fetch( `https://api.openai.com/v1/completions`, { body: JSON.stringify({"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}), method: "POST", headers: { "content-type": "application/json", Authorization: "Bearer API_KEY_HERE", }, } ).then((response) => { if (response.ok) { response.json().then((json) => { terminal.echo(json); }); } });