Hello guys,
I’m trying to run this code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChatGPT Integration</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
display: flex;
flex-direction: column;
align-items: center;
}
#chat-container {
width: 400px;
border: 1px solid #ccc;
border-radius: 8px;
padding: 10px;
margin-top: 20px;
}
#chat-log {
max-height: 300px;
overflow-y: auto;
}
#user-input {
width: 70%;
padding: 5px;
margin-right: 5px;
border: 1px solid #ccc;
border-radius: 4px;
}
#send-btn {
padding: 5px 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
</head>
<body>
<div>
<h1>Chat with ChatGPT</h1>
<div id="chat-container">
<div id="chat-log"></div>
<div>
<input type="text" id="user-input" placeholder="Type your message...">
<button id="send-btn" onclick="sendMessage()">Send</button>
</div>
</div>
</div>
<script>
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
// ...rest of your server code
const apiKey = '#####';
const apiUrl = 'https://api.openai.com/v1/chat/completions';
function sendMessage() {
const userInput = document.getElementById('user-input').value;
if (!userInput) return;
appendMessage('User', userInput);
fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
prompt: userInput,
max_tokens: 150
})
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
const botReply = data.choices[0].text.trim();
appendMessage('ChatGPT', botReply);
})
.catch(error => {
console.error('Error:', error);
appendMessage('ChatGPT', 'Error: Unable to get a response from ChatGPT.');
});
// Clear input field after sending message
document.getElementById('user-input').value = '';
}
function appendMessage(sender, message) {
const chatLog = document.getElementById('chat-log');
const messageDiv = document.createElement('div');
messageDiv.innerHTML = `<strong>${sender}:</strong> ${message}`;
chatLog.appendChild(messageDiv);
// Scroll to the bottom to show the latest messages
chatLog.scrollTop = chatLog.scrollHeight;
}
</script>
</body>
</html>
However, I get no response:
I’ve looked some tutorials on youtube that had a similar approach and in the recent comments people said that the code isn’t working for them as well.
Apparently it happend after some API-update.
In the official Quickstart-tutorial https://platform.openai.com/docs/quickstart
there is information only on node.js, curl and Python… so I assume it’s not possible just to use the method I provided? (HTML and JS only).
I’m new to API and AI in general, so I don’t know what the actual problem can be. I appreciate any help, thank you!