I'm trying to integrate ChatGPT with my Laravel application using an AJAX request to communicate with the Laravel backend. However, I keep getting the following error in my browser console when I try to submit a message:
Error: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
I've tried to send the message to the server, where I make a request to the OpenAI API, but it seems like the response returned is not a JSON object, as expected. Instead, it looks like an HTML document starting with <!DOCTYPE....
I suspect that this issue is related to the server returning an HTML error page instead of the expected JSON response. Here are a few things I’ve considered:
Route Configuration: I’ve made sure that the route /chatgpt is correctly defined in web.php and points to the correct controller method. Still, I'm getting this error, which makes me think that maybe Laravel is returning an HTML error page (such as a 404 or 500 page) when it fails to process the request.
API Request Error: I’ve checked that the API key is correct and set properly in the .env file. The API request to OpenAI should work fine, but I still wonder if the API response is somehow malformed or if there's an issue with the request itself.
CSRF Token: I’m including the CSRF token in the AJAX request, as required by Laravel. It’s possible that this might not be sent correctly, or the CSRF token is invalid, causing a redirection to an error page instead of returning JSON.
Laravel's Error Handling: I’ve enabled logging in Laravel to capture any errors that might be happening during the API request, but nothing seems to indicate a problem.
I would appreciate any guidance on how to troubleshoot this further. Could this be an issue with Laravel’s route handling or response formatting? I’ve already checked the OpenAI API documentation to ensure I'm making the request correctly, and I’ve confirmed that the response should be JSON.
I’ve also tried logging the response body directly to see what’s being returned, and it appears that an HTML document is being returned instead of the expected JSON.
Here are some additional details about my setup:
I’m using Laravel 8.x.
The OpenAI API key is stored in .env.
I’m using a simple Guzzle HTTP client to send the request to OpenAI.
Has anyone experienced something similar? How do I ensure that Laravel correctly processes the API request and returns the expected JSON response? Any suggestions for debugging this would be very helpful!
<script>
document.getElementById('chatForm').addEventListener('submit', function (e) {
e.preventDefault();
let message = document.getElementById('message').value;
// Send the message to the Laravel controller using AJAX
fetch('/chatgpt', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': "{{csrf_token()}}",
},
body: JSON.stringify({
message: message
}),
})
.then(response => response.json())
.then(data => {
if (data.response) {
// Display the response in the textarea
document.getElementById('message').value = 'data.response';
} else {
// Display error if any
document.getElementById('chatResponse').innerText = 'Error: ' + (data.error || 'An error occurred');
}
})
.catch(error => {
document.getElementById('chatResponse').innerText = 'Error: ' + error.message;
});
});
</script>
MY CONTROLLER
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
class ChatGptController extends Controller
{
public function getChatGptResponse(Request $request)
{
$client = new Client();
$apiKey = env('OPENAI_API_KEY');
if (!$apiKey) {
return response()->json(['error' => 'API key is not set.']);
}
try {
$response = $client->post('https://api.openai.com/v1/completions', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $apiKey,
],
'json' => [
'model' => 'text-davinci-003', // Or another model you want to use
'prompt' => $request->input('message'),
'max_tokens' => 150,
'temperature' => 0.7,
],
]);
$body = $response->getBody()->getContents();
// Log the raw response to check the content
\Log::info('ChatGPT API Response: ' . $body);
// Decode the response
$body = json_decode($body, true);
// Check for the response
if (isset($body['choices'][0]['text'])) {
return response()->json(['response' => $body['choices'][0]['text']]);
} else {
return response()->json(['error' => 'Unexpected response from API.']);
}
} catch (\Exception $e) {
\Log::error('ChatGPT API error: ' . $e->getMessage());
return response()->json(['error' => 'Error connecting to the API: ' . $e->getMessage()]);
}
}
}
Define you route in the api.php file if it is meant to be used as api endpoint.
Define your open ai key in a configuration file. In the config folder create a secrets.php file that returns an array:
<?php
return [
'openai_key' => env('OPENAI_API_KEY')
];
And use it in your code like this:
config('secrets.openai_key');
if the problem is not solved with this, debug the chatgpt endpoint with postman