sid
sid

Reputation: 1

OpenAI API error: How do I fix error 400 when using the Chat Completions API?

I am trying to make a small webpage where a button click would allow me to fetch the latest news in German from the OpenAI API.

Unfortunately, there's something wrong with my API calls which I want further help with. I am getting the following error whenever I run JS code:

script.js:11 POST https://api.openai.com/v1/chat/completions 400 (Bad Request)

I am not a programmer. I am just trying to copy and paste code from ChatGPT. Kindly explain in an easy format. I appreciate your help.

Code:

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.";
  }
});

Upvotes: 0

Views: 386

Answers (1)

Rok Benko
Rok Benko

Reputation: 23030

Your code will start working if you solve both problems you currently have with it.

Problem 1: You're using an incorrect parameter

The Chat Completions API has the messages parameter instead of the prompt parameter.

So, change this...

body: JSON.stringify({
  model: "gpt-3.5-turbo",
  prompt: prompt,
  max_tokens: max_tokens,
  temperature: temperature,
}),

...to this.

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

Problem 2: You're extracting the response incorrectly

The response you get from the Chat Completions API is different than the response from the Completions API. Consequently, the response extraction is different.

So, change this...

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

...to this.

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

Upvotes: 0

Related Questions