The creation of AI-based applications is made easier for developers by the robust artificial intelligence platform known as OpenAI.
Whether you are a seasoned Laravel developer or just getting started, this article will provide you with the knowledge you need to integrate OpenAI's machine-learning capabilities into your online apps.
We'll cover everything, from setting up your OpenAI account and installing the necessary dependencies to using the OpenAI API and integrating it into your Laravel application.
You'll have a clear knowledge of how to integrate OpenAI into your Laravel projects by the end of this article, and you'll be well on your way to creating web applications that are intelligent and machine learning-powered.
How to use OpenAI in Laravel
1. Install Laravel Project
First, open Terminal and run the following command to create a fresh laravel project:
composer create-project --prefer-dist laravel/laravel openai
or, if you have installed the Laravel Installer as a global composer dependency:
laravel new openai
2. Register to OpenAI
First, we need to get access to API to setup OpenAI. Go to https://openai.com/api and click the signup button.
Once signed up, go to https://beta.openai.com/account/api-keys and click the button. Now create a new secret key, copy it, and put it in our .env
file inside our Laravel project.
OPENAI_API_KEY=<YOUR API KEY>
3. Install OpenAI Client
Install OpenAI Client repository, Run the below command:
composer require openai-php/client
You can experiment with the API using the playground and generate the API call with curl.
The openai-client
package source code is here: https://github.com/openai-php/client.
4. Create Blade Editor
We will create a resources/view/writer.blade.php
blade file.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Writebot - AI Writing Assistant for Bloggers</title>
<!-- Fonts -->
<link href="https://fonts.bunny.net/css2?family=Space+Grotesk:[email protected];600;700&display=swap" rel="stylesheet">
<script src="https://cdn.tailwindcss.com"></script>
<style>
body {
font-family: 'Space Grotesk', sans-serif;
}
.title:empty:before {
content:attr(data-placeholder);
color:gray
}
</style>
<script src="https://unpkg.com/marked" defer></script>
</head>
<body class="antialiased">
<div class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center py-4 sm:pt-0">
<div class="max-w-6xl w-full mx-auto sm:px-6 lg:px-8 space-y-4 py-4">
<div class="text-center text-gray-800 dark:text-gray-300 py-4">
<h1 class="text-7xl font-bold">Writebot</h1>
</div>
<div class="w-full rounded-md bg-white border-2 border-gray-600 p-4 min-h-[60px] h-full text-gray-600">
<form action="/write/generate" method="post" class="inline-flex gap-2 w-full">
@csrf
<input required name="title" class="w-full outline-none text-2xl font-bold" placeholder="Type your article title..." />
<button class="rounded-md bg-emerald-500 px-4 py-2 text-white font-semibold">Generate</button>
</form>
</div>
<div class="w-full rounded-md bg-white border-2 border-gray-600 p-4 min-h-[720px] h-full text-gray-600">
<textarea class="min-h-[720px] h-full w-full outline-none" spellcheck="false">{{ $content }}</textarea>
</div>
</div>
</div>
</body>
</html>
And then, register the UI to write the endpoint, and we will pass an empty variable for $title
and $content
. We will use this later to display the generated content.
// routes/web.php
Route::get('/write', function () {
$title = '';
$content = '';
return view('write', compact('title', 'content'));
});
5. Create a Controller
Create ArticleGeneratorController
controller, run the following command:
php artisan make:controller ArticleGeneratorController
Remember to register the endpoint to our routes.
use App\Http\Controllers\ArticleGeneratorController;
Route::post('/write/generate', [ArticleGeneratorController::class, 'index']);
In the ArticleGeneratorController
, let's add a method index
to get the user input and call the OpenAI API to generate the content we want.
// app/Http/Controllers/ArticleGeneratorController.php
public function index(Request $request)
{
if ($request->title == null) {
return;
}
$title = $request->title;
$client = OpenAI::client(env('OPENAI_API_KEY'));
$result = $client->completions()->create([
"model" => "text-davinci-003",
"temperature" => 0.7,
"top_p" => 1,
"frequency_penalty" => 0,
"presence_penalty" => 0,
'max_tokens' => 600,
'prompt' => sprintf('Write article about: %s', $title),
]);
$content = trim($result['choices'][0]['text']);
return view('write', compact('title', 'content'));
}
Load the config from config/app.php
:
'openai_api_key' => env('OPENAI_API_KEY'),
Then run the config cache command to optimize the system call to get the env
value.
php artisan config:cache
Now you can use the config like this :
$client = OpenAI::client(config('app.openai_api_key'));
6. Run Laravel
Now, we will run the laravel application using the following command.
php artisan serve
Thank you for reading this article.
Read Also: Laravel 9 Custom Email Verification Tutorial