I have the following code which is giving me following error. I got the OpenAPI key using the following URL.
https://platform.openai.com/api-keys
POST https://api.openai.com/v1/chat/completions 401 (Unauthorized)
getChatResponse @ script.js:57
showTypingAnimation @ script.js:96
setTimeout (async)
handleOutgoingChat @ script.js:119
Javascript code:
const getChatResponse = async (incomingChatDiv) => {
const API_URL = “https://api.openai.com/v1/chat/completions”;
const pElement = document.createElement(“p”);
// Define the properties and data for the API request
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
},
body: JSON.stringify({
model: "text-davinci-003",
prompt: userText,
max_tokens: 2048,
temperature: 0.2,
n: 1,
stop: null
})
}
// Send POST request to API, get response and set the reponse as paragraph element text
try {
const response = await (await fetch(API_URL, requestOptions)).json();
pElement.textContent = response.choices[0].text.trim();
} catch (error) { // Add error class to the paragraph element and set error text
pElement.classList.add("error");
pElement.textContent = "Oops! Something went wrong while retrieving the response. Please try again.";
}
// Remove the typing animation, append the paragraph element and save the chats to local storage
incomingChatDiv.querySelector(".typing-animation").remove();
incomingChatDiv.querySelector(".chat-details").appendChild(pElement);
localStorage.setItem("all-chats", chatContainer.innerHTML);
chatContainer.scrollTo(0, chatContainer.scrollHeight);
}