Laravel Image

Discover how to create a dynamic chatbot in Laravel using the power of ChatGPT and Guzzle. Learn step-by-step how to seamlessly integrate user messages from a Blade file to a controller, and effortlessly display ChatGPT’s intelligent responses. Elevate user interaction on your web application with this comprehensive guide.

Building an Intelligent Chatbot with Laravel, ChatGPT, and Guzzle

  1. Create a New Laravel Project:

Open your terminal and navigate to the directory where you want to create your project. Run the following command to create a new Laravel project:

composer create-project --prefer-dist laravel/laravel ChatGPTChatbot
  1. Install Guzzle HTTP Client:

In your terminal, navigate to your project’s root directory and install the Guzzle HTTP client:

composer require guzzlehttp/guzzle
  1. Create Routes:

Open the routes/web.php file and define the routes for sending messages and receiving responses. Add the following lines:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ChatController;

Route::get('/', [ChatController::class, 'index']);
Route::post('/send-message', [ChatController::class, 'sendMessage']);
  1. Create a Controller:

Generate a new controller named ChatController using the following command:

php artisan make:controller ChatController
  1. Implement Controller Logic:

Open app/Http/Controllers/ChatController.php and implement the logic for sending messages and receiving responses:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Client;

class ChatController extends Controller
{
    public function index()
    {
        return view('chat.index');
    }

    public function sendMessage(Request $request)
    {
        $client = new Client();
         // Make the API request
        $response = $client->post('https://api.openai.com/v1/chat/completions', [
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer YOUR_OPENAI_API_KEY',
            ],
            'json' => [
                'model' => 'gpt-3.5-turbo',
                'messages' => [
                    ['role' => 'user', 'content' => $message],
                ],
            ],
        ]);
    
        // Retrieve the API response
        $data = json_decode($response->getBody(), true);
        $chatResponse = $data['choices'][0]['message']['content'];

        return response()->json(['response' => $chatResponse]);
    }
}

Note: Replace 'YOUR_OPENAI_API_KEY' with your actual OpenAI API key.

  1. Create Blade Views:

Create a new Blade view file named index.blade.php in the resources/views/chat directory. Add the following content:

<!DOCTYPE html>
<html>
<head>
    <title>ChatGPT Chatbot</title>
</head>
<body>
    <div>
        <h1>ChatGPT Chatbot</h1>
        <div id="chat">
            <!-- Chat messages will be displayed here -->
        </div>
        <div>
            <input type="text" id="userInput" placeholder="Type your message">
            <button id="sendButton">Send</button>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#sendButton").click(function () {
                var message = $("#userInput").val();
                $.post("/send-message", { message: message }, function (data) {
                    $("#chat").append('<div>User: ' + message + '</div>');
                    $("#chat").append('<div>ChatGPT: ' + data.response + '</div>');
                    $("#userInput").val('');
                });
            });
        });
    </script>
</body>
</html>
  1. Run the Application:

Start the Laravel development server by running the following command in your terminal:

php artisan serve

Access the application in your browser at http://localhost:8000.

Type a message in the input field and click the “Send” button. You should see the user’s message and the ChatGPT response displayed in the chat area.

Remember that this is a basic implementation for demonstration purposes. In a production environment, you should consider security measures, error handling, and additional features to enhance the user experience.

Read More