Open AI 私钥访问显示 400 错误(Java 脚本)

问题描述 投票:0回答:1

每当我运行 JS 代码时都会收到此错误

script.js:11 POST https://api.openai.com/v1/chat/completions 400(错误请求)

由于我不是程序员(我只是想从chatgpt复制粘贴代码),请以简单的格式解释xD。感谢您的帮助。

我的代码如下:

const apiKey = "Key Here"; // Replace with your actual key
const getNewsButton = document.getElementById("getNewsButton");
const newsText = document.getElementById("newsText");

getNewsButton.addEventListener("click", async () => {
  const prompt = "Give me the latest news in German";
  const temperature = 0.7; // Adjust for desired creativity vs factuality
  const max_tokens = 100; // Adjust for desired response length

  try {
    const response = await fetch("https://api.openai.com/v1/chat/completions", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${apiKey}`,
  },
  body: JSON.stringify({
    model: "gpt-3.5-turbo", // Choose appropriate GPT-3 model
    prompt: prompt,
    max_tokens: max_tokens,
    temperature: temperature,
  }),
});
    const data = await response.json();
    const news = data.choices[0].text.replace(/<[^>]+>/g, ""); // Remove HTML tags if present

    newsText.textContent = news;
  } catch (error) {
    console.error("Error fetching news:", error);
    // Handle the error here, for example, display an error message to the user
    newsText.textContent = "An error occurred while fetching news. Please try again later.";
  }
});

我正在尝试制作一个小网页,单击按钮即可从 chatgpt 提示符中获取德语的最新新闻。 不幸的是 API 有问题,我需要进一步的帮助。

javascript openai-api api-key
1个回答
0
投票

如果您解决了当前遇到的两个问题,您的代码将开始工作。

问题 1:您使用了不正确的参数

Chat Completions API 具有

messages
参数,而不是
prompt
参数。

所以,改变这个...

body: JSON.stringify({
  model: "gpt-3.5-turbo", // Choose appropriate GPT-3 model
  prompt: prompt,
  max_tokens: max_tokens,
  temperature: temperature,
}),

...对此。

body: JSON.stringify({
  model: "gpt-3.5-turbo", // Choose appropriate GPT-3 model
  messages: [{ role: "user", content: "Say this is a test!" }],
  max_tokens: max_tokens,
  temperature: temperature,
}),

问题 2:您错误地检索响应内容

您从 Chat Completions API 获得的响应与从 Completions API 获得的响应不同。因此,响应内容检索是不同的。

所以,改变这个...

const news = data.choices[0].text.replace(/<[^>]+>/g, "");

...对此。

const news = data.choices[0].message.content.replace(/<[^>]+>/g, "");
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.