Having trouble communicating with OpenAI API

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);

}

Heya! Welcome to our growing dev community!

A 401 could be…

401 - Invalid Authentication Cause: Invalid Authentication
Solution: Ensure the correct API key and requesting organization are being used.
401 - Incorrect API key provided Cause: The requesting API key is not correct.
Solution: Ensure the API key used is correct, clear your browser cache, or generate a new one.
401 - You must be a member of an organization to use the API Cause: Your account is not part of an organization.
Solution: Contact us to get added to a new organization or ask your organization manager to invite you to an organization.

More info here in the docs

ETA:

        model: "text-davinci-003",

No longer exists either, so you’re using old code maybe? If so, check out the Quickstart Guide to get up and running…

1 Like

You should also be very careful here.

This appears to be client code and you should not be deploying code into production that exposes your API key to everyone.

Make sure that ultimately you proxy this call in some way before you go live so the client is never aware of your key.

I suggest you make sure someone with experience reviews your setup end to end before you deploy it.

1 Like