How use OpenAI in Laravel

Chintan Karia
4 min readDec 27, 2022

--

In this tutorial, we will learn how to use OpenAI’s GPT-3 language model in a Laravel application. We will be building a simple Writebot that uses GPT-3 to generate responses to user input.

Prerequisites

Before we get started, make sure you have the following:

  • A Laravel application. If you don’t have one already, you can create a new Laravel project by running the following command:
composer create-project --prefer-dist laravel/laravel my-project

Installing the OpenAI PHP Client

We will be using the OpenAI PHP Client to interact with the GPT-3 API. To install it, run the following command:

 composer require openai-php/laravel

Then, publish the configuration file:

php artisan vendor:publish --provider="OpenAI\Laravel\ServiceProvider"

Finally, add your API key it in your .env file:

OPENAI_API_KEY=your-api-key

Setting up the Writebot Controller

Next, let’s set up a controller to handle the interaction with GPT-3. Create a new controller called WritebotController using the following artisan command:

php artisan make:controller WritebotController

Open the WritebotController and add the following method:


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use OpenAI;

class WritebotController extends Controller
{
public function generateResponse(Request $request)
{
// Validate the request
$validatedData = $request->validate([
'prompt' => 'required|string|max:1024'
]);

// Create a new OpenAI client
$client = OpenAI::client(env('OPENAI_API_KEY'));

// Set up the GPT-3 request
$response = $client->completions()->create([
'model' => 'text-davinci-002',
'prompt' => $validatedData['prompt'],
'max_tokens' => 2048,
'temperature' => 0.5,
]);


// Render the view and pass the response
return view('writebot', [
'response' => $response->choices[0]->text
]);
}
}

This method accepts a user input (prompt) as a POST request and uses the OpenAI client to generate a response using GPT-3. The response is returned as a JSON object.

Setting up the Routes

Next, let’s set up the routes for our Writebot. Open the routes/web.php file and add the following route:

Route::post('/writebot', 'WritebotController@generateResponse');

This route will point to the generateResponse method in the WritebotController and accept POST requests.

Testing the Writebot

To test our Writebot, we can use a tool like Postman to send a POST request to the /writebot route with a prompt as the request body.

For example, if we send a request with the prompt “What is the capital of Franc, we should receive a response like: “The capital of France is Paris.”

Adding the Writebot to the Laravel Application

Now that we have our Writebot set up, we can add it to our Laravel application. One way to do this is to create a simple form that accepts a prompt and displays the response.

First, let’s create a view for the form. In the resources/views directory, create a new file called writebot.blade.php and add the following code:

<!DOCTYPE html>
<html>
<head>
<title>Writebot</title>
</head>
<body>
<form method="POST" action="/writebot">
@csrf
<label for="prompt">Prompt:</label><br>
<textarea name="prompt" rows="4" cols="50"></textarea><br>
<input type="submit" value="Submit">
</form>
<br>
<div id="response">
@if (isset($response))
{{ $response }}
@endif
</div>
</body>
</html>

This form accepts a user input (prompt) and submits it as a POST request to the /writebot route. The response from the Writebot is displayed below the form.

Next, let’s update the WritebotController to render the view and pass the response to it. Update the generateResponse method to the following:

public function generateResponse(Request $request)
{
// Validate the request
$validatedData = $request->validate([
'prompt' => 'required|string|max:1024'
]);

// Create a new OpenAI client
$client = OpenAI::client(env('OPENAI_API_KEY'));

// Set up the GPT-3 request
$response = $client->completions()->create([
'model' => 'text-davinci-002',
'prompt' => $validatedData['prompt'],
'max_tokens' => 2048,
'temperature' => 0.5,
]);


// Render the view and pass the response
return view('writebot', [
'response' => $response->choices[0]->text
]);
}

Now, when the form is submitted, the generateResponse method will be called and the writebot.blade.php view will be rendered with the response from GPT-3.

Finally, let’s add a route for the Writebot form. In the routes/web.php file, add the following route:

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

This route will render the writebot.blade.php view when a GET request is made to the /writebot route.

Conclusion

In this tutorial, we learned how to use OpenAI’s GPT-3 language model in a Laravel application by creating a simple Writebot. We set up a controller to handle the interaction with GPT-3, set up the routes for the Writebot, and added the Write bot to our Laravel application by creating a form that accepts a user input and displays the response from GPT-3.

There are many other ways you can use GPT-3 in your Laravel applications. For example, you could use it to generate content for your website or to improve the search functionality of your application.

I hope this tutorial has been helpful in getting you started with using GPT-3 in Laravel. If you have any questions or suggestions, please don’t hesitate to ask.

--

--