Build a ChatGPT Messenger App with Laravel

Find AI Tools in second

Find AI Tools
No difficulty
No complicated process
Find ai tools

Build a ChatGPT Messenger App with Laravel

Table of Contents

  1. Introduction
  2. Setting up the Laravel project
  3. Adding the OpenAI API key
  4. Creating the OpenAI configuration file
  5. Building the ChatGPT controller
  6. Creating the view for the messaging interface
  7. Setting up the routing
  8. Styling the chat box interface
  9. Implementing the chat functionality using jQuery and AJAX
  10. Making API requests to OpenAI ChatGPT
  11. Displaying the chat responses
  12. Testing the end-to-end chatbot functionality
  13. Conclusion

1. Introduction

In this article, we will walk through the process of creating a chatbot using Laravel and OpenAI's ChatGPT. We will start by setting up the Laravel project, adding the OpenAI API Key, and creating the necessary configuration files. Then, we will build the ChatGPT controller and Create the view for the messaging interface. Next, we will set up the routing and style the chat box interface. We will implement the chat functionality using jQuery and AJAX, and make API requests to OpenAI ChatGPT. Finally, we will display the chat responses and test the end-to-end chatbot functionality.

2. Setting up the Laravel project

Before we start building the chatbot, we need to set up a Laravel project. This assumes that You have basic knowledge of Laravel and have PHP and Composer installed locally. To create the project, open your terminal and navigate to the desired directory. Then, run the following command to create a new Laravel project:

laravel new chatbot

Once the project is created, navigate to the project directory by running:

cd chatbot

3. Adding the OpenAI API key

To integrate with the OpenAI ChatGPT API, we need to add the API key to our Laravel project. First, locate the .env.example file in the project's root directory. Rename this file to .env. Open the .env file and add the following line:

OPENAI_API_KEY=your_openai_api_key

Replace your_openai_api_key with your actual OpenAI API key. Make sure to keep this key secure and do not share it with anyone.

4. Creating the OpenAI configuration file

In order to reference the OpenAI API key in our code, we need to create a configuration file. Create a new file called openai.php in the config directory of your Laravel project. Open the openai.php file and add the following code:

<?php

return [
    'api_key' => env('OPENAI_API_KEY'),
];

This configuration file will allow us to access the OpenAI API key using config('openai.api_key') in our code.

5. Building the ChatGPT controller

Next, let's create the ChatGPT controller. Run the following command in your terminal to generate a new controller:

php artisan make:controller ChatGPTController

This will create a new file called ChatGPTController.php in the app\Http\Controllers directory. Open the ChatGPTController.php file and replace the existing code with the following:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class ChatGPTController extends Controller
{
    public function index()
    {
        return view('chatgpt.index');
    }

    public function ask(Request $request)
    {
        $prompt = $request->input('prompt');

        $response = $this->askChatGPT($prompt);

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

    private function askChatGPT($prompt)
    {
        $apiKey = config('openai.api_key');

        $response = Http::withoutVerifying()->withHeaders([
            'Authorization' => 'Bearer ' . $apiKey,
            'Content-Type' => 'application/json',
        ])->post('https://api.openai.com/v1/chat/completions', [
            'model' => 'gpt-3.5-turbo',
            'messages' => [['role' => 'user', 'content' => $prompt]],
            'max_tokens' => 100,
        ]);

        $choices = $response->json('choices');

        if (!empty($choices)) {
            return $choices[0]['message']['content'];
        }

        return '';
    }
}

In this controller, we have two methods: index() and ask(). The index() method returns the view for the messaging interface. The ask() method handles the request when the user submits a message and makes a call to the OpenAI ChatGPT API.

6. Creating the view for the messaging interface

Now, let's create the view for the messaging interface. Create a new file called index.blade.php in the resources\views\chatgpt directory. Open the index.blade.php file and add the following code:

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">ChatGPT Messaging</div>

                    <div class="card-body">
                        <div id="chat-box">
                            <div id="user-message-template" style="display: none;">
                                <div class="message-box user-message">
                                    <div class="message-box-text"></div>
                                </div>
                            </div>

                            <div id="chatgpt-message-template" style="display: none;">
                                <div class="message-box chatgpt-message">
                                    <div class="message-box-text"></div>
                                </div>
                            </div>
                        </div>

                        <form id="ask-chatgpt-form" class="mt-3">
                            @csrf

                            <div class="input-group mb-3">
                                <textarea class="form-control" name="prompt" placeholder="Type your message here..." rows="3" required></textarea>
                            </div>

                            <div class="text-center">
                                <button type="submit" class="btn btn-primary">Send</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

This view contains the HTML markup for the messaging interface. It includes a chat box container, user and chat GPT message templates, and a form for submitting messages.

7. Setting up the routing

To set up the routing for the chatbot, open the routes\web.php file and add the following code:

use App\Http\Controllers\ChatGPTController;

Route::get('/chatgpt', [ChatGPTController::class, 'index'])->name('chatgpt.index');
Route::post('/chatgpt/ask', [ChatGPTController::class, 'ask'])->name('chatgpt.ask');

These routes will direct the GET requests to /chatgpt to the index() method in the ChatGPTController, and the POST requests to /chatgpt/ask to the ask() method in the ChatGPTController.

8. Styling the chat box interface

To style the chat box interface, open the resources\sass\app.scss file and add the following code:

#chat-box {
    height: 300px;
    overflow-y: scroll;
}

