How to integrate OpenAI in Laravel?

How to integrate OpenAI in Laravel

How to integrate OpenAI in Laravel 10 with a practical example from scratch

Integrate OpenAI in Laravel 10

The first step would be to create an account on the official openai website, then we install an sdk with composer, in this case we will use orhanerday/open-ai , we install the corresponding package in a terminal

composer install orhanerday/open-ai

We proceed to create a new controller by entering the following command where a file would be created in the following path nameProject/app/Http/Controllers/CityController.php

php artisan make:controller CityController

We proceed to create and obtain an environment variable in the .env file, the value is obtained with the following function env(‘OPENAI_API_KEY’);

OPENAI_API_KEY = sk-apikey-value-here

In our controller we will use the default index method where we add the following code

 $open_ai_key = env('OPENAI_API_KEY');
 $open_ai = new OpenAi($open_ai_key);
  
    $result = $open_ai->createEdit([
	"model" => "text-davinci-edit-001",
	"input" => $city,			
	"instruction" => "Reasons to move to the ".$city.'?',
	"temperature" => 0.9,			
	]);

return response()->json($result);

We are going to use the davinci model which is the most optimal for development states, here we simply add a value to the city variable and it will show us the reasons for moving to a certain city, returned a json format, remember that this api only allows us to a certain number of requests and then it is time to pay to use the service

Author