Laravel 10 - OpenAI ChatGPT

Touseef Afridi
12 Sep 24

Laravel 10 - OpenAI ChatGPT

In this tutorial, we will integrate OpenAI's ChatGPT into Laravel 10, enabling powerful AI-driven conversations to enhance user interactions and automate responses efficiently.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide takes you through building a simple ChatGPT integration into a Laravel application. We start by creating a fresh Laravel project, setting up the front-end with Vite, and installing the openai-php/laravel package. After configuring OpenAI's API settings, we create a view to allow users to submit questions, a controller to handle OpenAI communication, and define the necessary routes. You’ll learn how to set up AJAX form submissions for a seamless chat experience without page reloads. Finally, we'll connect everything, run the Laravel server, and test the application to interact with ChatGPT directly from your browser. By the end, you’ll have a fully functional mini-ChatGPT built into your Laravel app, ready for real-world use or further customization.

Step # 1 : Create a Fresh Laravel Project.

To begin, let's set up a new Laravel project. You can choose either the Laravel installer or Composer based on your preference. If you have Laravel installed globally, simply run.
laravel new chatgpt
Alternatively, if you prefer using Composer, run.
composer create-project laravel/laravel --prefer-dist chatgpt
This will generate a fresh Laravel project named chatgpt, which will serve as the foundation for your application. Composer will automatically download and configure all necessary files and directories, ensuring your environment is ready for development. Once the installation is complete, you can confidently proceed to the next steps.

Step # 2 : Access the project.

First, open a terminal (such as Git Bash) and navigate to the root folder of your Laravel project.
cd c:xampp/htdocs/chatgpt
Once inside the project directory, install the necessary dependencies and start the Laravel Vite development server for handling front-end assets with the following commands.
npm install && npm run dev
Keep this terminal open to allow the Vite server to continue running. Then, open a new terminal window or tab, navigate to the same project folder, and use this new terminal for running Laravel commands without interrupting the Vite server.

Step # 3 : Install the OpenAI Package.

To integrate OpenAI's functionality into your Laravel application, you need to install the OpenAI package. This can be done easily via Composer. Open your terminal and run the following command.
composer require openai-php/Laravel
This command will download and install the openai-php/laravel package, which provides a convenient Laravel wrapper for interacting with OpenAI's API. Once installed, you can start using OpenAI’s features in your Laravel app to enhance it with AI capabilities, such as text generation, chat functionality, and more.

Step # 4 : Publish the Configuration File.

To properly configure the OpenAI package in your Laravel application, you need to publish its configuration file. Run the following command in your terminal.
php artisan vendor:publish --provider="OpenAI\Laravel\ServiceProvider"
This command will generate the openai.php configuration file in the config directory of your Laravel project. The file contains essential configuration options, such as API keys and settings for connecting to OpenAI’s services. You can customize this file to suit your needs, ensuring that the integration works seamlessly with your application.

Step # 5: Create the View.

Create a new view file named openai.blade.php in the resources/views directory. This view will include a form for users to ask questions and receive answers from ChatGPT. Add the following HTML and JavaScript code to handle the form submission via AJAX and display the responses.
<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 <meta name="description" content="description">
 <meta name="csrf-token" content="{{ csrf_token() }}">
 <meta name="author" content="author">
 <title>OpenAI - Code Shotcut</title>
</head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<body class="bg-dark">
 <div class="conatiner m-5 p-5">
  <div class="row m-5 p-5 border">
   <div class="col-lg-8 offset-lg-2">
    <form id="ask">
     <h1 class="text-white">Ask ChatGPT</h1>
     <div class="form-group">
      <input type="text" class="form-control" name="question" id="question">
      <div class="text-white" id="question_help"></div>
     </div>
     <button type="submit" class="btn btn-primary">Ask ChatGPT</button>
    </form>
   </div>
   <div class="col-lg-8 offset-lg-2 mt-5" id="chat">
   </div>
  </div>
 </div>
