How To Use OpenAI In Laravel 8/9

Websolutionstuff | Feb-06-2023 | Categories : Laravel

In this article, we will explore the integration of OpenAI into Laravel versions 8, 9, and 10. Our focus will be on understanding and utilizing the OpenAI API within Laravel applications. The OpenAI API is a versatile tool that can be employed for a wide range of tasks involving the comprehension and generation of natural language or code.

Additionally, we will introduce the openai-php/client package in Laravel 9 to facilitate your OpenAI integration. This article aims to provide you with practical insights on leveraging OpenAI's capabilities in your Laravel 8, 9, and 10 applications

OpenAI Build next-gen apps with OpenAI’s powerful models. OpenAI is a powerful artificial intelligence platform that allows developers to easily build AI-powered applications.

PHP Libraries:

So, let's see how to use OpenAI in laravel 8, how to use OpenAI in laravel 9, OpenAI PHP example, OpenAI laravel 9, OpenAI tutorial, and laravel OpenAI example.

openai_api

 Step 1: Install laravel 9

In this step, we will install the laravel 9 application using the following composer command.

composer create-project laravel/laravel OpenAI-Example

 

Step 2: Install the OpenAI PHP Package

In this step, we will install the openai-php/client package using the following command. OpenAI PHP is a supercharged PHP API client that allows you to interact with the Open AI API.

Note: Requires PHP 8.1+

composer require openai-php/client

 

Step 3: Configure OpenAI

Now, we need the access key of OpenAI API. So, go to https://openai.com/api/ and click the signup button.

After signing up, go to https://beta.openai.com/account/api-keys and click the button Create new secret key.

.env

OPENAI_API_KEY="xxxxx"

 

 

Step 4: Create Routes

In this step, we create routes in the web.php file.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('text/generate', [App\Http\Controllers\OpenAIController::class, 'index']);
Route::post('/generate', [App\Http\Controllers\OpenAIController::class, 'generateText']);

 

Step 5: Create Controller

In this step, we will create an OpenAIController.php file using the following command.

php artisan make:controller OpenAIController

app/Http/Controllers/OpenAIController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use OpenAI\Client;

class OpenAIController extends Controller
{   
    public function index()
    {
        return view('text_generate');
    }

    public function generateText(Request $input){
        if ($input->title == null) {
            return;
        }
    
        $title = $input->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('text_generate', compact('title', 'content'));

    }
}

Completions:

the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position.

 

Step 6: Create Blade File

In this step, we will create a text_generate.blade.php file.

resources/views/text_generate.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>How To Use OpenAI in Laravel 8/9 - Websolutionstuff</title>

        <!-- Fonts -->
        <link href="https://fonts.bunny.net/css2?family=Space+Grotesk:wght@400;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-3xl 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">
                    <h3 class="text-2xl font-bold">How To Use OpenAI in Laravel 8/9 - Websolutionstuff</h3>
                </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="/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="Enter an article title..." />
                        <button class="rounded-md bg-gray-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-[300px] h-full text-gray-600">
                    <textarea class="min-h-[300px] h-full w-full outline-none" spellcheck="false"></textarea>
                </div>
            </div>
        </div>
    </body>
</html>

 

 

Step 7: Run Laravel Application

Now, we will run how to use the OpenAI API in laravel 8 and laravel 9 using the following command.

php artisan serve

Output:

how_to_use_openai_ in_laravel

 


You might also like:

Recommended Post
Featured Post
Laravel 9 Many To Many Polymorphic Relationship
Laravel 9 Many To Many Polymor...

In this article, we will see laravel 9 many to many polymorphic relationship. many to many polymorphic relationship more...

Read More

Apr-06-2022

Character Count In Textarea
Character Count In Textarea

In this article, we will explain to you how to count characters from textarea. many times a client has requirements...

Read More

Jul-08-2020

How To Roll back Specific Migration In Laravel
How To Roll back Specific Migr...

In this article, we will explore the process of rolling back specific migrations in Laravel, focusing on Laravel version...

Read More

Nov-11-2022

Laravel 8 Class NumberFormatter Not Found
Laravel 8 Class NumberFormatte...

In this example we will see example of laravel 8 class numberformatter not found. For numberformatter we need PHP 5...

Read More

Dec-27-2021