Free code on computer screen

How to integrate OpenAI Chat GPT-4 with Laravel

How to integrate OpenAI Chat GPT-4 with Laravel

SectionHeading
1Introduction to GPT-4 and Laravel
1.1What is GPT-4?
1.2What is Laravel?
2Prerequisites for Integrating GPT-4 with Laravel
2.1Setting Up Laravel
2.2Acquiring GPT-4 API Key
3Integrating GPT-4 with Laravel
3.1Installing Guzzle HTTP Client
3.2Creating a GPT-4 Service
3.3Using GPT-4 in Laravel Controllers
4Building a Sample Application
4.1Setting Up Routes and Controllers
4.2Creating Views and Forms
4.3Implementing GPT-4 Interactions
5Conclusion
Table of contents

Introduction to GPT-4 and Laravel

What is GPT-4?

GPT-4, or Generative Pre-trained Transformer 4, is a state-of-the-art natural language processing model developed by OpenAI. This powerful AI model can generate highly coherent and contextually relevant text, enabling numerous applications such as content creation, summarization, translation, and more.

What is Laravel?

Laravel is a popular PHP web application framework that simplifies development, providing an elegant and expressive syntax. Its robust tools and features make it a go-to choice for modern web application developers.

Prerequisites for Integrating GPT-4 with Laravel

Setting Up Laravel

Before integrating GPT-4 with Laravel, you must have a Laravel project up and running. You can install Laravel using Composer and create a new project using the laravel new command. Ensure you have a working development environment with PHP, a web server, and a database.

Installing the Laravel installer

If you want to install Laravel globally so that you can create new Laravel projects from anywhere in your system, run:

composer global require laravel/installer
# Then you can use:
laravel new project_name

Ensure Composer’s system-wide vendor bin directory is in your system’s PATH. Depending on where Composer was installed, this directory might be:

  • $HOME/.composer/vendor/bin or
  • $HOME/.config/composer/vendor/bin

Or you can choose to use the more direct approach and project-specific way, which is using composer:

composer create-project --prefer-dist laravel/laravel project_name

Acquiring GPT-4 API Key

To access GPT-4, you’ll need an API key from OpenAI. Visit the OpenAI website to sign up and acquire an API key.

Integrating GPT-4 with Laravel

Installing Guzzle HTTP Client

GPT-4 provides a RESTful API, so you’ll need an HTTP client to interact with it. Guzzle is a popular choice for PHP developers. Install Guzzle in your Laravel project using Composer:

composer require guzzlehttp/guzzle

Creating a GPT-4 Service

To keep things organized, let’s create a dedicated service for GPT-4 integration. Run the following command to generate a new service:

php artisan make: service GPT4Service

NOTE: If your version of Laravel does not have the make: service command, you can install this package which will allow doing so:

composer require getsolaris/laravel-make-service --dev

In app/Services/GPT4Service.php, import the required dependencies, and set up the constructor:

<?php

namespace App\Services;

use GuzzleHttp\Client;

class GPT4Service
{
    private $client;
    private $apiKey;

    public function __construct()
    {
        $this->apiKey = env('GPT_4_API_KEY');
        $this->client = new Client([
            'base_uri' => 'https://api.openai.com/v1/',
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
'Content-Type' => 'application/json',
                         ],
             ]);
    }
}

Remember to add your GPT-4 API key to your `.env` file:

GPT_4_API_KEY=your_api_key_here

Now, let’s add a method to generate text using GPT-4:

public function generateText(string $prompt, int $maxTokens = 50)
    {
        $response = $this->client->post('chat/completions', [
            'json' => [
                'model' => "gpt-4", // Here you can select from the following models : gpt-4, gpt-4-0314, gpt-4-32k, gpt-4-32k-0314, gpt-3.5-turbo, gpt-3.5-turbo-0301 
                'messages' => [ 
                    [
                        'role' => 'user',
                        'content' => $prompt,
                    ],
                ],                
                'max_tokens' => $maxTokens,
            ],
        ]);

        $responseData = json_decode($response->getBody(), true);     
        return  $responseData['choices'][0]['message']['content'];
    }

