skip to Main Content

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


  1. In your PHP code, I see two possible issues:

    1. You are using $_POST['message'] to get the user’s message. However, the fetch() 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 use php://input to read the raw data from the request.

    2. 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:

    <?php
    // Include your OpenAI API key
    $apiKey = 'YOUR_OPENAI_API_KEY';
    
    // Get the user's message from the request
    $requestBody = file_get_contents('php://input');
    $requestData = json_decode($requestBody, true);
    $userMessage = $requestData['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],
        ],
    ];
    
    // Set up cURL options
    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json",
        "Authorization: Bearer $apiKey",
    ]);
    
    // Send the request
    $response = curl_exec($ch);
    if (!$response) {
        die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
    }
    
    // Close cURL session handle
    curl_close($ch);
    
    // Decode the response
    $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]);
    ?>
    

    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.

    Login or Signup to reply.
  2. 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.

    $data = [
     'messages' => [
        ['role' => 'system', 'content' => 'You are a helpful assistant.'],
        ['role' => 'user', 'content' => $userMessage],
      ],
      "model" => "gpt-3.5-turbo",
    ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search