Laravel 9 Open AI PHP Client

Laravel 9 Open AI PHP Client

Hello there, guys! In today’s post, we will be diving into the world of OpenAI and how it can be utilized in Laravel with the help of the OpenAI PHP API client. The OpenAI PHP API client is a powerful tool that allows developers to interact with the OpenAI API, making it easy to integrate cutting-edge AI models into their Laravel applications.

We’ll explore the various features and capabilities of the client and see how it can be used to create innovative and engaging user experiences. Whether you’re a seasoned developer or just getting started with Laravel, this post will provide you with valuable insights into the potential of OpenAI and how it can be used to enhance your Laravel applications.

Step 1:

Begin by installing a Laravel application.

composer create-project laravel/laravel my-app

Once it’s installed create a controller and a web route. So to create the controller start by running this command

php artisan make:controller SomeController

Step 2:

Once the controller is installed we can now install the Open PHP Client package. Run the following command on your terminal.

composer require openai-php/client

To interact with OpenAI’s API I am using GuzzleHttp\Client. What is it? Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. Guzzle is built on top of the popular PSR-7 standard for HTTP messages.

Guzzle provides a simple interface for creating HTTP requests, handling responses and abstracting away low-level details like sending a stream of data. It also includes built-in support for retries, caching, logging, and other features that are common in modern web services.

It also allows to use middlewares and you can use it to send request, upload files, stream large files and many more.

One of the key feature of guzzle is that it makes working with APIs in PHP simple. GuzzleHttp\Client is a part of the guzzle library, it’s an HTTP client that can be used to interact with web services and APIs. It allows you to create and send HTTP requests and handle HTTP responses, making it easy to interact with web services and APIs.

To install Guzzle, you can use the following command:

composer require guzzlehttp/guzzle

This command will install the latest version of the Guzzle library, which you can then use in your project by including the Composer autoload file in your code, and importing the Guzzle client class. This allows you to use the HTTP client to make requests to web services and API’s.

Now we can begin interacting with OpenAI resources. The first resource we are going to access is the completions, in other words, we will interact with the following tools from OpenAI website.

  • Completions Models
  • List and Retrieve Models
  • Perform Edits on Texts
  • Images

Before we continue what is a model from an OpenAI perspective. A model from OpenAI is a machine learning model that has been trained on a specific dataset and can be used for a specific task. For example, OpenAI provides models for natural language processing (NLP) such as language translation, text summarization, and text generation.

They also provide models for image generation and image recognition. These models can be accessed through the OpenAI API using a client library, such as the OpenAI PHP client, to make requests and receive responses.

Each model has its own unique architecture, and are fine-tuned and trained on different datasets, hence the performance and capabilities of each model vary and can be specialized in a certain area, like image captioning or text summarization.

Step 3:

Now this is out of the way. Let’s start with completions.

Completions.

Completions refers to the process of generating text or other data based on a given prompt or input using a machine learning model. So for us to this in Laravel update the SomeController we created earlier like this

SomeController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Client;

class SomeController extends Controller
{
public function sendRequest()
{
$client = new Client();

$response = $client->post('https://api.openai.com/v1/completions', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer YOUR API_KEY',
],
'json' => [
'prompt' => 'Object oriented programming is',
'max_tokens' => 20,
'model' => 'text-davinci-002',
],
]);

$body = $response->getBody();
$completions = json_decode($body, true);
$completed_text = $completions['choices'][0]['text'];
return $completed_text;
// return response()->json(['completed_text' => $completed_text]);

}
}

First, get an API key from the OpenAPI website.

The script defines a controller class called “SomeController” that has a single method called “sendRequest.” This method creates an instance of the GuzzleHttp\Client class, which is used to make HTTP requests. Then it sends a POST request to the OpenAI API endpoint for completions, passing in a JSON payload that includes a prompt, a maximum number of tokens, and the ID of the model to use for generating the completion. After the response is received, it extracts the text of the completion from the JSON object and returns it.

Update the web.php with this code

web.php

Route::get('/some-route', 'App\Http\Controllers\SomeController@sendRequest');

List and Retrieve Models

You can list and retrieve a model using the following code

a) List Models

SomeController.php

public function sendRequest()
{
$client = new Client();

$response = $client->get('https://api.openai.com/v1/models', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer YOUR API_KEY',
],
]);

$body = $response->getBody();
$model = json_decode($body, true);

return response()->json(['model' => $model]);

}

This code will return all the models to your browser in a JSON format. You can view each model by examining the Id created by or owned by and so forth.

b) Retrieve A Model

You can retrieve a specific model from the open AI website like this.

SomeController.php

public function sendRequest()
{
$client = new Client();

$response = $client->get('https://api.openai.com/v1/models/text-davinci-002', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer  YOUR API_KEY',
],
]);

$body = $response->getBody();
$model = json_decode($body, true);
return $model;
}

Performing Edits

You can edit a given text. Let’s you have texts that contain spelling mistakes. You can input parameters to the model and instruct the model to correct the given input texts like this.

SomeController.php

public function sendRequest()
{
$client = new Client();

$response = $client->post('https://api.openai.com/v1/edits', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer YOUR API_KEY',
],
'json' => [
"model" => "text-davinci-edit-001",
"input" => "What day of the wek is it?",
"instruction" => "Fix the spelling mistakes"
],
]);

$body = $response->getBody();
$edit = json_decode($body, true);
$edited_text = $edit['choices'][0]['text'];
return $edited_text;
// return $edit;

}

The output will be

What day of the week is it?

Images

A model that Creates an image given a prompt. An example would be this…

SomeController.php

public function sendRequest()
{
$client = new Client();

$response = $client->post('https://api.openai.com/v1/images/generations', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer YOUR API_KEY',
],
'json' => [
"prompt"=> "A cute baby sea otter",
"n"=> 2,
"size"=>"1024x1024",
'response_format' => 'url',
]
]);

$responseData = json_decode((string) $response->getBody(), true);
$imageUrls = [];

foreach ($responseData['data'] as $data) {
$imageUrls[] = $data['url'];
}

return $imageUrls;

You can view the images by visiting the URLs in a web browser. For example, you can copy and paste the URLs into the address bar of your browser and press Enter.

To display the images on your application, you can use an HTML img tag. The src attribute of the img tag should be set to the URL of the image.

For example, if you want to display the first image from the URLs you’ve shown, you can use the following code:

<img src="https://oaidalleapiprodscus.blob.core.windows.net/private/org-gqRvDqlAsAAiA2PvTZFyZeEp/user-VIlCuMTQnPrWrITKPozBXmUh/img-9m81XxbpePiVKGfTmPSsWlb7.png?st=2023-01-10T07%3A22%3A12Z&se=2023-01-10T09%3A22%3A12Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-01-10T06%3A45%3A14Z&ske=2023-01-11T06%3A45%3A14Z&sks=b&skv=2021-08-06&sig=QO8W8nfIocTJUbxyTLjISApTlwyYVbB84DnIZqzbB3I%3D">

That’s all for this post. There are other models and of course different other ways to access them. Example, embeddings, Files, Fine-tuning models to your specific data etc. You can access all this in the OpenAI Website 

close

Sign up for free tutorials in your inbox.

We don’t spam! Read our privacy policy for more info.

Leave a Comment

Your email address will not be published. Required fields are marked *