Using GPT-4 in Laravel Controllers

With the GPT-4 service ready, you can now use it in your controllers. For instance, you can create a new controller with the following command:

php artisan make:controller GPT4Controller

In app/Http/Controllers/GPT4Controller.php, you can now inject the GPT4Service And use it to generate text:

<?php

namespace App\Http\Controllers;

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

class GPT4Controller extends Controller
{
    private $gpt4Service;

    public function __construct(GPT4Service $gpt4Service)
    {
        $this->gpt4Service = $gpt4Service;
    }

    public function generate(Request $request)
    {
        $generatedText = $this->gpt4Service->generateText($request->input('prompt'));
        return view('generated', compact('generatedText'));
    }
}

Building a Sample Application

Setting Up Routes and Controllers

Now let’s build a simple application to demonstrate GPT-4 integration. First, define routes for the application in routes/web.php:

use App\Http\Controllers\GPT4Controller;

Route::get('/', function () {
    return view('welcome');
});

Route::post('/generate', [GPT4Controller::class, 'generate'])->name('generate');

Creating Views and Forms

Create a new view in resources/views/welcome.blade.php with a form for users to input a prompt:

@extends('layouts.app')

@section('content')
    <div class="container">
        <h1>Generate Text with GPT-4 and Laravel</h1>
        <form action="{{ route('generate') }}" method="post">
            @csrf
            <div class="form-group">
                <label for="prompt">Enter a prompt:</label>
                <input type="text" class="form-control" id="prompt" name="prompt" required>
            </div>
            <button type="submit" class="btn btn-primary">Generate</button>
        </form>
    </div>
@endsection

Create another view in resources/views/generated.blade.php to display the generated text:

@extends('layouts.app')

@section('content')
    <div class="container">
        <h1>Generated Text</h1>
        <p>{{ $generatedText }}</p>
        <a href="{{ url('/') }}" class="btn btn-primary">Try Again</a>
    </div>
@endsection

Implementing chatGPT-4 Interactions

With the views and routes set up, users can now input a prompt, and the application will generate text using GPT-4.

Conclusion

Integrating OpenAI’s GPT-4 with Laravel is a powerful way to leverage the capabilities of this advanced natural language processing model in your web applications. Following the steps outlined in this article, you can easily set up the integration and harness GPT-4’s potential to generate contextually relevant and coherent text.

With GPT-4 integrated into your Laravel application, the possibilities are endless. You can create content generation tools, automated summarization systems, language translation applications, and more. Keep experimenting and exploring the vast potential that GPT-4 offers in conjunction with the simplicity and elegance of Laravel.

If you want to skip all the copy and paste, you can download all the source code from GitHub

FAQs

1. What is GPT-4?

GPT-4 (Generative Pre-trained Transformer 4) is a state-of-the-art natural language processing model developed by OpenAI. It can generate highly coherent and contextually relevant text for various applications such as content creation, summarization, translation, and more.

2. What is Laravel?

Laravel is a popular PHP web application framework that simplifies development by providing an elegant and expressive syntax. Its robust tools and features make it popular for modern web application developers.

3. How do I get an API key for ChatGPT-4?

To get an API key for ChatGPT-4, sign up on the OpenAI website and follow the instructions to acquire an API key.

4. Why do I need a Guzzle HTTP Client for this integration?

Guzzle is a popular HTTP client for PHP that simplifies making HTTP requests. GPT-4 provides a RESTful API, and Guzzle helps you interact with it quickly and efficiently within your Laravel application.

5. Can I use other PHP frameworks to integrate with GPT-4?

You can use PHP frameworks like Symfony, CodeIgniter, or Yii to integrate GPT-4. The process will be similar, though the implementation details may differ depending on your chosen framework.

By Louis M.

About the authorMy LinkedIn profile

Related Links: