Pusher real-time Notification with Laravel and React.js
Read More
OpenAI is an advanced artificial intelligence platform that enables developers to create AI-powered applications with minimal effort.
Whether you are an experienced Laravel developer or just getting started, this tutorial will walk you through the steps needed to incorporate OpenAI's machine learning capabilities into your web applications. We will go over everything from creating your OpenAI account and installing the required dependencies to using OpenAI's API and integrating it into your Laravel application.
Note: we are used laravel 10 + version and with latest openai api
here is some deprecated openai api : https://platform.openai.com/docs/deprecations
By the end of this tutorial, you'll have a solid understanding of how to use OpenAI in your Laravel projects and be well on your way to building intelligent, machine learning-powered web applications.
OpenAI PHP for Laravel is a community-maintained PHP API client that allows you to interact with the Open AI API. If you or your business relies on this package, it's important to support the developers who have contributed their time and effort to create and maintain this valuable tool:
Let us begin a new Laravel project. This app will help our users write articles with any title they specify. I understand that this sounds familiar, but my goal is to help you understand what it takes to use OpenAI in your Laravel project.
laravel new laravelopenai
Next, we need to gain access to the OpenAI API. First, go to https://openai.com/api/ and click the signup button If not, register.
After signing up, go to https://beta.openai.com/account/api-keys and click the button Create a new secret key, copy the key, and put it in our.env file inside our Laravel project.
OPEN_AI_TOKEN=sk-z......................
Actually, you should be able to interact directly with the API endpoint, but if you do not want to, we can use this package instead.
composer require openai-php/client
The openai-client package source code is here: https://github.com/openai-php/client.
The next step is to create a view that will display the generated article to the user. We can also add a button that allows the user to create a new article if they are dissatisfied with the current one.
Finally, we can add a feature that allows users to save the generated article for future reference. We will make a simple editor for our generate-article web app.
We will use CDN TailwindCSS, which eliminates the need to install the npm package, making application development easier and faster. Save it to resources/view/generate-aritcle.blade.php.
<!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:wght@400;600;700&display=swap" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<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">Generate Articles</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 class="inline-flex gap-2 w-full" id="interview-questions-search">
@csrf
<input required name="title" class="w-full outline-none text-2xl font-bold"
placeholder="Type your article title..." />
<button type="submit" 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" id="search-results">
</textarea>
</div>
</div>
</div>
{{-- wants submit form using ajax call --}}
<script>
$(document).ready(function() {
$('#interview-questions-search').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: "{{ route('generateArticle') }}",
method: "POST",
data: $(this).serialize(),
success: function(response) {
$('#search-results').html(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
</body>
</html>
We use Ajax scripts to store and retrieve data.
<script>
$(document).ready(function() {
$('#interview-questions-search').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: "{{ route('generateArticle') }}",
method: "POST",
data: $(this).serialize(),
success: function(response) {
$('#search-results').html(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
Then register the UI to generate an article endpoint, or something similar.
Route::get('/generate-aritcle', function () {
return view('generate-aritcle');
});
Let us add a controller to accept user input and use the OpenAI package to generate our article.
php artisan make:controller GenerateArticleController
Please remember to register the endpoint for our routes.
use App\Http\Controllers\GenerateArticleController;
Route::post('/generate-article', [GenerateArticleController::class, 'generateArticle'])->name('generateArticle');
Let us add the 'generateArticle' method to the GenerateArticleController to collect user input and then use the OpenAI API to generate the desired content.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use OpenAI;
class GenerateArticleController extends Controller
{
public function generateArticle(Request $request)
{
$title = $request->title;
$client = OpenAI::client(env('OPEN_AI_TOKEN'));
$result = $client->completions()->create([
'model' => 'gpt-3.5-turbo-instruct',
'prompt' => sprintf('Write article about: %s', $title),
'temperature' => 0.7,
'top_p' => 1.0,
'frequency_penalty' => 0.0,
'presence_penalty' => 0.0,
'best_of' => 1,
'max_tokens' => 600,
]);
return response()->json(trim( $result['choices'][0]['text']));
}
}
Then use the config cache command to optimize the system call for the env value.
php artisan config:cache
Finally, here's how the article would appear if it were created by the user.
This tutorial taught us how to use the OpenAI API with a Laravel project. We covered how to create an OpenAI account, use the API, and integrate it into a Laravel application.
Using OpenAI in your web applications can open up a whole new world of possibilities and allow you to create powerful AI-powered applications. When you combine OpenAI and Laravel, the possibilities are limitless.
Anyway, thank you for reading this article. I hope it helps you develop your own AI-powered Laravel app. I sincerely appreciate it.
Recent posts form our Blog
0 Comments
Like 1