Getting started with OpenAI using the OpenAI PHP client

January 2nd, 2023

There's alot of hype around ChatGPT, DALL-E, Github Copilot, etc. Personally, I haven't worked in the field of AI nor was I a fan. But you cannot ignore the fact that it's growing rapidly especially with all the auto generated content, be it text, images or videos. Seeing these mind-blowing results from a body of 1s and 0s, I decided to give it a try. This post is going to cover a simple service OpenAI provides — Text Completions — since I'm still new around here. There might be follow up posts with more fun AI stuff!
 

OpenAI

OpenAI has released a bunch of projects such as ChatGPT, DALL-E, Codex, etc. They have made the access to their products easier by providing public APIs. Developers can now integrate them into their own applications. A very popular tool that uses OpenAI is the Github Copilot. Under the hood, Copilot uses Codex to transform natural language prompts into code.

It goes without saying that the usage comes with a cost. Users can start with a free trial which comes with 18$ of free credit and is valid for 3 months. Once the free trial has ended, you must setup a payment method for further use. For personal use and just testing it out, the cost isn't all that high in my opinion. See Pricing for more details.
 

Completions

Text Completions API lets you specify a prompt and generate or manipulate a text. Example from the documentation:

Prompt: Write a tagline for an ice cream shop.
Output: We serve up smiles with every scoop!

You'd use GPT-3 models to achieve desirable results since they are trained for natural language processing. For this post, I'll stick to the most common one, Davinci. There are others like Ada, Babbage and Curie, each of which is good at specific skills. More on this here.
 

Prerequisites

  1. OpenAI account - Free trial works if not fully used up
  2. OpenAI API Key - Login and generate a new key
  3. PHP 8.1 - OpenAI PHP client requires 8.1 or higher
     

Project

We'll be building a motivational quotes generator. It's nothing fancy, it'll be a command line application wherein a quote will be shown when the command is run. Even though it's a basic application, the goal is to show how easy it is to use OpenAI API via the PHP client.
 

Setup

  1. Create a new folder for your project
  2. Initialize Composer and complete the steps
$ composer init
  1. Installing OpenAI PHP Client via Composer
$ composer require openai-php/client

Now that we've got our dependency sorted, lets write some code!
 

QuoteGenerator Class

 

Setting up constants

class QuoteGenerator {
    private const API_KEY = "sk-xxx";  // REPLACE IT WITH YOUR SECRET KEY
    private const COMPLETION_MODEL = 'text-davinci-003';
    private const QUOTE_GENERATION_PROMPT = "Give me a motivational quote";
}

I've added 3 constants to configure the completions API call:

  1. API_KEY: This is the secret key generated from the OpenAI website (don't forget to replace it with your secret key)
  2. COMPLETION_MODEL: The GPT-3 model to use for natural language processing
  3. QUOTE_GENERATION_PROMPT: This is the prompt that will generate the quote. Feel free to be creative/specific!
     

Generate method

public static function generate(): string {
    $client = OpenAI::client(self::API_KEY);

    $result = $client->completions()->create([
        'model' => self::COMPLETION_MODEL,  // Required parameter
        'prompt' => self::QUOTE_GENERATION_PROMPT,
        'max_tokens' => 100,
    ]);

    return $result['choices'][0]['text'] ?? 'Could not generate quote at the moment';
}

The generate method first gets an instance of the OpenAI client. Next, it calls the completion API with the given options provided in the array. Additional parameters like suffix, temperature, top_p, etc, can be provided. I have specified max_tokens so that long quotes still show up and not get cut off midway.

The full list of accepted parameters can be found in the API Reference.
 

Complete class

class QuoteGenerator {
    private const API_KEY = "sk-xxx";
    private const COMPLETION_MODEL = 'text-davinci-003';
    private const QUOTE_GENERATION_PROMPT = "Give me a motivational quote";

    public static function generate(): string {
        $client = OpenAI::client(self::API_KEY);

        $result = $client->completions()->create([
            'model' => self::COMPLETION_MODEL,
            'prompt' => self::QUOTE_GENERATION_PROMPT,
            'max_tokens' => 100,
        ]);

        return $result['choices'][0]['text'] ?? 'Could not generate quote at the moment';
    }
}

Generate file

  1. Create a new file — generate.php
  2. Include the necessary files as shown below
  3. Print the quote!
require 'vendor/autoload.php';  // To load the composer dependencies
require 'QuoteGenerator.php';

echo QuoteGenerator::generate();

Get motivated!

You should now be able run the following command and get motivational quotes:

$ php generate.php

> "The Pessimist Sees Difficulty In Every Opportunity. The Optimist Sees Opportunity In Every Difficulty." - Winston Churchill

OpenAI Laravel

For Laravel developers, the laravel community has developed a package built on top of the openai-php/client. The usage is almost exactly the same, it just provides access to the client as a facade and creates a config file explicitly for any configuration. The package can be found here.