How to use Chat GPT API in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Migration Add Column After Column Example
- Laravel 9 Restrict User Access From IP Address Tutorial
- Laravel Google ReCaptcha V3 Tutorial Example
- Laravel Google Pie Chart Example Tutorial
- How to Generate QR Code in Laravel?
- Laravel Eloquent whereHas() Condition Example
- Laravel Blade Include File Example
- Laravel Login with Google Account Tutorial
- Laravel Repository Pattern Tutorial Example
- How to Redirect Route with Querystring in Laravel?
- Laravel Custom Pagination View Example
- Laravel XSS Protection Middleware Example
- How to Get Query Log in Laravel Eloquent?