ItSolutionStuff.com

How to use Chat GPT API in Laravel?

By Hardik Savani β€’ November 5, 2023
Laravel

Hey Developer,

This post will give you an example of how to use chat gpt in laravel. let’s discuss about how to use chatgpt api in laravel. This article will give you a simple example of laravel chat gpt api. you can see laravel chatgpt api example. So, let us dive into the details.

Chat GPT (Generative Pre-trained Transformer) is a language model developed by OpenAI that is designed to generate human-like text in response to a given prompt or conversation. It is 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, and web pages. The model is trained using a self-supervised learning approach, where it tries to predict the next word in a given sequence of text. This allows the model to learn the patterns and structures of language and generate coherent and contextually relevant responses.

In this post, i will show you how to use open ai in laravel. we will create simple get route and call openai apt to getting data using HTTP client facade. Open AI has many models like GPT-3, GPT-3.5, GPT-4 and davinci etc. we will use gpt-3.5-turbo and get data.

So, let's follow the below steps:

Step 1: Install Laravel

This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create OpenAI Account

First you need to create account on OpenAI. then you can easily get account key.

Create Account from here: https://openai.com/product.

After, creating account go to following link and generate key:

Go Here: https://beta.openai.com/account/api-keys.

Next you can get account key and add on .env file as like bellow:

.env

OPENAI_API_KEY=sk-FQolFbZAM6OHS7ddhlS...

Step 3: Create Route

now we will create one route for calling our example, so let's add new route to web.php file as bellow:

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']);

Step 4: Create Controller

in this step, we will create OpenAIController and write index method. Then 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);

}

}

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/open-ai

Output:

I hope it can help you...

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube

We Are Recommending You

β˜…

Laravel Migration Add Column After Column Example

Read Now β†’
β˜…

Laravel 9 Restrict User Access From IP Address Tutorial

Read Now β†’
β˜…

Laravel Google ReCaptcha V3 Tutorial Example

Read Now β†’
β˜…

Laravel Google Pie Chart Example Tutorial

Read Now β†’
β˜…

How to Generate QR Code in Laravel?

Read Now β†’
β˜…

Laravel Eloquent whereHas() Condition Example

Read Now β†’
β˜…

Laravel Blade Include File Example

Read Now β†’
β˜…

Laravel Login with Google Account Tutorial

Read Now β†’
β˜…

Laravel Repository Pattern Tutorial Example

Read Now β†’
β˜…

How to Redirect Route with Querystring in Laravel?

Read Now β†’
β˜…

Laravel Custom Pagination View Example

Read Now β†’
β˜…

Laravel XSS Protection Middleware Example

Read Now β†’
β˜…

How to Get Query Log in Laravel Eloquent?

Read Now β†’