调用OpenAI API遇400错误,排查后通过正确传递payload解决
问题:使用XMLHttpRequest调用OpenAI Completions接口遇到的问题
问题背景
我尝试用XMLHttpRequest向OpenAI API的completions接口发送请求,测试接口是否能正常工作。
初始代码
var openairequest = new XMLHttpRequest(); const payload = ({ "model": "text-davinci-003", "prompt": "say this is a test" }); console.log(payload) openairequest.open("POST",`https://api.openai.com/v1/completions?data=${encodeURIComponent(JSON.stringify(payload))}`) openairequest.setRequestHeader("Content-Type", "application/json"); openairequest.setRequestHeader("Authorization",`Bearer ${open_ai_key}`)
收到的错误响应
{ "error": { "message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.", "type": "invalid_request_error", "param": null, "code": null } }
我很困惑,明明已经传入了JSON对象,却还是收到未提供API密钥的错误。
第一次修改
后来发现自己漏写了发送请求的send()方法,补上后代码如下,但还是搞不懂为什么Authorization请求头里的API密钥不生效:
var open_ai_key = "MY KEY" var openairequest = new XMLHttpRequest(); const payload = ({ "model": "text-davinci-003", "prompt": "say this is a test" }); openairequest.open("POST",`https://api.openai.com/v1/completions?data=${encodeURIComponent(JSON.stringify(payload))}`) openairequest.setRequestHeader("Content-Type", "application/json"); openairequest.setRequestHeader("Authorization",`Bearer ${open_ai_key}`) openairequest.send() console.log(openairequest)
最终解决
最后我通过将字符串化后的payload传入send()方法解决了问题,关键修改是:
openairequest.send(JSON.stringify(payload))
内容的提问来源于stack exchange,提问作者elijah
相关产品推荐
相关产品推荐

