ChatGPT error 401 : Incorrect API key provided?

Hi, I’ve written the following simple HTML web app to test the API, but no matter what I send, the console returns a 401 error. Am I not accessing the API properly? I’ve tried it with over 12 fresh keys, and still no luck after tweaking the code for ages.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pirate Chat</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
        }

        #chat-window {
            width: 400px;
            margin: 20px auto;
            border: 1px solid #ccc;
            border-radius: 5px;
            overflow: hidden;
        }

        #chat-box {
            height: 300px;
            overflow-y: scroll;
            padding: 10px;
            background-color: #fff;
        }

        #user-input {
            width: calc(100% - 20px);
            margin: 0;
            padding: 10px;
            border: none;
            border-top: 1px solid #ccc;
            font-size: 16px;
        }

        #send-btn {
            width: 100%;
            padding: 10px;
            background-color: #007bff;
            color: #fff;
            border: none;
            cursor: pointer;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div id="chat-window">
        <div id="chat-box"></div>
        <input type="text" id="user-input" placeholder="Type your message...">
        <button id="send-btn">Send</button>
    </div>

    <script>
        const chatBox = document.getElementById('chat-box');
        const userInput = document.getElementById('user-input');
        const sendBtn = document.getElementById('send-btn');

        sendBtn.addEventListener('click', () => {
            const userMessage = userInput.value.trim();
            if (userMessage !== '') {
                appendMessage('You', userMessage);
                userInput.value = '';
                sendMessageToPirate(userMessage);
            }
        });

        function appendMessage(sender, message) {
            const messageElement = document.createElement('div');
            messageElement.innerHTML = `<strong>${sender}:</strong> ${message}`;
            chatBox.appendChild(messageElement);
            chatBox.scrollTop = chatBox.scrollHeight;
        }

        async function sendMessageToPirate(message) {
            const apiKey = 'YOUR_API_KEY_PLACEHOLDER';
            const endpoint = 'https://api.openai.com/v1/engines/davinci/completions';
            const headers = {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            };
            const data = {
                prompt: message,
                max_tokens: 150,
                temperature: 0.5,
                top_p: 1,
                n: 1,
                stop: ['\n']
            };

            try {
                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify(data)
                });

                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }

                const responseData = await response.json();
                const pirateResponse = responseData.choices[0].text.trim();
                appendMessage('Pirate', pirateResponse);
            } catch (error) {
                console.error('Error:', error);
            }
        }
    </script>
</body>
</html>

Welcome to the community!

Did chatgpt write that code for you?

I hope you don’t intend to publish it to the internet like that!

All that said, you’re trying to talk to an ancient endpoint. Consider referring to the API documentation for more updated information: https://platform.openai.com/docs/api-reference/completions/create?lang=curl

2 Likes

Hi, I updated it with the new endpoints, but now it results in a 429 error.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pirate Chat</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
        }

        #chat-window {
            width: 400px;
            margin: 20px auto;
            border: 1px solid #ccc;
            border-radius: 5px;
            overflow: hidden;
        }

        #chat-box {
            height: 300px;
            overflow-y: scroll;
            padding: 10px;
            background-color: #fff;
        }

        #user-input {
            width: calc(100% - 20px);
            margin: 0;
            padding: 10px;
            border: none;
            border-top: 1px solid #ccc;
            font-size: 16px;
        }

        #send-btn {
            width: 100%;
            padding: 10px;
            background-color: #007bff;
            color: #fff;
            border: none;
            cursor: pointer;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div id="chat-window">
        <div id="chat-box"></div>
        <input type="text" id="user-input" placeholder="Type your message...">
        <button id="send-btn">Send</button>
    </div>

    <script>
        const chatBox = document.getElementById('chat-box');
        const userInput = document.getElementById('user-input');
        const sendBtn = document.getElementById('send-btn');
        let retryCount = 0;

        sendBtn.addEventListener('click', () => {
            const userMessage = userInput.value.trim();
            if (userMessage !== '') {
                appendMessage('You', userMessage);
                userInput.value = '';
                sendMessageToPirate(userMessage);
            }
        });

        function appendMessage(sender, message) {
            const messageElement = document.createElement('div');
            messageElement.innerHTML = `<strong>${sender}:</strong> ${message}`;
            chatBox.appendChild(messageElement);
            chatBox.scrollTop = chatBox.scrollHeight;
        }

        async function sendMessageToPirate(message) {
            // Replace 'sk-' with your actual API key
            const apiKey = 'YOUR_API_KEY';
            const endpoint = 'https://api.openai.com/v1/completions';
            const headers = {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            };
            const data = {
                "model": "gpt-3.5-turbo-instruct",
                "prompt": message,
                "max_tokens": 7,
                "temperature": 0
            };

            try {
                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify(data)
                });

                if (!response.ok) {
                    if (response.status === 429) {
                        // Implement exponential backoff
                        const delay = Math.pow(2, retryCount) * 1000;
                        retryCount++;
                        console.log(`Retrying in ${delay}ms`);
                        setTimeout(() => sendMessageToPirate(message), delay);
                    } else {
                        throw new Error('Network response was not ok');
                    }
                } else {
                    retryCount = 0; // Reset retry count on successful request
                    const responseData = await response.json();
                    const pirateResponse = responseData.choices[0].text.trim();
                    appendMessage('Pirate', pirateResponse);
                }
            } catch (error) {
                console.error('Error:', error);
            }
        }
    </script>
</body>
</html>

Do you have credit card attached? Billing details filled out? Credits in your account?

Check your rate-limits too, especially if you’re FREE tier…

Sorry, how is this relevant to my issue? Please elaborate.

results in a 429 error.

Visit https://platform.openai.com/account/billing/overview

More info…

https://help.openai.com/en/articles/6891831-error-code-429-you-exceeded-your-current-quota-please-check-your-plan-and-billing-details