DEV Community

Jérôme W
Jérôme W

Posted on • Edited on

Using ChatGPT in a Laravel 10 project

chatgpt and laravel

This tutorial explains how to use ChatGPT in a Laravel 10 project.

I will try to be clear and concise 😃

What you will get

form to ask something to chatgpt

chatgpt answer

Setup

I'm supposing you already installed the Laravel 10 framework, using the official documentation

Step 1: create controller

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class ChatGPTController extends Controller
{
    public function index()
    {
        return view('chatgpt.index');
    }

    public function ask(Request $request)
    {
        $prompt = $request->input('prompt');
        $response = $this->askToChatGPT($prompt);

        return view('chatgpt.response', ['response' => $response]);
    }

    private function askToChatGPT($prompt) 
    {
        $response = Http::withoutVerifying()
            ->withHeaders([
                'Authorization' => 'Bearer ' . env('CHATGPT_API_KEY'),
                'Content-Type' => 'application/json',
            ])->post('https://api.openai.com/v1/engines/text-davinci-003/completions', [
                "prompt" => $prompt,
                "max_tokens" => 1000,
                "temperature" => 0.5
            ]);

        return $response->json()['choices'][0]['text'];
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: create routes

<?php
use App\Http\Controllers\ChatGPTController;
use Illuminate\Support\Facades\Route;

(...)
Route::get('/chatgpt', [ChatGPTController::class, 'index'])
    ->name('chatgpt.index');
Route::post('/chatgpt/ask', [ChatG²PTController::class, 'ask'])
    ->name('chatgpt.ask');
Enter fullscreen mode Exit fullscreen mode

Step 3: create layout

// layouts/app.blade.php
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>My ChatGPT App</title>

        <!-- Styles -->
        <link href="{{ asset('css/app.css') }}" rel="stylesheet">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    </head>
    <body>
        <div class="container mt-5">
            @yield('content')
        </div>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 4: create index view

// chatgpt/index.blade.php
@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Ask something to ChatGPT</div>

                    <div class="card-body">
                        <form method="POST" action="{{ route('chatgpt.ask') }}">
                            @csrf

                            <div class="form-group">
                                <input type="text" class="form-control text-center" name="prompt" placeholder="Ask something...">
                            </div>

                            <button type="submit" class="btn btn-primary">Send</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection
Enter fullscreen mode Exit fullscreen mode

Step 5: create response view

// chatgpt/response.blade.php
@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">ChatGPT answer</div>

                    <div class="card-body">
                        <p>{{ $response }}</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection
Enter fullscreen mode Exit fullscreen mode

Final step 6: create a .env variable

CHATGPT_API_KEY=YOUR_API_KEY
Enter fullscreen mode Exit fullscreen mode

Get the ChatGPT API key

To get the API key, you can go to api-keys section in your openai platform account and generate your key

how generate chatgpt api key

The final word 💬

Thanks for reading this little tutorial, feel free to add a comment to share your opinions! 😀☕

If you want the project I created for this tutorial, feel free to go on the repository

If you want more examples, you can go to the official example section : https://platform.openai.com/examples

Top comments (7)

Collapse
 
stevepop profile image
Steve Popoola

Hello, just a very important thing to note in the example code above. The use of env('CHATGPT_API_KEY'), is wrong. Your key should be set in your config file instead so you can reference this as config('services.chatgpt.api_key)
I needed to highlight this for new devs who may follow this example without realising this.

Collapse
 
jeromew90 profile image
Jérôme W

You pretty right, I just wanted to be more concise but thanks for the information added, it will help devs ^^

Collapse
 
madfortech profile image
MadForCoding

config folder service.php file add this line
config('services.chatgpt.api_key)
can you give more details ?

Collapse
 
stevepop profile image
Steve Popoola

Hi, the config file can be anything to be honest. If you have other configurations related to your chatgpt implementation, you can actually create your own config file, something like config/openai.php and add your settings to it like this;

    'api_key' => env('OPENAI_API_KEY'),
    'organization' => env('OPENAI_ORGANIZATION'),
Enter fullscreen mode Exit fullscreen mode

When you want to make you call, pass this into the headers

'Authorization' => 'Bearer ' . config(openai.api_key),
Enter fullscreen mode Exit fullscreen mode

I hope that's clear.

Collapse
 
jpatrickphelan profile image
Patrick

@stevepop @jeromew90 Thank your for working on this post. After going through all the setup steps I am receiving an error when testing. On the index page when filling out the field "Ask something to ChatGPT" I am receiving a 500 server error as it loads the /ask page. Any tips on what could be wrong? I have followed the documented steps above.

Collapse
 
jpatrickphelan profile image
Patrick

@jeromew90 Via composer did you install a specific php openai library?

Collapse
 
jpatrickphelan profile image
Patrick

After I fill out the form on the index page the form response sends me to the page /chatgpt/ask which then flags a 500 error.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.