Welcome to CodeCrew Infotech

shape shape
Shape Shape Shape Shape
Blog

Integrating OpenAI with Laravel: A Complete Tutorial

OpenAI is an artificial intelligence research lab and organization that develops and promotes friendly AI for the benefit of humanity. Their work spans various domains, including natural language processing, robotics, and reinforcement learning.

To utilize OpenAI in Laravel, you can follow these steps:

  • Begin by installing the OpenAI package via Composer.
  • Configure the package by providing your API key and other necessary settings in your Laravel application.
  • Use the provided API methods to interact with OpenAI's services within your Laravel codebase.
  • Implement features such as text generation, language translation, or other AI capabilities offered by OpenAI according to your project requirements.
  • Ensure proper error handling and security measures in place when integrating OpenAI with your Laravel application.
  • By following these steps, you can seamlessly incorporate OpenAI's capabilities into your Laravel projects.

1. Create a Project:-

Now, open terminal run this command:

composer create-project laravel/laravel openai-app

After Setup Project:

cd openai-app

Next, we'll need to access the OpenAI API. Head over to https://openai.com/api/ and click on the signup button.

After signing up, navigate to https://beta.openai.com/account/api-keys. Then, click on the button labeled "Create new secret key" and copy the generated key. Paste this key into the .env file within our Laravel project.

OPENAI_API_KEY="**********************"

2.Install package:-

Now, open terminal

 composer require openai-php/client

3. Create Blade File:-

To add a widget to the widgets array, simply append the fully qualified class name of the widget to the array. Make sure to include the namespace and double backslashes for the class name.

For example, to create a blade  "resources/view/generate.blade.php", you would add it like this:

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <style>
        .content-box {
            border: 1px solid #ccc;
            padding: 10px;
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1 class="text-center">Content Generator Using OpenAI Laravel</h1>
        <form action="{{ route('generate-content') }}" method="POST">
            @csrf
            <div class="mb-3">
                <label for="contentInput" class="form-label">Enter Message</label>
                <input type="text" class="form-control" name="message">
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
        @if (!empty($content && $title))
            <div class="content-box" id="displayContent">
                <p>{{ $title }}</p>
                <p>{{ $content }}</p>
            </div>
        @endif
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous">
    </script>
</body>

</html>

Now Let's Add,  routes/web.php, you would add it like this:

  Route::get('/', function () {
    $content = "";
    $title = "";
    return view('generate', compact('content', 'title'));
});

4. Create Controller:-

In this step, we'll create a new  controller similar to GenerateContentController. Run the command below to generate the controller.

 php artisan make:controller GenerateContentController

Now Let's Add,  routes/web.php, you would add it like this:

use App\Http\Controllers\ArticleGenerator;

Route::post('generate', [GenerateContentController::class, 'index'])->name('generate-content');

app/Http/Controllers/GenerateContentController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use OpenAI;

class GenerateContentController extends Controller
{
    public function index(Request $request)
    {
        if ($request->message == null) {
            return;
        }

        $title = $request->message;

        $client = OpenAI::client(env("OPENAI_API_KEY"));

        $response = $client->completions()->create([
            "model" => "gpt-3.5-turbo-instruct",
            "prompt" => $title,
            "max_tokens" => 6,
            "temperature" => 0,
        ]);
        $content = trim($response["choices"][0]["text"]);

        return view("generate", compact("title", "content"));
    }
}

4. Configuration:-

Load the config from `config\app.php`:

'openai_api_key' => env('OPENAI_API_KEY'),

After clearing the cache, run the following command:

php artisan config:cache

4. Run Laravel Project:-

run the following command:

php artisan serve

Now, open your web browser and enter the provided URL to view the application output.

http://localhost:8000

At last, here's how the article appears once generated:

Conclusion:-

In this guide, we've explored the integration of the OpenAI API within a Laravel project. We've walked through the essential steps, from setting up your OpenAI account to leveraging the API within your Laravel application.

Integrating OpenAI into your web projects holds immense potential, offering a gateway to crafting sophisticated, AI-driven applications. With the synergy of OpenAI and Laravel, the horizons of what you can achieve expand boundlessly.

Thank you...