Chat Gpt Implement in laravel 9 | ChatGPT installation laravel

In this tutorial im going to share how to use chatgpt in laravel so follow this tutorial in this tutorials i have mentioned in very easy way.

composer require openai-php/laravel

php artisan vendor:publish --provider="OpenAI\Laravel\ServiceProvider"

Then create Controller Once

php artisan make:controller TestingController

And paste below code.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use OpenAI\Laravel\Facades\OpenAI;
class TestingController extends Controller
{
    public function index()
    {
        $messages = collect(session('messages', []))->reject(fn ($message) => $message['role'] === 'system');
        return view('welcome', [
            'messages' => $messages
        ]);
    }
     public function store(Request $request)
    {
        $messages = $request->session()->get('messages', [
            ['role' => 'system', 'content' => 'You are LaravelGPT - A ChatGPT clone. Answer as concisely as possible.']
        ]);
        $messages[] = ['role' => 'user', 'content' => $request->input('message')];
        $response = OpenAI::chat()->create([
            'model' => 'gpt-3.5-turbo',
            'messages' => $messages
        ]);
        $messages[] = ['role' => 'assistant', 'content' => $response->choices[0]->message->content];
        $request->session()->put('messages', $messages);
        return redirect('/');
    }
    public function destroy(Request $request)
    {
        $request->session()->forget('messages');
        return redirect('/');
    }

}

Next go to route and paste below code

<?php
use OpenAI\Laravel\Facades\OpenAI;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Request;
use App\Http\Controllers\TestingController;
use App\Http\Controllers\Api\ChatGptController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/


Route::get('/', [TestingController::class, 'index']);
Route::post('/', [TestingController::class, 'store']);
Route::get('/reset', [TestingController::class, 'destroy']);

Next got to welcome.blade.php and paste below code.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel</title>
        <!-- Fonts -->
        <link rel="preconnect" href="https://fonts.bunny.net">
        <link href="https://fonts.bunny.net/css?family=figtree:400,600&display=swap" rel="stylesheet" />
        <script src="https://cdn.tailwindcss.com"></script>
    </head>
    <body class="antialiased">
        <div class="flex flex-col space-y-4 p-4">
        @foreach($messages as $message)
            <div class="flex rounded-lg p-4 @if ($message['role'] === 'assistant') bg-green-200 flex-reverse @else bg-blue-200 @endif ">
                <div class="ml-4">
                    <div class="text-lg">
                        @if ($message['role'] === 'assistant')
                            <a href="#" class="font-medium text-gray-900">LaravelGPT</a>
                        @else
                            <a href="#" class="font-medium text-gray-900">You</a>
                        @endif
                    </div>
                    <div class="mt-1">
                        <p class="text-gray-600">
                            {!! \Illuminate\Mail\Markdown::parse($message['content']) !!}
                        </p>
                    </div>
                </div>
            </div>
        @endforeach
        </div>
        <form class="p-4 flex space-x-4 justify-center items-center" action="/" method="post">
            @csrf
            <label for="message">Ask something:</label>
            <input id="message" type="text" name="message" autocomplete="off" class="border rounded-md  p-2 flex-1" />
            <a class="bg-gray-800 text-white p-2 rounded-md" href="/reset">Reset Chat</a>
        </form>
    </body>
</html>

Next go to .env and paste below code.

First generate the secret key

Open this url => https://platform.openai.com/account/api-keys

And generate key and paste in .env file

OPENAI_API_KEY=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

Now run your project

Hi I am Amit Kumar Thakur Experienced as s Software Developer with a demonstrated history of working in the information technology and services industry. Skilled in HTML, CSS, Bootstrap4, PHP, Laravel-9 , REST API,FB API,Google API, Youtube Api, Bitbucket,Github,Linux and jQuery. Strong engineering professional focused in Computer/Information Technology Administration and Management. Currently my profile is to Software Developer, analyze the requirement, creating frame for web application, coding and maintenance.

Related Posts

How to Crawl any website Meta Title and Meta Description in Laravel ?

1st step install below package. Next to create Controller First go to route and put below code Next go to controller and put below code Next go…

SQLSTATE[HY000] [2002] No such file or directory (Connection: mysql, SQL: insert into `oauth_clients` (`user_id`, `name`, `secret`

In this tutorial i’m going to solve the error SQLSTATE[HY000] [2002] No such file or directory (Connection: mysql, SQL: insert into oauth_clients (user_id, name, secret Error :-…

Top 20 Laravel Interview Question in 2024

In this tutorial im going share interview experience For laravel developer. A list of top frequently asked Laravel Interview Questions and answers are given below. Q #1) What is…

How to Get Google Analytics API key ?

In this tutorial we’re going to share how to get the google Analytics API key. I have shared in very easy way. First go enable Google analytics…

Youtube Subscriber Count in ReactJs

In this tutorial i’m going to learn how to count YouTube Subsribers count, views count as well, as define below. In order to install your app, first…

How to Disable Laravel’s Eloquent timestamps in laravel ?

In this tutorial we’re going to share how to disable the automatic created_at and updated_at timestamps in Laravel’s Eloquent models, along with explanations of different scenarios: 1st…

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x