I'm trying to integrate ChatGPT (OpenAI) into my website so that it can respond to user questions. However, I'm encountering an issue where ChatGPT doesn't provide any responses. I've provided the relevant code snippets below. I also received the API key and replaced it, but it still only returns null.
index.php:
<!DOCTYPE html>
<html>
<head>
<title>ChatGPT Example</title>
</head>
<body>
<h1>Chat with ChatGPT</h1>
<div id="chat-container">
<div id="chat-history">
<!-- Chat messages will be displayed here -->
</div>
<div id="user-input">
<input type="text" id="user-message" placeholder="Type your message..." />
<button onclick="sendMessage()">Send</button>
</div>
</div>
<script>
async function sendMessage() {
const userMessage = document.getElementById('user-message').value;
if (userMessage.trim() === '') return;
appendMessage('You', userMessage);
const response = await fetch('get_response.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: userMessage }),
});
const responseData = await response.json();
const chatGptResponse = responseData.response;
appendMessage('ChatGPT', chatGptResponse);
}
function appendMessage(sender, message) {
const chatHistory = document.getElementById('chat-history');
const messageDiv = document.createElement('div');
messageDiv.innerHTML = `<strong>${sender}:</strong> ${message}`;
chatHistory.appendChild(messageDiv);
// Scroll to the bottom of the chat history
chatHistory.scrollTop = chatHistory.scrollHeight;
}
</script>
</body>
</html>
get_response.php:
<?php
// Include your OpenAI API key
$apiKey = 'YOUR_OPENAI_API_KEY';
// Get the user's message from the request
$userMessage = $_POST['message'];
// Make a request to the OpenAI API
$apiUrl = 'https://api.openai.com/v1/chat/completions';
$data = [
'messages' => [
['role' => 'system', 'content' => 'You are a helpful assistant.'],
['role' => 'user', 'content' => $userMessage],
],
];
$options = [
'http' => [
'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data),
],
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
$decodedResponse = json_decode($response, true);
// Get the assistant's reply
$assistantReply = $decodedResponse['choices'][0]['message']['content'];
// Return the response
header('Content-Type: application/json');
echo json_encode(['response' => $assistantReply]);
?>