.message-box {
    margin-bottom: 10px;
    padding: 10px;
    border-radius: 5px;
}

.user-message {
    background-color: #eee;
    float: right;
}

.chatgpt-message {
    background-color: #d4e9fd;
    float: left;
}

Save the file and compile the Sass to CSS by running the following command in your terminal:

npm run dev

This will compile the Sass file into a CSS file and Apply the specified styles to the chat box interface.

9. Implementing the chat functionality using jQuery and AJAX

To implement the chat functionality using jQuery and AJAX, open the resources\js\app.js file and add the following code:

$(document).on('submit', '#ask-chatgpt-form', function(event) {
    event.preventDefault();

    var form = $(this);
    var formData = form.serialize();

    form[0].reset();

    generateChatBotMessage('user', formData);

    $.ajax({
        url: form.attr('action'),
        type: 'POST',
        data: formData,
        dataType: 'json',
        success: function(response) {
            generateChatBotMessage('chatgpt', response.message);
        }
    });
});

function generateChatBotMessage(role, text) {
    var templateSelector = role === 'chatgpt' ? '#chatgpt-message-template' : '#user-message-template';
    var templateHTML = $(templateSelector).html();
    var messageBox = $(templateHTML);

    messageBox.find('.message-box-text').text(text);

    $('#chat-box').append(messageBox);
    $("#chat-box").scrollTop($("#chat-box")[0].scrollHeight);
}

This code handles the form submission using jQuery's submit event. It prevents the default form submission behavior, resets the form, and generates a chat message. It then sends an AJAX request to the /chatgpt/ask endpoint and generates a chatbot message Based on the response from the API.

10. Making API requests to OpenAI ChatGPT

To make API requests to OpenAI ChatGPT, we need to update the askChatGPT function in the ChatGPTController.php file. Open the ChatGPTController.php file and replace the askChatGPT function with the following code:

private function askChatGPT($prompt)
{
    $apiKey = config('openai.api_key');

    $response = Http::withoutVerifying()->withHeaders([
        'Authorization' => 'Bearer ' . $apiKey,
        'Content-Type' => 'application/json',
    ])->post('https://api.openai.com/v1/chat/completions', [
        'model' => 'gpt-3.5-turbo',
        'messages' => [['role' => 'user', 'content' => $prompt]],
        'max_tokens' => 100,
    ]);

    $choices = $response->json('choices');

    if (!empty($choices)) {
        return $choices[0]['message']['content'];
    }

    return '';
}

This code sends a POST request to the OpenAI ChatGPT API with the user's prompt and retrieves the response. It then returns the content of the first message from the choices array in the API response.

11. Displaying the chat responses

To display the chat responses, open the index.blade.php file and add the following code inside the <script> tag at the end of the file:

generateChatBotMessage('chatgpt', 'Hello! How can I assist you today?');

This code generates an initial chatbot message when the page loads, welcoming the user and asking them how they can be assisted.

12. Testing the end-to-end chatbot functionality

To test the end-to-end chatbot functionality, start the Laravel development server by running the following command in your terminal:

php artisan serve

Open your browser and navigate to http://localhost:8000/chatgpt. You should see the chatbox interface. Type your message in the text area and hit the send button. The chatbot will respond with an appropriate answer.

13. Conclusion

In this article, we have covered the step-by-step process of creating a chatbot using Laravel and OpenAI's ChatGPT. We started by setting up the Laravel project, adding the OpenAI API key, and creating the necessary configuration files. Then, we built the ChatGPT controller and created the view for the messaging interface. We set up the routing and styled the chat box interface. We implemented the chat functionality using jQuery and AJAX, and made API requests to OpenAI ChatGPT. Finally, we displayed the chat responses and tested the end-to-end chatbot functionality.

Highlights

  • Create a chatbot using Laravel and OpenAI's ChatGPT.
  • Set up the Laravel project and add the OpenAI API key.
  • Build the ChatGPT controller and create the view for the messaging interface.
  • Implement the chat functionality using jQuery and AJAX.
  • Make API requests to OpenAI ChatGPT and display the chat responses.
  • Test the end-to-end chatbot functionality.

FAQ

Q: How can I get the OpenAI API key? A: You can obtain the OpenAI API key by signing up for an OpenAI account and following the instructions provided by OpenAI to generate an API key.

Q: Can I customize the styling of the chatbox interface? A: Yes, you can customize the styling of the chatbox interface by modifying the CSS styles in the app.scss file.

Most people like

Are you spending too much time looking for ai tools?
App rating
4.9
AI Tools
100k+
Trusted Users
5000+
WHY YOU SHOULD CHOOSE TOOLIFY

TOOLIFY is the best ai tool source.

Browse More Content