【问题标题】:Error 400 when using GPT API (in JavaScript)使用 GPT API 时出现错误 400(在 JavaScript 中)
【发布时间】:2023-02-04 15:08:58
【问题描述】:

当我尝试使用 GPT API 运行我的非常基本的聊天机器人时,我不断收到 400 错误: error

附件是我的代码;我在使用 API 密钥时做错了什么吗?

const chatHistoryContent = document.querySelector("#chat-history-content");
const chatMessageInput = document.querySelector("#chat-message-input");
const chatMessageSubmit = document.querySelector("#chat-message-submit");



chatMessageSubmit.addEventListener("click", async function () {
    const message = chatMessageInput.value;
    chatMessageInput.value = "";

    // Add the user's message to the chat history
    const userMessageDiv = document.createElement("div");
    userMessageDiv.innerHTML = `You: ${message}`;
    chatHistoryContent.appendChild(userMessageDiv);

    // Use the OpenAI GPT-3 API to get a response from the chatbot
    const response = await getResponseFromAPI(message);

    // Add the chatbot's response to the chat history
    const chatbotMessageDiv = document.createElement("div");
    chatbotMessageDiv.innerHTML = `Max: ${response}`;
    chatHistoryContent.appendChild(chatbotMessageDiv);
});

async function getResponseFromAPI(message) {

    const apiKey = "sk-myapikey";
    const endpoint = `https://api.openai.com/v1/engines/davinci/jobs`;

    const response = await fetch(endpoint, {
        method: "POST",
        headers: {
            "Content-Type": `application/json`,
            "Authorization": `Bearer ${apiKey}`,
        },
        body: JSON.stringify({
            model: "text-davinci-003",
            prompt: "test prompt", 
            temperature: 0.5,
            max_tokens: 512,
            top_p: 1,
            frequency_penalty: 0,
            presence_penalty: 0,
        })
    });

    const data = await response.json();
    return data.choices[0].text;
}

谢谢

我曾尝试咨询许多网站以查看解决方案,但没有成功。

【问题讨论】:

标签: javascript error-handling openai gpt-3


【解决方案1】:

400 (Bad Request) 错误代码通常表示客户端请求的数据不正确。所以是的,必须与您的身份验证标头/请求正文有关。通常响应包含一个原因,请尝试打印响应文本(在尝试获取 json 输出之前),例如

console.log(response.text());

或者只检查 Dev Console 中的网络选项卡

【讨论】:

    猜你喜欢
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多