</body>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script type="text/javascript">
 $.ajaxSetup({
  headers : {
   'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
  }
 })
 baseUrl = {!! json_encode(url('/')) !!}
 $('#ask').submit(function(event){
  event.preventDefault();
  var form = $('#ask')[0];
  var formData = new FormData(form);
  $.ajax({
   url : baseUrl+'/question',
   type : 'POST',
   data : formData,
   contentType : false,
   processData : false,
   success: function(data)
   {
    refresh();
    var divQuestion = '<div class="bg-white rounded"><h4 class="p-2">Question : '+data.question+'</h6></div>';
    var divAnswer = '<h5 class="text-white">Answer </h5><div class="bg-white rounded mb-3"><textarea class="w-100 form-control h-auto">'+data.answer+'</textarea></div>';
    $('#chat').append(divQuestion);
    $('#chat').append(divAnswer);
   },
   error: function(reject)
   {
    refresh();
    if(reject.status = 422){
     var errors = $.parseJSON(reject.responseText);
     $.each(errors.errors , function(key, value){
      $('#'+ key + '_help' ).text(value[0]);
     })
    }
   }
  });
 });
 function refresh()
 {
  $('#question_help').text('');
 }
</script>
</html>
This view will handle user interactions with OpenAI and display questions and answers dynamically. When the user submits a question, an AJAX request is sent to the server, which then fetches the answer from OpenAI. The response is dynamically displayed on the page without reloading.

Step # 6 : Create a controller.

Run the following command to generate the OpenAiController.
php artisan make:controller OpenAiController
After the controller is created, replace the content of OpenAiController.php with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Response;
use OpenAI\Laravel\Facades\OpenAI;
class OpenAiController extends Controller
{
    public function index(Request $request)
    {
        // Validate the incoming request to ensure 'question' is present and required.
        $request->validate([
            'question' => 'required',
        ]);
        // Assign the validated 'question' from the request to a variable.
        $question = $request->question;
        // Use OpenAI's chat API to send the question and get a response from the GPT-3.5-turbo model.
        $response = OpenAI::chat()->create([
            'model' => 'gpt-3.5-turbo', // Specify the OpenAI model to use.
            'messages' => [
                // Send the user's question as part of the message payload.
                ['role' => 'user', 'content' => $question],
            ],
        ]);
        // Extract and trim the AI's answer from the response data.
        $answer = trim($response['choices'][0]['message']['content']);
        // Return a JSON response containing both the user's question and the AI's answer.
        return response()->json(['question' => $question, 'answer' => $answer]);
    }
}
This controller is responsible for handling the interaction between the user and OpenAI's API. It takes a user's question from the request, validates it, and sends it to OpenAI’s gpt-3.5-turbo model for processing. The AI’s response is then extracted, and both the user's question and the AI’s answer are returned in a JSON format.

Step # 7 : Create & Update Route.

To connect the OpenAiController with routes, first import the controller at the top of your routes file.
use App\Http\Controllers\OpenAiController;
Then, update the default route and create a new route to handle user questions.
Route::get('/', function () {
    return view('openai');
});
Route::post('/question', [OpenAiController::class, 'index']);
The first route (/) loads the openai view, allowing users to interact with the form. The second route (/question) listens for POST requests from the form submission and invokes the index method in the OpenAiController to process the submitted question and return the AI's response.

Step # 8 : Get the Api Key.

To integrate OpenAI, you need to obtain an API key.
  1. Create an account at OpenAI API Link : https://openai.com/api/.
  2. Click on Create new secret key to generate a new API key.
  3. Copy and save the API key (you won't be able to view it again).

Open your .env file and add the following line, replacing Your API Key Here with the key you generated.
OPENAI_API_KEY="Your API Key Here"
This ensures your Laravel application has the necessary credentials to access the OpenAI API.

Step # 9 : It's time to test.

Start the Laravel development server.
php artisan serve
Once the server is running, open your browser and visit: http://127.0.0.1:8000.

You should now be able to interact with the form, submit questions, and receive answers from OpenAI.

Conclusion

By following this guide, you’ve successfully integrated a ChatGPT-powered interface into your Laravel application. With this setup, users can submit questions and receive real-time AI responses without reloading the page, providing a smooth and interactive experience. This foundation not only makes it easier to incorporate AI into your projects but also opens up possibilities for further enhancements, such as adding chat history, user authentication, or richer UI elements.

For more advanced usage, customization, or scaling options, be sure to explore OpenAI’s official API documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering