Laravel & Php

How to use Chat GPT API in Laravel?


How to use Chat GPT API in Laravel

Using the Chat GPT API in Laravel is a straightforward process that allows developers to integrate OpenAI’s advanced natural language processing capabilities into their Laravel applications. The Chat GPT API can be used to build chatbots, language models, and other AI-powered applications that can communicate with users in natural language. Laravel is a popular PHP framework that provides developers with a powerful set of tools for building web applications. In this guide, we will explore how to set up and use the Chat GPT API in Laravel, including how to authenticate with the API, send requests, and handle responses. By the end of this guide, you will have a working Laravel application that can leverage the power of the Chat GPT API.

Step 1 : Create OpenAI Account

First you need to create account on OpenAI. then you can easily get account key.

Create Account from here: https://openai.com/product.

After, creating account go to following link and generate key:

Go Here: https://beta.openai.com/account/api-keys.

Next you can get account key and add on .env file as like bellow:

OPENAI_API_KEY=sk-FQolFbZAM6OHS7ddhlS...

Step 2 : Create Route

Now we will create one route for calling our example, so let’s add new route to web.php file as bellow:

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\OpenAIController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('open-ai', [OpenAIController::class, 'index']);

Step 3 : Create Controller

in this step, we will create OpenAIController and write index method. Then we will call OpenAI API and getting data, so let’s add new route to web.php file as bellow:

app/Http/Controllers/OpenAIController.php

<?php

namespace App\Http\Controllers;

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

class OpenAIController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(): JsonResponse
    {
        $search = "laravel get ip address";

        $data = Http::withHeaders([
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer '.env('OPENAI_API_KEY'),
                  ])
                  ->post("https://api.openai.com/v1/chat/completions", [
                    "model" => "gpt-3.5-turbo",
                    'messages' => [
                        [
                           "role" => "user",
                           "content" => $search
                       ]
                    ],
                    'temperature' => 0.5,
                    "max_tokens" => 200,
                    "top_p" => 1.0,
                    "frequency_penalty" => 0.52,
                    "presence_penalty" => 0.5,
                    "stop" => ["11."],
                  ])
                  ->json();

        return response()->json($data['choices'][0]['message'], 200, array(), JSON_PRETTY_PRINT);
    }
}

Run Laravel App:

Now, Go to your web browser, type the given URL and view the app output:

Results are as below


chat GPT Laravel
Share with Friends

Like this chef? Share with friends..