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/jsonrnAuthorization: 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]);
?>
2
Answers
In your PHP code, I see two possible issues:
You are using
$_POST['message']
to get the user’s message. However, thefetch()
call in your JavaScript code is sending the user’s message as JSON data.$_POST
will not be able to handle this correctly. Instead, you should usephp://input
to read the raw data from the request.You are using the
file_get_contents()
function to send a POST request. This function may not support all types of HTTP requests properly, so you might want to use cURL instead.Here’s how you can modify your PHP code:
This code uses the cURL extension to send the POST request to the OpenAI API. You may need to install this extension if it’s not already installed and enabled on your server.
Please note that this code doesn’t handle errors in a production-ready way. For example, if the API request fails for some reason, the PHP script will die and not return a proper JSON response. In a real-world application, you’d want to handle these error cases more gracefully. Also, you’d want to handle the case where the user’s message is not provided in the request.
You should include one of the ChatGPT models in your data for this to work. I just modified your $data to use the GPT-3.5-Turbo model as follows.