Laravel 10 - OpenAI ChatGPT
Laravel 10 - OpenAI ChatGPT
In this tutorial, we will integrate OpenAI's ChatGPT into Laravel 10, enabling powerful AI-driven conversations to enhance user interactions and automate responses efficiently.
If you're a video person, feel free to skip the post and check out the video instead!
Step # 1 : Create fresh Laravel project.
Two commands to create fresh Laravel project.
Global Command : laravel new chatgpt
Or use
Non Global Command : composer create-project laravel/laravel --prefer-dist chatgpt
Step # 2 : Access the project.
Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
Git Bash : cd c:xampp/htdocs/chatgpt
Next, install the required dependencies and run the Laravel Vite development server for front-end assets:
Command : npm install && npm run dev
In a new terminal window or tab (while keeping the Vite server running), navigate to the same project directory to execute further Laravel command.
Step # 3 : Install OpenAi package.
Command : composer require openai-php/laravel
Step # 4 : Publish the configuration file.
Command : php artisan vendor:publish --provider="OpenAI\Laravel\ServiceProvider"
This will create the openai.php file in the config directory.
Step # 5 : Create a view.
Create a view named openai.blade.php and paste the following code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="description">
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="author" content="author">
<title>OpenAI - Code Shotcut</title>
</head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<body class="bg-dark">
<div class="conatiner m-5 p-5">
<div class="row m-5 p-5 border">
<div class="col-lg-8 offset-lg-2">
<form id="ask">
<h1 class="text-white">Ask ChatGPT</h1>
<div class="form-group">
<input type="text" class="form-control" name="question" id="question">
<div class="text-white" id="question_help"></div>
</div>
<button type="submit" class="btn btn-primary">Ask ChatGPT</button>
</form>
</div>
<div class="col-lg-8 offset-lg-2 mt-5" id="chat">
</div>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script type="text/javascript">
$.ajaxSetup({
headers : {
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
}
})
baseUrl = {!! json_encode(url('/')) !!}
$('#ask').submit(function(event){
event.preventDefault();
var form = $('#ask')[0];
var formData = new FormData(form);
$.ajax({
url : baseUrl+'/question',
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(data)
{
refresh();
var divQuestion = '<div class="bg-white rounded"><h4 class="p-2">Question : '+data.question+'</h6></div>';
var divAnswer = '<h5 class="text-white">Answer </h5><div class="bg-white rounded mb-3"><textarea class="w-100 form-control h-auto">'+data.answer+'</textarea></div>';
$('#chat').append(divQuestion);
$('#chat').append(divAnswer);
},
error: function(reject)
{
refresh();
if(reject.status = 422){
var errors = $.parseJSON(reject.responseText);
$.each(errors.errors , function(key, value){
$('#'+ key + '_help' ).text(value[0]);
})
}
}
});
});
function refresh()
{
$('#question_help').text('');
}
</script>
</html>
Step # 6 : Create a controller.
Run the following command to generate the OpenAiController.
Command : php artisan make:controller OpenAiController
Once the controller is created, replace the content of OpenAiController.php with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Response;
use OpenAI\Laravel\Facades\OpenAI;
class OpenAiController extends Controller
{
public function index(Request $request)
{
// Validate the incoming request to ensure 'question' is present and required.
$request->validate([
'question' => 'required',
]);
// Assign the validated 'question' from the request to a variable.
$question = $request->question;
// Use OpenAI's chat API to send the question and get a response from the GPT-3.5-turbo model.
$response = OpenAI::chat()->create([
'model' => 'gpt-3.5-turbo', // Specify the OpenAI model to use.
'messages' => [
// Send the user's question as part of the message payload.
['role' => 'user', 'content' => $question],
],
]);
// Extract and trim the AI's answer from the response data.
$answer = trim($response['choices'][0]['message']['content']);
// Return a JSON response containing both the user's question and the AI's answer.
return response()->json(['question' => $question, 'answer' => $answer]);
}
}
Step # 7 : Create & update route.
Import OpenAiController class.
use App\Http\Controllers\OpenAiController;
//Update the default route and create a new route to ask questions.
Route::get('/', function () {
return view('openai');
});
Route::post('/question', [OpenAiController::class, 'index']);
Step # 8 : Get the Api Key.
In order to integrate openai we need the api key. Therefore you need to create an account.
Link : https://openai.com/api/
Click on create new secret key.
Copy and save the API key (you won’t be able to see the key again).
Access the .env file and add the following.
OPENAI_API_KEY="Your API Key Here"
Step # 9 : It's time to test.
Start the Laravel development server.
Command : php artisan serve.
Access the URL below and start asking questions.
127.0.0.1:8000
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments