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