Copied!
Laravel
How to integrate Chatgpt in Laravel Step by Step
Chatgpt-laravel.jpg
Shahroz Javed
Oct 21, 2023 . 167 views

Table Of Contents

 
 

Introduction

ChatGPT is a semantic language developed by OpenAI that allows you to create intelligent chat, virtual assistants, and conversational agents. With its natural language manipulation capabilities, it can engage users in dynamic and contextual wrangling, making it a value addition to modern web applications. In this tutorial, we guide you through the process of adding ChatGPT to your Laravel application.

By the time you follow this guide, you'll have a fully functional bot to interact with your customers, answer questions, and provide valuable information. We will cover the following key topics:

 

Setting Up a Laravel Project

composer create-project laravel/laravel ChatGPT
          
 

OpenAI API Key Setup

CHATGPT_SECRET="you api key"
 

Create Routes

Route::get('/', [ChatController::class, 'index']);
Route::post('/chat', [ChatController::class, 'chat']);
          
 

Create Chat View

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css">
    <title>Chatgpt</title>
</head>

<body>
    <div class="card w-25 m-5 p-0">
        <div class="card-header">
            <h2>Search Using Chatgpt:</h2>
        </div>
        <div class="card-body">
            <div class="form-group">
                <input type="text" id="question" class="form-control">
            </div>
        </div>
        <div class="card-footer">
            <button class="btn btn-dark" id="btn" onclick="search()">Search</button>
        </div>
    </div>


    <div class="form-group" id="response">
    </div>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/js/bootstrap.min.js"></script>
    <script>
        function search() {
            let question = $('#question').val()
            $('#question').val('')
            $('#btn').text('loading...')
            $.ajax({
                url: '/chat',
                method: 'post',
                data: {
                    question: question,
                    _token: '{{ csrf_token() }}'
                },
                success: function(res) {
                    $('#response').append(res)
                    $('#btn').text('Search')
                }
            })
        }
    </script>
</body>

</html>

          
 

Create Controller

php artisan make:controller ChatController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use PhpParser\Node\Stmt\TryCatch;

class ChatController extends Controller
{
    function index()
    {
        return view('welcome');
    }

    public function chat(Request $request)
    {

        $question = $request->input('question');
        $apiKey = env('CHATGPT_SECRET');

        try {
            $data = Http::withHeaders([
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $apiKey,
            ])
                ->post("https://api.openai.com/v1/chat/completions", [
                    "model" => "gpt-3.5-turbo",
                    'messages' => [
                        [
                            "role" => "user",
                            "content" => $question
                        ]
                    ],
                    'temperature' => 0.5,
                    "max_tokens" => 200,
                    "top_p" => 1.0,
                    "frequency_penalty" => 0.52,
                    "presence_penalty" => 0.5,
                    "stop" => ["11."],
                ])
                ->json();
                
            return $res = view('response', compact('data', 'question'))->render();
        } catch (\Exception $e) {
            return response()->json($e->getMessage());
        }
    }
}
          
 

6.1: Response View:

<div class="card m-3">
  <div class="card-body">
      <h3>{{ $question }}</h3>
      @if ($data)
          <pre>{{ $data }}</pre>
      @endif
  </div>
</div>
          

Conclusion:

By following all these steps you will be able to setup a simple chatgpt chat in you laravel application. Please provide your feedback at comment below.

13 Shares

Related Posts