The error I am getting is: “{
“error”: {
“message”: “You didn’t provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you’re accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.”,
“type”: “invalid_request_error”,
“param”: null,
“code”: null
}
}”
My code is:
const chatInput = document.querySelector("#chat-input");
const sendButton = document.querySelector("#send-btn");
const chatContainer = document.querySelector(".chat-container");
let userText = null;
const API_KEY = "sk-proj-ddddddddddddddddddddddBlbkFJ2ogLhP4plGxAUxj2-lLf6pTW_XmiZo_Pyx3AUujUkWezQmLiwDo2BB3J4A";
createElement = (html, className) => {
const chatDiv = document.createElement("div");
chatDiv.classList.add("chat", className);
chatDiv.innerHTML = html;
return chatDiv;
}
const getChatResponse = async () => {
const API_KEY = "sk-proj-dddddddddddddddddddddddddddddddddddddddddddBlbkFJ2ogLhP4plGxAUxj2-lLf6pTW_XmiZo_Pyx3AUujUkWezQmLiwDo2BB3J4A";
const API_URL = "https://api.openai.com/v1/completions";
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
})
}
try {
const response = await (await fetch(API_URL, requestOptions)).json();
console.log(response);
} catch(error) {
console.log(error)
}
}
const showTypingAnimation = () => {
const html = `<div class="chat-content">
<div class="chat-details">
<img src="images/chatbot.jpg" alt="chatbot-img">
<div class="typing-animation">
<div class="typing-dot" style="--delay: 0.2s"></div>
<div class="typing-dot" style="--delay: 0.3s"></div>
<div class="typing-dot" style="--delay: 0.4s"></div>
</div>
</div>
<span class="material-symbols-rounded">
content_copy
</span>
</div>`;
const outgoingChatDiv = createElement(html, "incoming");
chatContainer.appendChild(outgoingChatDiv);
getChatResponse();
}
const handleOutgoingChat = () => {
userText = chatInput.value.trim();
const html = ` <div class="chat-content">
<div class="chat-details">
<img src="images/chatbot.jpg" alt="user-img">
<p>${userText}</p>
</div>
</div>`;
const outgoingChatDiv = createElement(html, "outgoing");
chatContainer.appendChild(outgoingChatDiv);
setTimeout(showTypingAnimation, 500)
}
sendButton.addEventListener("click", handleOutgoingChat);