March 7, 2024 | Posted in AI, 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!
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.
If you haven’t already, install Laravel and set up a new project. This tutorial assumes you have a basic Laravel application ready.
.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'),
],
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']]);
});
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
.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:
model
you want to use, in this case, “gpt-3.5-turbo”.messages
array containing two messages:
system
message that sets the context for the AI (“You are a poetic assistant, skilled in explaining complex programming concepts with creative flair.”)user
message that asks the AI to perform a task (“Compose a poem that explains the concept of recursion in programming.”)->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.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>
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.