How to Integrate ChatGPT API with Laravel 11
How to Integrate ChatGPT API with Laravel 11

How to Integrate ChatGPT API with Laravel 11

Integrating the ChatGPT API with Laravel 11 can add powerful conversational capabilities to your application. This guide will walk you through the steps to set up the integration, using simple language and easy-to-follow code examples.

Prerequisites

Before starting, make sure you have the following:

  1. A Laravel 11 project set up on your local machine.
  2. Composer installed.
  3. An API key from OpenAI. Sign up at OpenAI if you don’t have one.

Step 1: Create a New Laravel Project (if you don’t have one)

If you don’t have a Laravel 11 project set up, you can create a new one using Composer:

composer create-project laravel/laravel chatgpt-integration
cd chatgpt-integration

Step 2: Install Guzzle HTTP Client

Laravel uses Guzzle to make HTTP requests. Install it using Composer:

composer require guzzlehttp/guzzle

Step 3: Set Up Environment Variables

Add your OpenAI API key to the .env file:

OPENAI_API_KEY=your-openai-api-key-here

Step 4: Create a Service to Handle API Requests

Create a new service class to handle requests to the ChatGPT API. You can generate a new service class using the Artisan command:

php artisan make:service ChatGPTService

In the app/Services directory, you should see a new file ChatGPTService.php. Open it and add the following code:

<?php

namespace App\Services;

use GuzzleHttp\Client;

class ChatGPTService
{
    protected $client;
    protected $apiKey;

    public function __construct()
    {
        $this->client = new Client();
        $this->apiKey = env('OPENAI_API_KEY');
    }

    public function getResponse($prompt)
    {
        $response = $this->client->post('https://api.openai.com/v1/completions', [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
            ],
            'json' => [
                'model' => 'text-davinci-003',
                'prompt' => $prompt,
                'max_tokens' => 150,
            ],
        ]);

        return json_decode($response->getBody(), true);
    }
}

Step 5: Create a Controller

Next, create a controller to handle user input and return responses from the ChatGPT API. Generate a new controller using Artisan:

php artisan make:controller ChatGPTController

Open the newly created controller in app/Http/Controllers/ChatGPTController.php and add the following code:

<?php

namespace App\Http\Controllers;

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

class ChatGPTController extends Controller
{
    protected $chatGPTService;

    public function __construct(ChatGPTService $chatGPTService)
    {
        $this->chatGPTService = $chatGPTService;
    }

    public function ask(Request $request)
    {
        $prompt = $request->input('prompt');
        $response = $this->chatGPTService->getResponse($prompt);

        return response()->json($response);
    }
}

Step 6: Define Routes

Now, define a route for the controller method. Open routes/web.php and add the following:

use App\Http\Controllers\ChatGPTController;

Route::post('/ask', [ChatGPTController::class, 'ask']);

Step 7: Create a View

Create a simple view to take user input and display the response from ChatGPT. Create a new view file in resources/views/chatgpt.blade.php and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>ChatGPT Integration</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
    <h1>Ask ChatGPT</h1>
    <form id="chatgpt-form">
        <textarea id="prompt" placeholder="Type your question here..."></textarea>
        <button type="submit">Ask</button>
    </form>
    <h2>Response:</h2>
    <pre id="response"></pre>

    <script>
        document.getElementById('chatgpt-form').addEventListener('submit', async function(event) {
            event.preventDefault();

            const prompt = document.getElementById('prompt').value;
            const responseElement = document.getElementById('response');

            const response = await fetch('/ask', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                },
                body: JSON.stringify({ prompt: prompt })
            });

            const data = await response.json();
            responseElement.textContent = data.choices[0].text;
        });
    </script>
</body>
</html>

Step 8: Test the Integration

Start the Laravel development server:

php artisan serve

Open your browser and go to http://localhost:8000/chatgpt. You should see a form where you can type a question. When you submit the form, it will send the question to the ChatGPT API and display the response.

Conclusion

You have successfully integrated the ChatGPT API with your Laravel 11 application. This guide provided you with the steps to set up the integration, including creating a service, a controller, and a view to interact with the API. You can now expand on this basic example to add more features and improve the user experience.