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>