Building a Chatbot using ChatGPT and Laravel

In our previous tutorial, we have expalined to Make ChatBot using ChatGPT and PHP. In this tutorial, we are going to develop Chatbot using ChatGPT and Laravel.

ChatGPT is a chatbot developed by OpenAI. It is a language model that can generate human like responses to text input. We can use OpenAI to build ChatBot to support natural language conversation with users.

In this tutorial, we will explain step by step to integrate OpenAi with Laravel and develop a ChatBot. So let’s proceed with it.

1. Create Laravel Project

First we will create Laravel project laravel-openai-chatbot by running below command:

composer create-project laravel/laravel laravel-openai-chatbot

2. Get OpenAi Key and Define it

In order to use ChaGPT in your application, you first need to get API Key from OpenAI.


Then open the .env file in the root directory of project and addd the below line:

OPENAI_API_KEY=YOUR_API_KEY

you need to replace YOUR_API_KEY with the API key obtained from OpenAI.

3. Installing OpenAI Library and Publishing

We also need to install the OpenAI library to use ChatGPT in our project. We will run the below command to install this library.

composer require openai/api

This command will install the OpenAI library in your Laravel project.

We also need to publish the configuration file to start using the the OpenAI library in our project. We will run the below command to publish the configuration.


php artisan vendor:publish --provider="OpenAI\OpenAIServiceProvider"

4. Create ChaBot Controller

We will create controller ChatBotControllerto interact OpenAI and handle form submit functionality. We will run below command to create controller.

php artisan make:controller ChatBotController

It will create a new file named ChatBotController.php in the app/Http/Controllers directory of project.

5. Implement ChaBot Controller

We will open controller file ChatBotController.php and implement to use OpenAI to interact with ChatGPT. We will define index() method and implement to handle form submit to make request to ChatGPT with user input. We will return repsonse with user input question and response.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use OpenAI\OpenAI;

class ChatBotController extends Controller
{
    protected $openai;

    public function __construct()
    {
        $this->openai = new OpenAI();
    }

    public function index(Request $request)
    {
        $request->validate([
            'question' => 'required',
        ]);

        $question = $request->input('question');

        $response = $this->openai->chatCompletion([
            'model' => 'gpt-3.5-turbo',
            'messages' => [
                ['role' => 'system', 'content' => 'You are a helpful assistant.'],
                ['role' => 'user', 'content' => $question],
            ],
        ]);

        $answer = $response['choices'][0]['message']['content'];

        return response()->json([
            'question' => $question,
            'answer' => $answer,
        ]);
    }
}

6. Creating ChatBot Form Template

We will also create template file in chatbot.blade.php and create form to allow user’s to enter questions to get answer from ChatGPT.

<form id="ask" method="post" action="/ask">
    <h2>ChatBot using ChatGPT andLaravel</h2>
    <div>
        <label for="question">Question:</label>
        <input type="text" id="question" name="question">
    </div>
    <div id="error"></div>
    <button type="submit">Submit</button>
</form>
<div id="chat"></div>

7. Creating and Updating Route

We need to create and update the route to access the controllers. So we will oepn the routes/web.php file in the root directory of project and replace the existing content with the below code:


<?php

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

Route::get('/', function () {
    return view('chatbot');
});

Route::post('/ask', [ChatBotController::class, 'index']);

Here in above, we have defined two routes to GET route for the homepage that returns the chatbot.blade.php view. We will also handle a POST route for the form submission that calls the index method.

8. Running Project

Now we have implement chatGPT in our application. Now we will run our project using below command.

php artisan serve

The project will be available on the development server on http://127.0.0.1:8000

Leave a Reply

Your email address will not be published. Required fields are marked *