AI, Laravel

How to Integrate OpenAI API in Laravel to Generate Creative Responses

In this tutorial, we’ll walk through the process of integrating the OpenAI API into a Laravel application to generate creative responses. We will create a custom Chat class to manage the interaction with the API and display the results in a view.

Prerequisites

  1. Laravel installed on your machine.
  2. An OpenAI API key. If you don’t have one, sign up at OpenAI.

Step 1: Set Up Laravel Project

If you don’t already have a Laravel project, create one:

composer create-project --prefer-dist laravel/laravel openai-laravel
cd openai-laravel

Step 2: Configure Environment Variables

Open your .env file and add your OpenAI API key:

OPENAI_SECRET=your_openai_api_key

Step 3: Create the Chat Class

Create a new directory AI inside app and create a Chat.php file:

mkdir app/AI
touch app/AI/Chat.php

Add the following code to Chat.php:

<?php

namespace App\AI;

use Illuminate\Support\Facades\Http;

class Chat 
{
    protected array $messages = [];

    public function systemMessage(string $message): static
    {
        $this->messages[] = [
            'role' => 'system',
            'content' => $message
        ];

        return $this;
    }

    public function send(string $message): ?string
    {
        $this->messages[] = [
            'role' => 'user',
            'content' => $message
        ];
        
        $response = Http::withToken(config('services.openai.secret'))
            ->post('https://api.openai.com/v1/chat/completions', [
                "model" => "gpt-3.5-turbo",
                "messages" => $this->messages,
            ])->json('choices.0.message.content');
        
        if ($response) {
            $this->messages[] = [
                'role' => 'assistant',
                'content' => $response
            ];
        }

        return $response;
    }

    public function reply(string $message): ?string
    {
        return $this->send($message);
    }

    public function messages()
    {
        return $this->messages;
    }
}

This Chat class handles the conversation flow with the OpenAI API, including setting the system message, sending user messages, and storing the responses.

Step 4: Define Routes

Open routes/web.php and add the following route:

use App\AI\Chat;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    $chat = new Chat();

    $poem = $chat
        ->systemMessage("You are a poetic assistant, skilled in explaining complex programming concepts with creative flair.")
        ->send('Compose a poem that explains the concept of recursion in programming.');

    $sillyPoem = $chat->reply('Cool, can you make it much, much sillier.');

    return view('welcome', ['poem' => $sillyPoem]);
});

This route creates an instance of the Chat class, sends an initial message, and then sends a follow-up message to make the response sillier.

Step 5: Create the View

Create a welcome.blade.php file in the resources/views directory:

touch resources/views/welcome.blade.php

Add the following code to welcome.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>AI Poetic Assistant</title>
</head>
<body>
    <h1>AI Generated Poem</h1>
    <p>{{ $poem }}</p>
</body>
</html>

Step 6: Test the Application

Run your Laravel application:

php artisan serve

Visit http://127.0.0.1:8000 in your browser. You should see the poem generated by the OpenAI API, followed by the sillier version of the poem.

+---------------------------+
| User                      |
| (Accesses '/' URL)        |
+------------+--------------+
             |
             v
+------------+--------------+
| Laravel Route             |
| (Route::get('/', ...))    |
+------------+--------------+
             |
             v
+------------+--------------+
| Anonymous Function        |
| Creates Chat Instance     |
| Adds System Message       |
| Sends Initial Message     |
| Sends Follow-up Message   |
+------------+--------------+
             |
             v
+------------+--------------+
| Chat Class                |
| (systemMessage method)    |
| 1. Add system message     |
+------------+--------------+
             |
             v
+------------+--------------+
| Chat Class                |
| (send method)             |
| 1. Add user message       |
| 2. Send POST request to   |
|    OpenAI API             |
| 3. Receive response       |
| 4. Add assistant response |
+------------+--------------+
             |
             v
+------------+--------------+
| OpenAI API                |
| (Processes request and    |
| returns response)         |
+------------+--------------+
             |
             v
+------------+--------------+
| Chat Class                |
| (send method)             |
| 1. Add second user message|
| 2. Send POST request to   |
|    OpenAI API             |
| 3. Receive response       |
| 4. Add assistant response |
+------------+--------------+
             |
             v
+------------+--------------+
| OpenAI API                |
| (Processes request and    |
| returns response)         |
+------------+--------------+
             |
             v
+------------+--------------+
| Chat Class                |
| (Returns second response  |
| to anonymous function)    |
+------------+--------------+
             |
             v
+------------+--------------+
| Anonymous Function        |
| Returns view 'welcome'    |
| with sillier poem         |
+------------+--------------+
             |
             v
+------------+--------------+
| Laravel View              |
| (Displays poem to user)   |
+---------------------------+

Conclusion

You have successfully integrated the OpenAI API into your Laravel application to generate creative responses. This tutorial covered setting up the project, configuring the environment, creating a custom Chat class, defining routes, and displaying the results in a view. Happy coding!