OpenAI and it's API integration in a Laravel application

OpenAI and it's API integration in a Laravel application

Exploring OpenAI, models and their integration through the OpenAI API in a Laravel application

In this article, we'll be exploring OpenAI, its models and its practical integration in a Laravel application to meet users' need.

What is OpenAI?

OpenAI is an American Artificial Intelligence (AI) research and deployment company. The aim is to make artificial intelligence (highly autonomous systems that do better than humans at the most profitable tasks)safe and beneficial to everyone.

The OpenAI models can be accessed through their API.

Introduction to OpenAI API

Any activity that involves understanding or producing natural language or code can be used with the OpenAI API. The OpenAI API offers a spectrum of models with different levels of power appropriate for various activities as well as the ability to customize models tailored to one's needs. Everything from content creation to semantic search and classification can be achieved using these models.

Text can be inputted as "prompt" and the model will generate a text completion based on the pattern given.

OpenAI models understand and process text by chunks of characters referred to as Tokens.

"The number of tokens processed in a given API request depends on the length of both your inputs and outputs. As a rough rule of thumb, 1 token is approximately 4 characters or 0.75 words for English text. One limitation to keep in mind is that your text prompt and generated completion combined must be no more than the model's maximum context length (for most models this is 2048 tokens or about 1500 words)."

-OpenAI documentation

OpenAI GPT-3 Models

A collection of models with various capabilities and pricing points (measured by the number of words per token ) powers the OpenAI API. Additionally, you can fine-tune OpenAI fundamental models to fit your unique use case.

  • GPT-3

    GPT-3 has four models that can be used to understand and generate natural language.

    Source: OpenAI Documentation

  • Davinci is the most capable model, and Ada is the fastest.

  • Codex (Limited beta)

    There are currently two Codex models that can be used to understand and generate code.

  • Content Filter

    Similar to Cloud vision text detection the OpenAI content filter currently has three ways of classifying and understanding generated text - Safe, Sensitive, and Unsafe.

Applications of OpenAI models

GPT-3 can be used to perform diverse kinds of natural language tasks (custom text, blog posts, Facebook ads, paraphrasing, resume, developing bio), translation of human language to code using Codex, DALL -E which can be used to generate and modify original images.

Examples of What's possible with OpenAI:

  • Question & Answers

  • Text to command

  • SQL Translate

  • Classification

  • Chat

  • Interview Questions

  • TL;DR summarization and many more...

Authentication

You can use this link to Signup or Login to your account.

Ease to Sign up using email, Google account or Microsoft account

Screenshot 2022-12-06 at 22.57.00.png

Homepage, after successful signup or login.

Screenshot 2022-12-06 at 23.03.47.png

Setup the API Keys

Getting Started with exploring OpenAI applications in a Laravel app.

The applications of OpenAI can be explored in the Playground but we'll be integrating the APIs in a Laravel application to play with the functionalities.

Let's start with a fresh Laravel 9 app installation

laravel new OpenAI_in_Laravel

OR

composer create-project laravel/OpenAI_in_Laravel

After successful installation, change the directory to laravel_chatgpt

cd OpenAI_in_Laravel

Let's serve the application

php artisan serve

We can use Laravel HTTP client or Packages to interact with OpenAI API in a Laravel application.

  • Create a controller OpenAIController
php artisan make:controller OpenAIController
  • Define the models/engines to allow for ease of use and avoid repitition
    private $models = [
        "babbage" => "text-babbage-001",
        "curies" => "text-curie-001",
        "ada" => "text-ada-001",
        "davinci" => "text-davinci-003",
        "code_davinci" => "code-davinci-002"
    ];

HTTP client approach

Create a route to access the method for HTTP client approach

Route::get('/openai/http', [OpenAIController::class, 'open_ai_http']);

In the open_ai_http method use the Laravel HTTP client to communicate with the OpenAI API.

The OpenAI documentation at the time of writing this article does not provide the direct code for PHP integration but the curl approach can be used as a clue on how to communicate with the endpoints.


 public function open_ai_http()
    {

        try {
            $prompt = "OpenAI API is";

            //As a rough rule of thumb, 1 token is approximately 4 characters or 0.75 words for English text
            $maxTokens = 50;

            $open_ai_response = Http::withHeaders([
                'Content-Type' => 'application/json',
                'Authorization' => "Bearer " . env('OPEN_AI_TOKEN')
            ])->post("https://api.openai.com/v1/engines/$this->models['davinci']/completions", [
                'prompt' => $prompt,
                "temperature" => 0.7,
                "max_tokens" => $maxTokens,
                "top_p" => 1,
                "frequency_penalty" => 0,
                "presence_penalty" => 0,
            ])->json();


   return (!$open_ai_response) ?  "No response available!" : $open_ai_response['choices'][0]['text'];
        } catch (\Throwable $th) {
            return  $th;
        }
    }

