How to connect Laravel with ChatGPT step by step (OpenAI API)

Let's look at the steps to connect ChatGPT to a Laravel project, although the steps are practically the same for any other technology. The only slight change is how you make the call.

1. Install the package for HTTP requests

The first thing we need is a package for making HTTP requests, in case you don't have it installed.

In Laravel, it usually comes by default, so you shouldn't have any problems. But if you don't have it, install it as usual:

$ composer require guzzlehttp/guzzle

2. Get the OpenAI API key

The next step is to obtain your ChatGPT API key.
To do so, go to the official OpenAI website:

https://platform.openai.com/api-keys

There you'll see a screen like this. Click "Create new secret key," give it any name (it can be your project name), and create the key.
Once generated, save it to your Laravel project.

3. Create the view

We create a controller with a simple HTML view containing a form for submitting the query:

A <textarea> to enter the question.

A Submit button:

resources\views\chatgtp\textarea.blade.php

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <form action="{{ route('gtp-1') }}" method="post">
        @csrf
        <textarea name="ask"></textarea>
        <button type="submit">{{ __('Send') }}</button>
    </form>
</body>

</html>

Here, as you can see, we have two routes:

A GET route to display the form.

A POST route to process the question.

routes\web.php

Route::get('chatgtp', [ChatGTPController::class, 'textarea']);
Route::post('chatgtp/ask1', [ChatGTPController::class, 'ask'])->name('gtp-1');

Additionally, we gave the route a name to easily reference it from the view.

4. Controller: Make the request to the API

Using the already installed HTTP package, we make a request to the OpenAI API. Here's a basic example structure:

  1. OpenAI endpoint URL.
  2. The model to use (in my case, the free one: gpt-3.5-turbo).
  3. The message with:
  4. Role: "user".
  5. Content: The question entered.
  6. temperature: A value that defines the creativity of the answer (you can try 0.7, for example).

You can also place a dd() or dump() to see what the API returns.

app\Http\Controllers\Dashboard\ChatGTPController.php

<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Http;

class ChatGTPController extends Controller
{

    public function textarea()
    {
        return view('chatgtp.textarea');
    }

    public function ask(): string
    {

        $response = Http::withToken(env('OPENAI_API_KEY'))
            ->post('https://api.openai.com/v1/chat/completions', [
                'model' => 'gpt-3.5-turbo',
                'messages' => [
                    ['role' => 'user', 'content' => request('ask')],
                ],
                'temperature' => 0.7,
            ]);
            dd($response->json());
        return $response->json()['choices'][0]['message']['content'] ?? 'No hubo respuesta.';
    }
}

5. Set the key in .env

You can save the key directly in your .env file, for example:

.env

OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxx

And then retrieve it in your code with env('OPENAI_API_KEY').

I agree to receive announcements of interest about this Blog.

We show you the steps to connect your Laravel app to ChatGTP.

- Andrés Cruz

En español