ChatGPT + Laravel

Back-End Dev Note May 18, 2023

How to use ChatGPT in Laravel?

 

 

First let us dive into the details.

 

Chat GPT stands for Chat Generative Pre-trained Transformer. It is a language model developed by OpenAI that is designed to generate human-like text responses to a given prompt or conversation. This api became useful and it became one of the largest and most advanced language models in existence, with billions of parameters.

 

Chat GPT is trained on a massive dataset of text from the internet, including books, articles, web, and many more. 

Also, the model is trained using a self-supervised learning approach, where it tries to predict the next word in a given sequence of text. 

 

On the first step, we will show you how to use OpenAI in Laravel. Let us create a simple route (get) and call the OpenAI apt to get the data using HTTP client facade. Open AI has many models like GPT-3, GPT-3.5, GPT-4, and many more. For today we will be using gpt-3.5-turbo and get data.

 

1st Step: Install Laravel via terminal

 

composer create-project laravel/laravel projectname-app

 

2nd Step: Create OpenAI Account

 

Let’s create an account on OpenAI. https://openai.com/product

 


 

After, you created an account and logged in, access to following link below and generate key:

URL: https://beta.openai.com/account/api-keys

 

 

 

Next step is copy and paste the account key created and add on .env file as like below:

 

.env

OPENAI_API_KEY=sk-FQolFbZAM6OHS7ddhlS…

 

3rd Step: Create Route on Laravel

 

Let us modify the on the following directory: routes/web.php

 

<?php
 use Illuminate\Support\Facades\Route;
 use App\Http\Controllers\OpenAIController;
 /*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
 Route::get('open-ai', [OpenAIController::class, 'index']);

 

We will then create OpenAIController and write index method. After that, we will call OpenAI API and getting data, so let’s add new route to web.php file as bellow:

 

app/Http/Controllers/OpenAIController.php

 

 

<?php
 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\JsonResponse;
 class OpenAIController extends Controller
{
   /**
    * Write code on Method
    *
    * @return response()
    */
   public function index(): JsonResponse
   {
       $search = "laravel get ip address";
        $data = Http::withHeaders([
                   'Content-Type' => 'application/json',
                   'Authorization' => 'Bearer '.env('OPENAI_API_KEY'),
                 ])
                 ->post("https://api.openai.com/v1/chat/completions", [
                   "model" => "gpt-3.5-turbo",
                   'messages' => [
                       [
                          "role" => "user",
                          "content" => $search
                      ]
                   ],
                   'temperature' => 0.5,
                   "max_tokens" => 200,
                   "top_p" => 1.0,
                   "frequency_penalty" => 0.52,
                   "presence_penalty" => 0.5,
                   "stop" => ["11."],
                 ])
                 ->json();
        return response()->json($data['choices'][0]['message'], 
        200, array(), JSON_PRETTY_PRINT);
   }
}

 

4th and last step: Run Laravel via terminal:

 

php artisan serve

 

Go to your web browser.

http://localhost:8000/open-ai

 

 


 

 

We’re developing something similar. We have established an online exhibition system and are deploying it, utilizing this type of technology, and we do everything, from planning to infrastructure design, system development, and design. Please do not hesitate to contact us at info@commude.ph.

 

“Today we think ahead as one, in making tomorrow so much fun.”