I’m trying to write a chatbox with chatgpt api responses. Can anyone spot what’s wrong with my code?
front end:
<!DOCTYPE html>
<!--chatbox-->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chat</title>
<link rel="stylesheet" href="assets/css/styles.css">
<script src="assets/js/chatbox.js"></script>
</head>
<body>
<div class="ai-chat-container">
<div id="chatbox" class="chatbox">
<!-- Messages will be added here dynamically -->
</div>
<input type="text" id="userInput" placeholder="Type your message here..." autocomplete="off">
<button onclick="sendMessage()">Send</button>
</div>
</body>
</html>
.js
document.getElementById('userInput').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
e.preventDefault(); // Prevent the default action for the Enter key in a form
sendMessage();
}
});
function sendMessage() {
let userText = document.getElementById('userInput').value;
if (userText.trim() === '') return; // Don't send empty messages
displayMessage(userText, 'user'); // Display the user's message in the chatbox
document.getElementById('userInput').value = ''; // Clear the input field after sending
// Send the user's message to the php Backend
fetch('../../ChatGPT.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: userText }),
})
.then(response => response.json()) // Parse the JSON response from the server
.then(data => {
// Display the chatbot's (server's) response in the chatbox
displayMessage(data.response, 'ai');
})
.catch((error) => {
console.error('Error:', error);
displayMessage("Sorry, there was an error processing your message.", 'ai');
});
}
function displayMessage(message, sender) {
let chatbox = document.getElementById('chatbox');
let messageElement = document.createElement('div');
messageElement.classList.add('message', sender); // Styling apply
messageElement.textContent = message;
chatbox.appendChild(messageElement);
chatbox.scrollTop = chatbox.scrollHeight; // Auto-scroll
}
Backend
<?php
$api_key = "X";
header("Content-Type: application/json");
function sendMessageToChatGPT($message, $api_key) {
$ch = curl_init("https://api.openai.com/v1/chat/completions");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
"Authorization: Bearer $api_key",
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
"model" => "gpt-4-0613",
"messages" => [
[
"role" => "user",
"content" => $message
]
],
]));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
error_log("cURL Error #: " . $err);
return null;
} else {
$decodedResponse = json_decode($response, true);
if (json_last_error() === JSON_ERROR_NONE) {
return $decodedResponse;
} else {
error_log("JSON Decode Error: " . json_last_error_msg());
return null;
}
}
}
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, true);
$message = $input['message'] ?? '';
if (!empty($message)) {
$response = sendMessageToChatGPT($message, $api_key);
if ($response !== null && isset($response["choices"][0]["message"]["content"])) {
$chatGPTResponse = $response["choices"][0]["message"]["content"];
} else {
$chatGPTResponse = "Sorry, I couldn't understand that.";
}
echo json_encode(['response' => $chatGPTResponse]);
} else {
echo json_encode(['response' => 'No message received.']);
}
If anyone could look over my code and see the error I’d be appreciative !