Can you provide which error messages are you getting in return?
Jan 9, 2025
3
Level 1
Facing Issues with OpenAI Chatbot Integration in Laravel: Need Help!
I just tried to build a chatbot using the OpenAI API, but no matter what I do, it's not working for me. I copied someone else's project, but it's still not working. I've tried everything I could, but nothing seems to fix it. Here is my controller, my route, and my blade template.
my route, ialso put my api key in the .env file
Route::get('/main', [ChatbotController::class, 'index']);
Route::post('/chat', [ChatbotController::class, 'chat'])->name('chat');
my controller
<?php
namespace App\Http\Controllers;
use OpenAI\Laravel\Facades\OpenAI;
use Illuminate\Http\Request;
class chatBotController extends Controller
{
public function index(Request $request)
{
$request->validate([
'question' => 'required|string|max:255',
]);
$question = $request->input('question');
\Log::info("Question received: " . $question); // Log the incoming question
try {
$response = OpenAI::chat()->create([
'model' => 'gpt-3.5-turbo',
'messages' => [
['role' => 'system', 'content' => 'You are a helpful assistant.'],
['role' => 'user', 'content' => $question],
],
]);
\Log::info("OpenAI response: " . json_encode($response)); // Log the response from OpenAI
$answer = $response['choices'][0]['message']['content'];
return response()->json([
'answer' => $answer,
]);
} catch (\Exception $e) {
\Log::error("Error: " . $e->getMessage()); // Log any errors
return response()->json([
'answer' => 'Sorry, I could not process your request at the moment.',
], 500);
}
}
}
myblade file
<!-- resources/views/chat.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat with AI</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="chat-container">
<h1>Chat with AI</h1>
<!-- Chat Form -->
<form id="ask-form" method="post" action="{{route('chat')}}">
<label for="question">Ask something:</label>
<input type="text" id="question" name="question" placeholder="Type your question..." required>
<button type="submit">Ask</button>
</form>
<!-- Display chat history -->
<div id="chat-box">
<!-- Messages will appear here -->
</div>
</div>
<script>
// Submit the form using JavaScript (AJAX)
document.getElementById('ask-form').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent page reload
const question = document.getElementById('question').value;
const chatBox = document.getElementById('chat-box');
// Show the user's question in the chat
chatBox.innerHTML += `<div><strong>You:</strong> ${question}</div>`;
// Send the question to the Laravel backend using Axios (AJAX)
axios.post('/ask', { question })
.then(response => {
const answer = response.data.answer;
// Show the AI response in the chat
chatBox.innerHTML += `<div><strong>AI:</strong> ${answer}</div>`;
// Clear the input field
document.getElementById('question').value = '';
})
.catch(error => {
console.error('Error:', error);
chatBox.innerHTML += `<div><strong>Error:</strong> Unable to get a response from AI.</div>`;
});
});
</script>
</body>
</html>
first i run this command "composer require openai-php/laravel" then "php artisan openai:install" and i put my api key in the .env file and when i run the project it didn't work
Please or to participate in this conversation.