从 OpenAI API 请求时出现 400 错误

问题描述 投票:0回答:1
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}`)

我尝试向 OpenAI API 完成 URl 发送 XHR 请求,以测试请求是否按预期正常工作

{
    "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 密钥的问题

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)

编辑

我设法通过将对象传递给

openairequest.send(JSON.stringify(payload))

来解决这个问题
javascript json ajax openai-api
1个回答
0
投票

编辑

我设法通过将对象传递给

openairequest.send(JSON.stringify(payload))
来解决这个问题 我还使用了已弃用的文本模型,因此将其更改为推荐的
gpt-3.5-turbo-instruct
我在 freecodecamp

上找到了这个解决方案
© www.soinside.com 2019 - 2024. All rights reserved.