Outcome

Let's play one more time with the codex model to interpret a python code as shown in the documentation.

Route

// This method uses the http method to access OpenAI API making request to codex models
Route::get('/openai/codex', [OpenAIController::class, 'open_ai_http_codex']);

Method

    public function open_ai_http_codex(){
        try {
            // python code to explain
          $prompt = "class Log:\n    def __init__(self, path):\n        dirname = os.path.dirname(path)\n        os.makedirs(dirname, exist_ok=True)\n        f = open(path, \"a+\")\n\n        # Check that the file is newline-terminated\n        size = os.path.getsize(path)\n        if size > 0:\n            f.seek(size - 1)\n            end = f.read(1)\n            if end != \"\\n\":\n                f.write(\"\\n\")\n        self.f = f\n        self.path = path\n\n    def log(self, event):\n        event[\"_event_id\"] = str(uuid.uuid4())\n        json.dump(event, self.f)\n        self.f.write(\"\\n\")\n\n    def state(self):\n        state = {\"complete\": set(), \"last\": None}\n        for line in open(self.path):\n            event = json.loads(line)\n            if event[\"type\"] == \"submit\" and event[\"success\"]:\n                state[\"complete\"].add(event[\"id\"])\n                state[\"last\"] = event\n        return state\n\n\"\"\"\nHere's what the above class is doing:\n1.";

            //As a rough rule of thumb, 1 token is approximately 4 characters or 0.75 words for English text
            $maxTokens = 64;

            $open_ai_response = Http::withHeaders([
                'Content-Type' => 'application/json',
                'Authorization' => "Bearer " . env('OPEN_AI_TOKEN')
            ])->post("https://api.openai.com/v1/engines/$this->models['code-davinci']/completions", [
                'prompt' => $prompt,
                "temperature" => 0.7,
                "max_tokens" => $maxTokens,
                "top_p" => 1,
                "frequency_penalty" => 0,
                "presence_penalty" => 0,
                "stop" => ["\"\"\""]
            ])->json();


            return (!$open_ai_response) ?  "No response available!" : $open_ai_response['choices'][0]['text'];
        } catch (\Throwable $th) {
            return  $th;
        }
    }

Outcome

With the HTTP client in Laravel, you can directly interact with different models as shown on the Playground page.

Laravel Package approach

Examples of Laravel packages for OpenAI API integration

In this tutorial, we'll explore OpenAI PHP package but kindly note that Laravel package integration for others is pretty straightforward and clearly described in the Readme section of the package on Github.

composer require openai-php/client

OpenAI PHP - Requires PHP 8.1

Next,

Inside the OpenAIController let's create a method to interact with OpenAI API.

<?php

namespace App\Http\Controllers;

use OpenAI;
class OpenAIController extends Controller
{
    private $models = [
        "babbage" => "text-babbage-001",
        "curies" => "text-curie-001",
        "ada" => "text-ada-001",
        "davinci" => "text-davinci-003"
    ];

    public function open_ai()
    {
        $client = OpenAI::client(env('OPEN_AI_TOKEN'));

        $prompt = "What is Laravel framework";

        $result = $client->completions()->create([
            'model' => $this->models['davinci'],
            'prompt' => $prompt,
        ]);

        echo $result['choices'][0]['text'];
    }
}

Next, create a route to access the method

Route::get('/openai', [OpenAIController::class, 'open_ai']);

Visit the route on your browser to see OpenAI GPT-3 in action using davinci model. All text are not displayed because of the tokens specified.

If you're not satisfied with the output... you can retry making the request or increase the tokens for more words.

There are other methods in this package documentation and others to explore.

Conclusion

The OpenAI functionalities and features demonstrated in this tutorial and the documentation is safe and beneficial to everyone which is its core aim.

Twitter: Alemsbaja | Youtube: Tech with Alemsbaja to stay updated on more articles

Find this helpful or resourceful?? kindly share and feel free to use the comment section for questions, answers, and contributions.

Did you find this article valuable?

Support Alemoh Rapheal Baja by becoming a sponsor. Any amount is appreciated!