How To Integrate ChatGPT API in Laravel 10 Tutorial

Reading Time: 5 minutes
193 Views

By leveraging extensive natural language processing capabilities, integrating ChatGPT API into Laravel 10 provides a powerful dimension to your online apps. Laravel, a powerful PHP framework, easily integrates external APIs, and in this article, we’ll walk you through the process of integrating the ChatGPT API step by step.

With OpenAI’s ChatGPT, you can improve user interactions, build intelligent chatbots, and enable your applications to understand and reply to natural language queries. This connection allows for a more engaging and dynamic user experience.

Read More: How To Cache Database Query Using Laravel Cache?

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

What is ChatGPT?

ChatGPT is a language model developed by OpenAI. It is part of the GPT (Generative Pre-trained Transformer) series, specifically GPT-3.5-turbo. ChatGPT is designed to generate human-like responses based on the input it receives.

Key features of ChatGPT include:

  • Natural Language Understanding
  • Contextual Understanding
  • Versatility
  • Large-scale Pre-training

Create an Account and Generate OpenAI API Key

To make use of ChatGPT, create an account on OpenAI platform to generate API keys.

You have to pass an email address and password. It will send you a verification email and later on asks for basic information like Name, Phone number, DOB etc.

Once your account will be set successfully,

Click on Create New Secret Key

Copy generated secret key.

Read More: How To Validate Image Upload in Laravel 10 Example

Installation of “openai-php/client” Composer Package

Open project terminal and run this command to install “openai-php/client” this composer package.

composer require openai-php/client

Set up OpenAI API Credentials

Open .env file and add this key and it’s value.

OPENAI_API_KEY="sk-UKlics6Ct2So5noVWWGzT3BlbkF....."

Create a ChatGPT Service Class

There is no specific folder location to create service classes in laravel application.

So, let’s create a service class named GeneratorOpenAIService.php inside /app/Services folder.

Write this complete code into it,

<?php

namespace App\Services;

use OpenAI;

class GeneratorOpenAIService
{
    private $client;

    public function __construct()
    {
        $this->client = OpenAI::client(env('OPENAI_API_KEY'));
    }

    public function generateResponseOpenAi(string $question): string
    {
        $response = $this->client->completions()->create([
            'model' => 'text-davinci-003',
            'temperature' => 0.9,
            'top_p' => 1,
            'frequency_penalty' => 0,
            'presence_penalty' => 0,
            'prompt' => $question,
            'max_tokens' => 4000,
        ]);

        return $response['choices'][0]['text'];
    }
}

Usage of OpenAI Service in a Controller

Use the service into a controller where you want to use the ChatGPT API,

Create a controller class,

php artisan make:controller OpenAIController

It will create a OpenAIController.php file inside /app/Http/Controllers folder.

Open file and write this code into it,

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\GeneratorOpenAIService;

class OpenAIController extends Controller
{
    private $openAiService;

    public function __construct(GeneratorOpenAIService $openaiService)
    {
        $this->openAiService= $openaiService;
    }

    public function chatOpenAi()
    {
        $question = "How artificial intelligence is transforming the world?";

        if ($question == null) {
            return back();
        }

        $response= $this->openAiService->generateResponseOpenAi($question);

        return response()->json([
            'question' => $question,
            'response' => $response
        ]);
    }
}

Add Route

Open web.php from /routes folder. Add this route into it,

//...

use App\Http\Controllers\OpenAIController;

Route::get('open-ai', [OpenAIController::class, 'chatOpenAi']);

//...

Application Testing

Run this command into project terminal to start development server,

php artisan serve

Read More: Laravel 10 Convert Word Docx File to PDF File Example

URL: http://127.0.0.1:8000/open-ai

That’s it.

We hope this article helped you to learn about How To Integrate ChatGPT API in Laravel 10 Tutorial Example in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more