Can't figure out what's wrong with code

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 !

What error are you getting?

Welcome.

Might be related to this bit?

$data = json_decode($result,true);
$totokens = $data[‘usage’][‘total_tokens’];
$mytext = $data[‘choices’][0][‘message’][‘content’];

blankz

1 Like

when i run the file in ssh and on the frontend, it returns my “no message received” error. None in error log though.

What would those new variables do?

Right. You’ll want to change that bit then…to this…

$message = $input[‘choices’][0][‘message’][‘content’];

You can find out more here…

https://platform.openai.com/docs/api-reference/chat/create

Response will look like this so you can pull out total tokens used, etc…

{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1677652288,
  "model": "gpt-3.5-turbo-0125",
  "system_fingerprint": "fp_44709d6fcb",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "\n\nHello there, how may I assist you today?",
    },
    "logprobs": null,
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 12,
    "total_tokens": 21
  }
}

And what are you doing here exactly?

3 Likes

I changed it and it’s now returning on the front end ‘Sorry, there was an error processing your message.’
and returns weirdly, nothing on the backend.

That cmd reads the raw data from the request body, sent to the php script. I’m not entirely sure if it’s necessary, but its incase the data from the api is sent as json or xml which $_POST cant parse.

Yeah, just grab the _POST data for message here. Pretty sure that’s your problem at this point.

Let us know.

As it turns out, the issue is to do with my quota. After testing the API in the backend, it returns:

"error": {
"message": "You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.",
"type": "insufficient_quota",
"param": null,
"code": "insufficient_quota"
}
}

The API I’m connecting to however, still has the free trial usage, which is at 0% as of right now.
Is this a bug, or is there something I have to do to activate it?

Is the free trial usage expired? They haven’t given it out in a long time now.

429 - You exceeded your current quota, please check your plan and billing details Cause: You have run out of credits or hit your maximum monthly spend.
Solution: Buy more credits or learn how to increase your limits.

1 Like

Just checked and yes. That makes sense now ha!

I assume I have to add my card details to get it working then right?

2 Likes