AI, Laravel

Integrating OpenAI with Laravel – Part One

Integrating OpenAI with Laravel

Welcome to the first part of our tutorial on integrating OpenAI with a Laravel application. This tutorial is designed for PHP and Laravel developers who are interested in leveraging the power of AI in their applications. We’ll walk through the process of interacting with the OpenAI API, from setting up authentication to displaying AI-generated content on a web page. Let’s get started!

Prerequisites

  • Basic understanding of PHP and Laravel.
  • Laravel installed on your development machine.
  • An account with OpenAI and access to API keys.

Step 1: Setting Up Your OpenAI Account

Before we start coding, you need to have an OpenAI account. Once you’ve set up your account, navigate to the API section and generate an API key. This key will be used to authenticate your requests to the OpenAI API.

Step 2: Installing Laravel and Setting Up Your Project

If you haven’t already, install Laravel and set up a new project. This tutorial assumes you have a basic Laravel application ready.

Step 3: Configuring Your Environment

  1. OpenAI API Key: Store your API key in your Laravel project’s .env file for secure access. Add the following line to your .env file:
OPENAI_SECRET=your_openai_secret_key_here

Service Configuration: Add your OpenAI configuration to the config/services.php file. This makes your API key accessible throughout your Laravel application:

'openai' => [
    'secret' => env('OPENAI_SECRET'),
],

Step 4: Creating a Route to Fetch and Display AI Content

  1. Update the web.php File: Open the routes/web.php file and create a new route. This route will make a POST request to the OpenAI API and display the response:
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Http;

Route::get('/', function () {
    $response = Http::withToken(config('services.openai.secret'))->post('https://api.openai.com/v1/chat/completions', [
        "model" => "gpt-3.5-turbo",
        "messages" => [
            [
                "role" => "system",
                "content" => "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."
            ],
            [
                "role" => "user",
                "content" => "Compose a poem that explains the concept of recursion in programming."
            ]
        ]
    ])->json();

    return view('welcome', ['poem' => $response['choices'][0]['message']['content']]);
});
  1. Route Definition: Route::get('/', function () {...}); defines a new route in your Laravel application. When a user visits the root URL ('/'), Laravel executes the closure function defined inside Route::get.
  2. Fetching the Poem: Inside the closure function, the first line is making an HTTP POST request to the OpenAI API using the Http facade in Laravel:
    • Http::withToken(config('services.openai.secret')) sets the authorization header for the HTTP request using the OpenAI secret token stored in your config/services.php file, which in turn retrieves it from the .env file.
    • ->post('https://api.openai.com/v1/chat/completions', [...]) sends a POST request to the OpenAI API’s chat completions endpoint. The payload includes:
      • The model you want to use, in this case, “gpt-3.5-turbo”.
      • The messages array containing two messages:
        • A system message that sets the context for the AI (“You are a poetic assistant, skilled in explaining complex programming concepts with creative flair.”)
        • A user message that asks the AI to perform a task (“Compose a poem that explains the concept of recursion in programming.”)
  3. Extracting the Content: ->json('choices.0.message.content'); extracts the content from the response. This navigates through the JSON response to retrieve the actual poem text generated by the AI.
  4. Returning the View: return view('welcome',['poem'=>$poem]); returns the welcome view, passing along the poem content. In the view file (welcome.blade.php), you can display the poem using Blade syntax (e.g., {{ $poem }} or {!! nl2br(e($poem)) !!} for formatted output).

This route is essentially the core of your application’s interaction with OpenAI, handling the request to generate content based on user input (in this case, a predefined input) and then displaying that content in a view

Creating the View: Now, create a welcome.blade.php file in the resources/views directory. This file will be responsible for displaying the AI-generated content:

<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Poems</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="h-full grid place-items-center p-6">
    <div class="text-xs font-sans">
        {!! nl2br(e($poem)) !!}
    </div>
</body>
</html>

Conclusion

You’ve successfully integrated OpenAI with your Laravel application! Now, when you navigate to your application’s root URL, you’ll see a beautifully formatted AI-generated poem. This tutorial has demonstrated the basic steps for interacting with the OpenAI API, setting up authentication, and displaying the response in a Laravel view.

Stay tuned for Part Two, where we’ll delve deeper into customizing requests and handling more complex AI-generated content. Happy coding!

Footnote:

I would like to extend my heartfelt thanks to Jeffrey Way and the entire team at Laracasts for their invaluable tutorials and insights. This tutorial was inspired by and built upon the foundational knowledge shared by Laracasts, and I am deeply grateful for the learning resources they provide to the developer community.