OpenAI GPT-3 API错误:为什么当我尝试在JavaScript代码中实现OpenAI API时会出现错误?

qvtsj1bj  于 2023-08-07  发布在  Java
关注(0)|答案(1)|浏览(137)

我试图使用HTML和JavaScript创建一个简单的网站,使用OpenAI API,用户输入查询,模型生成响应。每当我在文本框中键入一些东西并单击按钮生成一些东西时,它总是会显示错误。这是CORS限制的问题,还是我的代码的问题?
下面是我的JavaScript代码:

function generateOutput() {
    var userInput = document.getElementById("input").value;

    fetch("https://api.openai.com/v1/engines/davinci-codex/completions", {
        method:"POST",
        headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer 'MY_API'"
        },
        body: JSON.stringify({
            prompt: userInput,
            max_tokens:50,
            model: "text-davinci-003"
        }),
    })
        .then(response => {
            if (response.ok) {
                return response.json();
            }else{
                throw new Error("Error occurred while communicating with the API.")
            }
        })
        .then(data => {
            const output = data.choices[0].text.trim();
            document.getElementById("output").textContent = output;
        })  
        .catch(error => {
            document.getElementById("errorMessage").textContent = "Error occurred while communicating with the API: " + error.message;
        });
}

字符串
在这段代码中,用户可以键入一些内容,然后通过单击按钮生成响应。如果有错误,它将显示文本“Error occurred while communicating with the API.”我试过没有错误函数的情况下,它只是在生成我的请求时什么都不显示。

xqnpmsa8

xqnpmsa81#

所有Engines API endpoints都已弃用。
x1c 0d1x的数据
从此更改URL...

https://api.openai.com/v1/engines/davinci-codex/completions

字符串
...这个

https://api.openai.com/v1/completions


您可能使用ChatGPT编写了这段代码。问题是,即使是最新的OpenAI模型(即GPT-3.5和GPT-4)也使用了截至2021年6月/9月的数据进行训练,当时引擎API端点仍在使用。ChatGPT不知道,截至2023年6月,它应该建议您使用Completions API endpoint而不是Engines API端点。
试试这个:

function generateOutput() {
  var userInput = document.getElementById("input").value;

  fetch("https://api.openai.com/v1/completions", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer 'MY_API'"
      },
      body: JSON.stringify({
        prompt: userInput,
        max_tokens: 50,
        model: "text-davinci-003"
      }),
    })
    .then(response => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error("Error occurred while communicating with the API.")
      }
    })
    .then(data => {
      const output = data.choices[0].text.trim();
      document.getElementById("output").textContent = output;
    })
    .catch(error => {
      document.getElementById("errorMessage").textContent = "Error occurred while communicating with the API: " + error.message;
    });
}

相关问题