OpenAI and it’s API integration in a Laravel application

AuthorSumit Dey Sarkar

Pubish Date01 Apr 2023

categoryLaravel

In this tutiorial we will learn OpenAI and it’s API integration in a Laravel application.

OpenAI and it’s API integration in a Laravel application

OpenAI and it’s API integration in a Laravel application

 

What is open AI?

OpenAI is an artificial intelligence research laboratory.

It aims to create safe and beneficial AI for everyone.

OpenAI conducts research and develops AI tools and software.

 

How to integrate openAI API in a Laravel application

To integtate Chat GPT API in Laravel application, you need to follow below steps:

 

Step 1 - In first step you need to nstall the OpenAI SDK using following command in your Laravel project directory

composer require openai/openai

 

Step 2 - Create an OpenAI API key by signing up for an account on the OpenAI website.

 

 

Step 3 -  Add your API key to your Laravel project's .env file

OPENAI_API_KEY=your_api_key_here

 

Step 4 - Create a new controller in your Laravel project by running the following command:

php artisan make:controller OpenAIController

 

Step 5 - In your OpenAIController, import the OpenAI namespace and set up the API credentials

<?php

namespace App\Http\Controllers;

use OpenAI;

class OpenAIController extends Controller
{
    public function chatGPT()
    {
        OpenAI::setApiKey(env('OPENAI_API_KEY'));
        // Your code goes here
    }
}

 

Step 6 - In the chatGPT method of your OpenAIController, call the appropriate OpenAI API method to perform the desired action. For example, to generate text using the Chat GPT model, you can use the following code

$response = OpenAI::completion([
    'engine' => 'davinci',
    'prompt' => 'Hello,',
    'max_tokens' => 5,
    'temperature' => 0.5,
]);

$text = $response['choices'][0]['text'];

return response()->json(['text' => $text]);

In this example, the completion method is used to generate a short text completion given a prompt. The max_tokens and temperature parameters control the length and randomness of the generated text, respectively.

 

Step 7 - Finally, you can create a route in your routes/web.php file to call the chatGPT method of your OpenAIController. For example:

Route::get('/chat', [OpenAIController::class, 'chatGPT']);

 

Step 8 - You may want to create a form or user interface to allow users to input their desired prompts and see the generated text. You can do this by creating a view in your Laravel project, which can be loaded by the chatGPT method of your controller. For example, you can create a chat.blade.php file in the resources/views directory with the following code

<!DOCTYPE html>
<html>
<head>
    <title>Chat with GPT</title>
</head>
<body>
    <form method="POST" action="{{ route('chat') }}">
        @csrf
        <label for="prompt">Prompt:</label>
        <input type="text" name="prompt" id="prompt">
        <br>
        <button type="submit">Generate</button>
    </form>

    @if ($text)
        <p>{{ $text }}</p>
    @endif
</body>
</html>

 

Step 9 - Modify your chatGPT method in your controller to handle the form submission and return the generated text to the view. For example

public function chatGPT(Request $request)
{
    OpenAI::setApiKey(env('OPENAI_API_KEY'));

    $text = null;

    if ($request->isMethod('post')) {
        $response = OpenAI::completion([
            'engine' => 'davinci',
            'prompt' => $request->input('prompt'),
            'max_tokens' => 50,
            'temperature' => 0.5,
        ]);

        $text = $response['choices'][0]['text'];
    }

    return view('chat', ['text' => $text]);
}

In the above example, the chatGPT method checks if the HTTP method is POST, which indicates that the form has been submitted. If so, it generates text using the Chat GPT model and assigns the result to the $text variable. The method then returns the chat.blade.php view with the $text variable passed to it.

 

Step 10 - Finally, create a route in your routes/web.php file that maps to the chatGPT method of your controller. For example

Route::get('/chat', [OpenAIController::class, 'chatGPT'])->name('chat');
Route::post('/chat', [OpenAIController::class, 'chatGPT'])->name('chat.post');

In the above example, two routes are defined for the chatGPT method: one for the initial page load (GET method) and one for form submissions (POST method). The name method is used to name the routes, which can be used to generate URLs in your views using the route function.

Now you have a Laravel application that allows users to chat with the Chat GPT model. This is just a basic example but you can modify it according to your needs.

Comments 0

Leave a comment