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

Could not fetch https://api.github.com/repos/Setasign/FPDI/zipball/

When I composer update in Laravel its throwing error could not fetch issues so let’s start to finish this issues. 1st step go to GitHub setting section….

Error: error:0308010C:digital envelope routines::unsupported

In this tutorial I’m going to share how to solve Error: error:0308010C:digital envelope routines::unsupported. Just copy below code and run your terminal. After run above all code…

API calls from the server require an appsecret_proof argument

In this tutorial im going to solve this issue API calls from the server require an appsecret_proof argument. 1st step go to developer facebook advance setting and…

How to Delete All Records Older Than 30 Days in Laravel 10 ?

In Laravel, you can use the Eloquent ORM to delete records older than a certain number of days. Here’s an example of how you can delete all…

How to safely remove Laravel Debugbar ?

What is Laravel Debugbar ? Laravel Debugbar is a package for the Laravel PHP framework that provides a debug bar or toolbar for your application. It offers…

Example of __construct and __destruct in laravel ?

In Laravel, PHP classes can have a constructor and destructor like any other PHP class. The constructor is called when an object is created, and the destructor…

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