Loading image
OpenAI for Laravel : A Comprehensive Guide

OpenAI for Laravel : A Comprehensive Guide

  • showkat ali
  • 18th Feb, 2024
  • 329
  • 0

How can we use OpenAI with Laravel?

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:

Create new Project

Let us start a new Laravel project. This app will assist our users in writing articles for any title they specify. I realize this sounds familiar, but the goal is to help you understand what it takes to use OpenAI in your Laravel project.

laravel new laravelopenai

Register to OpenAI

Next, we need to get access to the OpenAI API. First, go to https://openai.com/api/ and click the signup button If not, sign up.

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......................

Install OpenAPI client

Actually, you should be able to interact with the endpoint of the API directly, but if you don't want to do that, we can use this package.

composer require openai-php/client

The openai-client package source code is here: https://github.com/openai-php/client.

 

Create a user interface (blade)

Next, we need to create a view that will show the generated article to the user. We can also include a button that allows the user to create a new article if they are dissatisfied with the current one.

Finally, we can include a feature that allows users to save the generated article for later reference. We will create a very simple editor for our generate-article web app.

We will use the CDN TailwindCSS, so we don't need to install the npm package, making the development of our application simpler 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');
});

Make Controller

Let us now add a controller to receive user input and call the OpenAI package to generate our article.

php artisan make:controller GenerateArticleController

Don't forget 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 get user input and then call 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 run the config cache command to optimize the system call to get the env value.

php artisan config:cache

Finally, here's how the article would appear if it were created by the user.

 

 

Conclusion

In this tutorial, we learned how to use the OpenAI API with a Laravel project. We have covered the steps for creating an OpenAI account, using the API, and integrating it into a Laravel application.

Using OpenAI in your web applications can open up a new world of possibilities and enable you to build powerful, AI-powered applications. The possibilities are endless when you combine OpenAI and Laravel.

Anyway, thanks for reading this article. I hope it helps you create your own AI-powered Laravel app. I appreciate it.

showkat ali

Greetings, I'm a passionate full-stack developer and entrepreneur based in Pakistan. I specialize in PHP, Laravel, React.js, Node.js, JavaScript, and Python. I own interviewsolutionshub.com, where I share tech tutorials, tips, and interview questions. I'm a firm believer in hard work and consistency. Welcome to interviewsolutionshub.com, your source for tech insights and career guidance

0 Comments

Please log in to leave a comment.