OpenAI PHP extension library

The OpenAI PHP is an extension that allows PHP developers to integrate the powerful capabilities of OpenAI into their applications. Activating the extension on the web server will allow users to quickly access the services offered by OpenAI without additional libraries in PHP.

C++ PHP 7.4 PHP 8.0 PHP 8.1 PHP 8.2 PHP 8.3 License MIT Version 1.0.0

OpenAI PHP extension is written in C++, allowing for faster execution than pure PHP code, and they can access system-level resources that may not be available through PHP alone. Activating the extension on the web server will allow users to quickly access the services offered by OpenAI.

To use the OpenAI PHP extension, you need to download a library designed for a specific version of PHP. The compiled version of the library is available for Linux and Windows. Just download the library and activate it in the php.ini file. You can also build a library from the source code available on GitHub.

Download

Latest version 1.0.0 (2023-05-23)
Download the binary package for PHP 7.4, PHP 8.0, PHP 8.1, PHP 8.2 and PHP 8.3.

64bit binaries:

Linux (Ubuntu):Linux (Ubuntu) 64bit | tar.gz Linux (Ubuntu) 64bit | zip
Windows:Windows 64bit | tar.gz Windows 64bit | zip

Source code on GitHub

Installation and configuration

Linux

Before installation, check the installed version of PHP (NTS - non-tread safe, ZTS - thread safe) on your system with the command:

php -v

Sample result:

PHP 8.3.1 (cli) (built: Dec 20 2023 14:06:30) (NTS Visual C++ 2019 x64)
Copyright (c) The PHP Group
Zend Engine v4.3.1, Copyright (c) Zend Technologies

Unzip the archive and enter the root directory, for example:

tar xf openai-php-binary-linux.tar.gz
cd openai-php-binary-linux

Now, you can use the PHP, MODE and ZTS parameters in the make command. PHP means the PHP version (7.4, 8.0, 8.1, 8.2, 8.3), MODE means operating modes (cli, fpm or apache2) and ZTS means thread safe (enable) or non-thread safe (disable) version.

The syntax for make is:

make PHP=7.4,8.0,8.1,8.2,8.3 MODE=cli,fpm,apache2 ZTS=enable,disable

For example, to install the extension for PHP 8.3, execute the command:

for PHP 8.3 ZTS (thread safe), CLI mode:

make PHP=8.3 MODE=cli ZTS=enable

for PHP 8.3 NTS (non-thread safe), FPM mode:

make PHP=8.3 MODE=fpm ZTS=disable

By default, if MODE parameter is not defined, the extension is installed for the PHP CLI.

Done! You may need to reload the webserver.

To uninstall the extension, execute the command:

make PHP=7.4,8.0,8.1,8.2,8.3 MODE=cli,fpm,apache2 uninstall

Windows

Download the latest release of binaries for Windows. Find the directory where PHP is installed and then upload the extension to the ext directory. For example, if you have installed the XAMPP on your C drive, upload the extension to the C:\xampp\php\ext directory.

Activate the extension by adding the following line to the php.ini file:

extension=openai.dll

Installation from source code

Instruction on how install the extension from source codes is on the GtHub repository page.

After installation and configuration

Use the phpinfo() function to get detailed information about active extensions in PHP.

OpenAI PHP

Basic usage

Below is a sample PHP code for chatting with OpenAI. The description of the constants defined in the extension is here.

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    $response = $OpenAI->chat(request:
    [
        "model"    => "gpt-3.5-turbo",
        "messages" => 
        [
            "role"    => "user",
            "content" => "Do you know Elon Musk?"
        ]
    ], response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY);

    print_r($response);
}
catch (Exception $e)
{
    echo("Hmm, something went wrong :(").PHP_EOL;
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [choices] => Array
        (
            [finish_reason] => stop
            [index] => 0
            [message] => Array
                (
                    [content] => Yes, Elon Musk is a well-known entrepreneur and innovator, founder and CEO of companies such as Tesla, SpaceX, Neuralink, and The Boring Company. He is also known for his ambitious plans to colonize Mars and his work on electric cars, solar power, and space exploration.
                    [role] => assistant
                )

        )

    [created] => 1684159459
    [id] => chatcmpl-7GT6BqqvwVELlVGxyheAztsT438jd
    [model] => gpt-3.5-turbo-0301
    [object] => chat.completion
    [usage] => Array
        (
            [completion_tokens] => 59
            [prompt_tokens] => 14
            [total_tokens] => 73
        )

)

Advanced usage

Enable or disable the saving of logs to a file

The OpenAI PHP extension allows you to save all requests sent to the OpenAI system and all responses to log files. You can activate this function globally in the php.ini file:

openai.log_enable = 1
openai.log_filepath = "./openai.log"

Enabling this feature may increase server load, so the optimal option is to activate logging by the user. An example of activating this function in PHP code by the user might be:

define("OPENAI_LOG_ENABLE", 1);
define("OPENAI_LOG_FILEPATH", "./openai.log");

The format of the returned data

The default response parameter value is OpenAI::PHP_OPENAI_RESPONSE_ARRAY. This means that all functions return data as arrays by default. To return data in JSON format, use the OpenAI::PHP_OPENAI_RESPONSE_JSON constants.

$models = $OpenAI->models(
    response: OpenAI::PHP_OPENAI_RESPONSE_JSON
);

PHP 7

In PHP 7 (and earlier versions), function parameters are declared with a dollar sign followed by the parameter name, like this:

<?php
namespace OpenAI;

$OpenAI = new OpenAI($api_key = "YOUR_API_KEY");

$models = $OpenAI->models(
    $response = OpenAI::PHP_OPENAI_RESPONSE_ARRAY
);

Using methods

Class synopsis

class OpenAI
{
    /* Constants */
    const int PHP_OPENAI_RESPONSE_ARRAY       11
    const int PHP_OPENAI_RESPONSE_JSON        12

    const int PHP_OPENAI_IMAGE_CREATE         21
    const int PHP_OPENAI_IMAGE_EDIT           22
    const int PHP_OPENAI_IMAGE_VARIATION      23

    const int PHP_OPENAI_AUDIO_TRANSCRIPTION  31
    const int PHP_OPENAI_AUDIO_TRANSLATION    32

    const int PHP_OPENAI_FILE_LIST            41
    const int PHP_OPENAI_FILE_UPLOAD          42
    const int PHP_OPENAI_FILE_DELETE          43
    const int PHP_OPENAI_FILE_RETRIEVE        44
    const int PHP_OPENAI_FILE_CONTENT         45

    const int PHP_OPENAI_FINETUNE_CREATE      51
    const int PHP_OPENAI_FINETUNE_LIST        52
    const int PHP_OPENAI_FINETUNE_RETRIEVE    53
    const int PHP_OPENAI_FINETUNE_CANCEL      54
    const int PHP_OPENAI_FINETUNE_EVENTS      55
    const int PHP_OPENAI_FINETUNE_DELETE      56

    /* Methods */
    public __construct(string api_key, ?string org_id)
    public models(?int response): array|string
    public model(string model, ?int response): array|string
    public completion(array request, ?int response): array|string
    public chat(array request, ?int response): array|string
    public edit(array request, ?int response): array|string
    public image(array request, int create, ?int response): array|string
    public embedding(array request, ?int response): array|string
    public audio(array request, int create, ?int response): array|string
    public file(array request, int command, ?int response): array|string
    public fineTune(array request, int command, ?int response): array|string
    public moderation(array request, ?int response): array|string
}

Constructs a new OpenAI object

<?php
namespace OpenAI;

$OpenAI = new OpenAI(
    api_key: "YOUR_API_KEY",
    org_id: "YOUR_ORG_ID"    // optional
);

Parameters:

  • api_key: string (required)
  • org_id: string

Class methods

Predefined constants

The constants below are defined by this extension and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

ConstantValue
OpenAI::PHP_OPENAI_VERSION
Extension version, e.g. "1.0.0"
1.0.0
Type of returned results
OpenAI::PHP_OPENAI_RESPONSE_ARRAY
Returns the results in an array
11
OpenAI::PHP_OPENAI_RESPONSE_JSON
Returns results in JSON format
12
OpenAI images
OpenAI::PHP_OPENAI_IMAGE_CREATE
Create image
21
OpenAI::PHP_OPENAI_IMAGE_EDIT
Create image edit
22
OpenAI::PHP_OPENAI_IMAGE_VARIATION
Create image variation
23
OpenAI audio
OpenAI::PHP_OPENAI_AUDIO_TRANSCRIPTION
Create transcription
31
OpenAI::PHP_OPENAI_AUDIO_TRANSLATION
Create translation
32
OpenAI files
OpenAI::PHP_OPENAI_FILE_LIST
List files
41
OpenAI::PHP_OPENAI_FILE_UPLOAD
Upload file
42
OpenAI::PHP_OPENAI_FILE_DELETE
Delete file
43
OpenAI::PHP_OPENAI_FILE_RETRIEVE
Retrieve file
44
OpenAI::PHP_OPENAI_FILE_CONTENT
Retrieve file content
45
OpenAI fine-tunes
OpenAI::PHP_OPENAI_FINETUNE_CREATE
Create fine-tune
51
OpenAI::PHP_OPENAI_FINETUNE_LIST
List fine-tunes
52
OpenAI::PHP_OPENAI_FINETUNE_RETRIEVE
Retrieve fine-tune
53
OpenAI::PHP_OPENAI_FINETUNE_CANCEL
Cancel fine-tune
54
OpenAI::PHP_OPENAI_FINETUNE_EVENTS
List fine-tune events
55
OpenAI::PHP_OPENAI_FINETUNE_DELETE
Delete fine-tune model
56
Saving logs to a file, the value depends on the settings in the php.ini file.
OpenAI::PHP_OPENAI_LOG_ENABLE
Enabled (1) or disabled (0) saving logs to a file
0 or 1
OpenAI::PHP_OPENAI_LOG_FILE
The name of the file where the logs are saved
./openai.log

About OpenAI

OpenAI API is a cloud-based platform that provides access to OpenAI's language models and tools through a simple API (Application Programming Interface).

Once you have your API key, you can use it to access the OpenAI API through your code. Note that there may be usage limits or fees associated with different API plans, so make sure to read the documentation carefully before starting to use the API.

OpenAI models

The OpenAI list models and retrieve model allows for selecting the appropriate language model for a particular natural language processing (NLP) task. This enables developers to tailor the choice of model to their needs and constraints related to hardware resources and costs.

For example, the list models API provides a view of available language models and their descriptions, including information on their size, performance, and application areas. When selecting the appropriate model, the retrieve model API allows for downloading a specific model from the OpenAI server, along with information on its configuration and parameters.

Method

public models(?int response): array|string

Parameters

response

  • OpenAI::PHP_OPENAI_RESPONSE_ARRAY (default)
  • OpenAI::PHP_OPENAI_RESPONSE_JSON

Return values

Depending on the response parameter, the returned value is an array or text in JSON format.

Method

public model(string model, ?int response): array|string

Parameters

model

  • model name e.g. "gpt-3.5-turbo"

response

  • OpenAI::PHP_OPENAI_RESPONSE_ARRAY (default)
  • OpenAI::PHP_OPENAI_RESPONSE_JSON

Return values

Depending on the response parameter, the returned value is an array or text in JSON format.

Example 1 (List models)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* List models */
    $models = $OpenAI->models(
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print "List of currently available models:".PHP_EOL;
    foreach($models["data"] as $model)
    {
        print "Model ID: ".$model["id"].PHP_EOL;
    }
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

List of currently available models:
Model ID: whisper-1
Model ID: babbage
Model ID: davinci
Model ID: text-davinci-edit-001
Model ID: babbage-code-search-code
Model ID: text-similarity-babbage-001
Model ID: code-davinci-edit-001
Model ID: text-davinci-001
Model ID: ada
Model ID: text-davinci-003
Model ID: babbage-code-search-text
Model ID: babbage-similarity
Model ID: code-search-babbage-text-001
Model ID: gpt-3.5-turbo-0301
Model ID: text-curie-001
Model ID: code-search-babbage-code-001
Model ID: text-ada-001
Model ID: text-embedding-ada-002
Model ID: text-similarity-ada-001
Model ID: curie-instruct-beta
Model ID: gpt-3.5-turbo
Model ID: ada-code-search-code
Model ID: ada-similarity
Model ID: code-search-ada-text-001
Model ID: text-search-ada-query-001
Model ID: davinci-search-document
Model ID: ada-code-search-text
Model ID: text-search-ada-doc-001
Model ID: davinci-instruct-beta
Model ID: text-similarity-curie-001
Model ID: code-search-ada-code-001
Model ID: ada-search-query
Model ID: text-search-davinci-query-001
Model ID: curie-search-query
Model ID: davinci-search-query
Model ID: babbage-search-document
Model ID: ada-search-document
Model ID: text-search-curie-query-001
Model ID: text-search-babbage-doc-001
Model ID: curie-search-document
Model ID: text-search-curie-doc-001
Model ID: babbage-search-query
Model ID: text-babbage-001
Model ID: text-search-davinci-doc-001
Model ID: text-search-babbage-query-001
Model ID: curie-similarity
Model ID: curie
Model ID: text-similarity-davinci-001
Model ID: text-davinci-002
Model ID: davinci-similarity
Model ID: cushman:2020-05-03
Model ID: ada:2020-05-03
Model ID: babbage:2020-05-03
Model ID: curie:2020-05-03
Model ID: davinci:2020-05-03
Model ID: if-davinci-v2
Model ID: if-curie-v2
Model ID: if-davinci:3.0.0
Model ID: davinci-if:3.0.0
Model ID: davinci-instruct-beta:2.0.0
Model ID: text-ada:001
Model ID: text-davinci:001
Model ID: text-curie:001
Model ID: text-babbage:001

Example 2 (Retrieve model)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Retrieve model */
    $model = $OpenAI->model(
        model: "gpt-3.5-turbo",
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print "Basic information about the gpt-3.5-turbo model:".PHP_EOL;
    print_r($model);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Basic information about the gpt-3.5-turbo model:
Array
(
    [created] => 1677610602
    [id] => gpt-3.5-turbo
    [object] => model
    [owned_by] => openai
    [parent] => null
    [permission] => Array
        (
            [allow_create_engine] => false
            [allow_fine_tuning] => false
            [allow_logprobs] => true
            [allow_sampling] => true
            [allow_search_indices] => false
            [allow_view] => true
            [created] => 1683852530
            [group] => null
            [id] => modelperm-C34BeeteYvuLNoa893aJRcnp
            [is_blocking] => false
            [object] => model_permission
            [organization] => *
        )

    [root] => gpt-3.5-turbo
)

OpenAI completions

The OpenAI completions can be used for generating text completions based on a given prompt. It is particularly useful for applications such as text generation, language translation and chatbots.

For example, the API can be used to generate personalized email responses, chatbot messages, or product descriptions. It can also be used for language translation, where the API can translate text between different languages with high accuracy.

Method

public completion(array request, ?int response): array|string

Parameters

request

  • array with parameters:
    • model: string (required)
    • prompt: string|array
    • suffix: string
    • max_tokens: int
    • temperature: float
    • top_p: float
    • n: int
    • stream: bool
    • logprobs: int
    • echo: bool
    • stop: string|array
    • presence_penalty: float
    • frequency_penalty: float
    • best_of: int
    • logit_bias: string
    • user: string

response

  • OpenAI::PHP_OPENAI_RESPONSE_ARRAY (default)
  • OpenAI::PHP_OPENAI_RESPONSE_JSON

Return values

Depending on the response parameter, the returned value is an array or text in JSON format.

Example

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Create completion */
    $completion = $OpenAI->completion(request: 
    [
        "model"       => "text-davinci-003",
        "prompt"      => "Silesia is famous for its",
        "max_tokens"  => 12,
        "temperature" => 1,
        "top_p"       => 1,
        "n"           => 2,
        "stream"      => false,
        "logprobs"    => null,
        "stop"        => "\n"
    ], response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY);

    print_r($completion);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [choices] => Array
        (
            [0] => Array
                (
                    [finish_reason] => stop
                    [index] => 0
                    [logprobs] => null
                    [text] =>  coal mining
                )

            [1] => Array
                (
                    [finish_reason] => stop
                    [index] => 1
                    [logprobs] => null
                    [text] =>  coal mining and steel production activities
                )

        )

    [created] => 1684160275
    [id] => cmpl-7GTJLfzba9QNRHxxIiqjUuJ1WTpP4
    [model] => text-davinci-003
    [object] => text_completion
    [usage] => Array
        (
            [completion_tokens] => 8
            [prompt_tokens] => 7
            [total_tokens] => 15
        )

)

OpenAI chat

The OpenAI chat is designed for building conversational agents or chatbots that can simulate human-like conversations. It allows developers to create custom conversational agents that can answer users' questions, provide recommendations, or carry out tasks based on user inputs.

The chat API supports three primary roles: user, assistant, and system. The user represents the person who interacts with the chatbot, providing input and receiving output. The assistant is the conversational agent, providing responses to the user's inputs. The system role represents the OpenAI API, handling communication between the user and the assistant.

Method

public chat(array request, ?int response): array|string

Parameters

request

  • array with parameters:
    • model: string (required)
    • messages: array (required)
      • role: string (required)
      • content: string (required)
      • name: string
    • temperature: float
    • top_p: float
    • n: int
    • stream: bool
    • stop: string|array
    • max_tokens: int
    • presence_penalty: float
    • frequency_penalty: float
    • logit_bias: string
    • user: string

response

  • OpenAI::PHP_OPENAI_RESPONSE_ARRAY (default)
  • OpenAI::PHP_OPENAI_RESPONSE_JSON

Return values

Depending on the response parameter, the returned value is an array or text in JSON format.

Example

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Create chat completion */
    $chat = $OpenAI->chat(request: [
        "model"    => "gpt-3.5-turbo",
        "messages" => [
            [
                "role" => "system", 
                "content" => "You know everything about Silesia."
            ],
            [
                "role" => "user", 
                "content" => "What is the largest city in Silesia?"
            ],
            [
                "role" => "assistant", 
                "content" => "The largest city in Silesia is Katowice."
            ],
            [
                "role" => "user", 
                "content" => "How many people live there?"
            ]
        ]
    ], response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY);

    print_r($chat);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [choices] => Array
        (
            [finish_reason] => stop
            [index] => 0
            [message] => Array
                (
                    [content] => According to the latest estimates from 2021,the population of Katowice is approximately 287,119 people. However, the larger urban area of the city, which includes neighboring cities and municipalities, has a population of over 2.7 million people, making it the largest urban center in the region.
                    [role] => assistant
                )

        )

    [created] => 1684160647
    [id] => chatcmpl-7GTPLSzYEaRjTHDPa5SkTsQBxMMv0
    [model] => gpt-3.5-turbo-0301
    [object] => chat.completion
    [usage] => Array
        (
            [completion_tokens] => 63
            [prompt_tokens] => 59
            [total_tokens] => 122
        )

)

OpenAI edits

The OpenAI edits can be used for generating high-quality text corrections and suggestions, especially for proofreading and improving the quality of written content. The API provides state-of-the-art language models that can analyze and generate suggestions for improving text.

For example, the edits API can be used to improve the accuracy, readability, and tone of written content, such as emails, articles, or reports. It can also be used to provide feedback and suggestions for improving the writing skills of language learners or non-native speakers.

Method

public edit(array request, ?int response): array|string

Parameters

request

  • array with parameters:
    • model: string (required)
    • input: string
    • instruction: string (required)
    • n: int
    • temperature: float
    • top_p: float

response

  • OpenAI::PHP_OPENAI_RESPONSE_ARRAY (default)
  • OpenAI::PHP_OPENAI_RESPONSE_JSON

Return values

Depending on the response parameter, the returned value is an array or text in JSON format.

Example

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Create edit */
    $edit = $OpenAI->edit(request: [
        "model"       => "text-davinci-edit-001",
        "input"       => "What's the temperture outside?",
        "instruction" => "Fix the spelling mistakes"
    ], response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY);

    print_r($edit);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [choices] => Array
        (
            [index] => 0
            [text] => What's the temperature outside?\n
        )

    [created] => 1684161202
    [object] => edit
    [usage] => Array
        (
            [completion_tokens] => 25
            [prompt_tokens] => 24
            [total_tokens] => 49
        )

)

OpenAI images

The OpenAI images provides several features that can be used for manipulating and generating images using state-of-the-art AI models. Here are some examples of what you can do with the API's different functionalities:

  • Create image
    The create image functionality allows you to generate custom images from textual descriptions. For example, you can input a description like "a vase on the kitchen table" and the API will generate an image that matches that description.
  • Create image edit
    The create image edit functionality allows you to modify existing images by changing specific attributes, such as the color or style. For example, you can change the color of a car from red to blue or change the style of a dress from modern to vintage.
  • Create image variation
    The create image variation functionality allows you to generate variations of existing images, such as by changing the background or cropping the image. For example, you can create a square-cropped version of a portrait or generate an image of a person standing in front of a beach instead of a city skyline.

Method

public image(array request, int create, ?int response): array|string

Parameters

request

  • array with parameters (create: OpenAI::PHP_OPENAI_IMAGE_CREATE):
    • prompt: string (required)
    • n: int
    • size: string
    • response_format: string
    • user: string
  • array with parameters (create: OpenAI::PHP_OPENAI_IMAGE_EDIT):
    • image: string (required)
    • mask: string
    • prompt: string (required)
    • n: int
    • size: string
    • response_format: string
    • user: string
  • array with parameters (create: OpenAI::PHP_OPENAI_IMAGE_VARIATION):
    • image: string (required)
    • n: int
    • size: string
    • response_format: string
    • user: string

create

  • OpenAI::PHP_OPENAI_IMAGE_CREATE
  • OpenAI::PHP_OPENAI_IMAGE_EDIT
  • OpenAI::PHP_OPENAI_IMAGE_VARIATION

response

  • OpenAI::PHP_OPENAI_RESPONSE_ARRAY (default)
  • OpenAI::PHP_OPENAI_RESPONSE_JSON

Return values

Depending on the response parameter, the returned value is an array or text in JSON format.

Example 1 (Create image)

<?php
namespace OpenAI;
use Exception;

try
{
    $OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

    /* Create image */
    $image = $OpenAI->image(request: [
        "prompt"    => "A vase on the kitchen table.",
        "n"         => 2,
        "size"      => "512x512"
    ],
        create: OpenAI::PHP_OPENAI_IMAGE_CREATE,
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($image);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

A vase on the kitchen table.

Example 2 (Create image edit)

<?php
namespace OpenAI;
use Exception;

try
{
    $OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

    /* Create image edit */
    $image = $OpenAI->image(request: [
        "image"     => "vase_on_table.png",
        "mask"      => "vase_on_table_mask.png",
        "prompt"    => "A vase and a mobile phone on the kitchen table.",
        "n"         => 2,
        "size"      => "512x512"
    ], 
        create: OpenAI::PHP_OPENAI_IMAGE_EDIT, 
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($image);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

sample
edit

Example 3 (Create image variation)

<?php
namespace OpenAI;
use Exception;

try
{
    $OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

    /* Create image variation */
    $image = $OpenAI->image(request: [
        "image"     => "vase_and_phone_on_table.png",
        "n"         => 2,
        "size"      => "512x512"
    ],
        create: OpenAI::PHP_OPENAI_IMAGE_VARIATION, 
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($image);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

sample
variation

OpenAI embeddings

The OpenAI embeddings can be used for generating high-quality representations of text, called embeddings, that can be used for a wide range of natural language processing tasks. The API provides state-of-the-art language models that can analyze and represent the meaning of text in a high-dimensional vector space.

For example, the embeddings API can be used for semantic search, where the embeddings of a user's query can be compared to the embeddings of a database of documents to find the most relevant results. It can also be used for text classification, where the embeddings of a document can be used to predict its category or topic.

Method

public embedding(array request, ?int response): array|string

Parameters

request

  • array with parameters:
    • model: string (required)
    • input: string|array (required)
    • user: string

response

  • OpenAI::PHP_OPENAI_RESPONSE_ARRAY (default)
  • OpenAI::PHP_OPENAI_RESPONSE_JSON

Return values

Depending on the response parameter, the returned value is an array or text in JSON format.

Example

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Create embedding */
    $embedding = $OpenAI->embedding(request: [
        "model"     => "text-embedding-ada-002",
        "input"     => "The weather was great and the coach..."
    ], response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY);

    print_r($embedding);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [data] => Array
        (
            [embedding] => Array
                (
                    [0] => -0.00752546
                    [1] => -0.0018637821
                    .... (1536 floats total for ada-002)
                    [1534] => -0.018912753
                    [1535] => -0.0045779347
                )

            [index] => 0
            [object] => embedding
        )

    [model] => text-embedding-ada-002-v2
    [object] => list
    [usage] => Array
        (
            [prompt_tokens] => 8
            [total_tokens] => 8
        )

)

OpenAI audio

The OpenAI audio can be used for both audio transcription and translation. The API provides state-of-the-art machine learning models for both of these tasks.

For audio transcription, the API can be used to convert speech in an audio file to written text. This can be useful for a wide range of applications, such as transcribing interviews, lectures, and podcasts. With the help of the OpenAI audio API, this process can be automated and completed quickly and accurately.

For audio translation, the API can be used to translate speech in one language to another. This can be useful for communicating with people who speak different languages or for transcribing audio in one language and translating it to another. With the help of the OpenAI audio API, this process can also be automated and completed quickly and accurately.

Method

public audio(array request, int create, ?int response): array|string

Parameters

request

  • array with parameters (create: OpenAI::PHP_OPENAI_AUDIO_TRANSCRIPTION):
    • file: string (required)
    • model: string (required)
    • prompt: string
    • response_format: string
    • temperature: float
    • language: string
  • array with parameters (create: OpenAI::PHP_OPENAI_AUDIO_TRANSLATION):
    • file: string (required)
    • model: string (required)
    • prompt: string
    • response_format: string
    • temperature: float

create

  • OpenAI::PHP_OPENAI_AUDIO_TRANSCRIPTION
  • OpenAI::PHP_OPENAI_AUDIO_TRANSLATION

response

  • OpenAI::PHP_OPENAI_RESPONSE_ARRAY (default)
  • OpenAI::PHP_OPENAI_RESPONSE_JSON

Return values

Depending on the response parameter, the returned value is an array or text in JSON format.

Example 1 (Create transcription)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Create transcription */
    $transcription = $OpenAI->audio(request: [
        "file"      => "audio_en.mp3",
        "model"     => "whisper-1"
    ],
        create: OpenAI::PHP_OPENAI_AUDIO_TRANSCRIPTION, 
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($transcription);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

audio_en.mp3

Array
(
    [text] => Seven years in Folsom, in the hole for three. McNeil before that. McNeil as tough as they say.
)

Example 2 (Create translation)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Create translation */
    $translation = $OpenAI->audio(request: [
        "file"      => "audio_fr.mp3",
        "model"     => "whisper-1"
    ],
        create: OpenAI::PHP_OPENAI_AUDIO_TRANSLATION, 
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($translation);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

audio_fr.mp3

Array
(
    [text] => You're going back in? You know I've tied up guys like you who go back to the Mithar voluntarily. Did I?
)

OpenAI files

The OpenAI files provides a way for developers to store, manage, and access files within their applications.

For example, developers can use the files API to allow users to upload and share images or other types of files within a social networking application. They can also use it to store and manage configuration files for an application or to retrieve data from a cloud-based storage service and use it in their application.

Method

public file(array request, int command, ?int response): array|string

Parameters

request

  • array with parameters (command: OpenAI::PHP_OPENAI_FILE_UPLOAD):
    • file: string (required)
    • purpose: string (required)
  • array with parameters (commands: OpenAI::PHP_OPENAI_FILE_RETRIEVE,
    OpenAI::PHP_OPENAI_FILE_CONTENT, OpenAI::PHP_OPENAI_FILE_DELETE):
    • file_id: string (required)
  • command: OpenAI::PHP_OPENAI_FILE_LIST - no parameters, empty array []

command

  • OpenAI::PHP_OPENAI_FILE_UPLOAD
  • OpenAI::PHP_OPENAI_FILE_LIST
  • OpenAI::PHP_OPENAI_FILE_RETRIEVE
  • OpenAI::PHP_OPENAI_FILE_CONTENT
  • OpenAI::PHP_OPENAI_FILE_DELETE

response

  • OpenAI::PHP_OPENAI_RESPONSE_ARRAY (default)
  • OpenAI::PHP_OPENAI_RESPONSE_JSON

Return values

Depending on the response parameter, the returned value is an array or text in JSON format.

Example 1 (Upload file)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Upload file */
    $file_upload = $OpenAI->file(request: [
        "file"    => "fine-tune-01.jsonl",
        "purpose" => "fine-tune"
    ],
        command: OpenAI::PHP_OPENAI_FILE_UPLOAD,
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($file_upload);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [bytes] => 101
    [created_at] => 1684165336
    [filename] => fine-tune-01.jsonl
    [id] => FILE_ID
    [object] => file
    [purpose] => fine-tune
    [status] => uploaded
    [status_details] => null
)

Example 2 (List files)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* List files */
    $files = $OpenAI->file(request: [],
        command: OpenAI::PHP_OPENAI_FILE_LIST,
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($files);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [data] => Array
        (
            [bytes] => 101
            [created_at] => 1684165336
            [filename] => fine-tune-01.jsonl
            [id] => FILE_ID
            [object] => file
            [purpose] => fine-tune
            [status] => processed
            [status_details] => null
        )

    [object] => "list"
)

Example 3 (Retrieve file)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Retrieve file */
    $file_info = $OpenAI->file(request: [
        "file_id" => "FILE_ID"
    ],
        command: OpenAI::PHP_OPENAI_FILE_RETRIEVE,
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($file_info);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [bytes] => 101
    [created_at] => 1684165336
    [filename] => fine-tune-01.jsonl
    [id] => FILE_ID
    [object] => file
    [purpose] => fine-tune
    [status] => processed
    [status_details] => null
)

Example 4 (Retrieve file content)

Retrieve file content is not available for free accounts.

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Retrieve file content */
    $file_content = $OpenAI->file(request: [
        "file_id" => "FILE_ID"
    ],
        command: OpenAI::PHP_OPENAI_FILE_CONTENT,
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($file_content);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Example 5 (Delete file)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Delete file */
    $file_delete = $OpenAI->file(request: [
        "file_id" => "FILE_ID"
    ],
        command: OpenAI::PHP_OPENAI_FILE_DELETE,
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($file_delete);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [deleted] => true
    [id] => FILE_ID
    [object] => file
)

OpenAI fine-tunes

The OpenAI fine-tunes provides a way for developers to fine-tune pre-existing language models to adapt them to specific tasks.

For example, developers can use the fine-tunes API to fine-tune GPT-3 for a specific use case, such as generating text for a customer service chatbot. They can also use it to fine-tune a language model for a specific language, such as Polish or Latvian.

Method

public fineTune(array request, int command, ?int response): array|string

Parameters

request

  • array with parameters (command: OpenAI::PHP_OPENAI_FINETUNE_CREATE):
    • training_file: string (required)
    • validation_file: string
    • model: string
    • n_epochs: int
    • batch_size: int
    • learning_rate_multiplier: float
    • prompt_loss_weight: float
    • compute_classification_metrics: bool
    • classification_n_classes: int
    • classification_positive_class: string
    • classification_betas: array
    • suffix: string
  • array with parameters (commands: OpenAI::PHP_OPENAI_FINETUNE_RETRIEVE,
    OpenAI::PHP_OPENAI_FINETUNE_CANCEL):
    • fine_tune_id: string (required)
  • array with parameters (command: OpenAI::PHP_OPENAI_FINETUNE_EVENTS):
    • fine_tune_id: string (required)
    • stream: bool
  • command: OpenAI::PHP_OPENAI_FINETUNE_LIST - no parameters, empty array []

command

  • OpenAI::PHP_OPENAI_FINETUNE_CREATE
  • OpenAI::PHP_OPENAI_FINETUNE_LIST
  • OpenAI::PHP_OPENAI_FINETUNE_RETRIEVE
  • OpenAI::PHP_OPENAI_FINETUNE_CANCEL
  • OpenAI::PHP_OPENAI_FINETUNE_EVENTS
  • OpenAI::PHP_OPENAI_FINETUNE_DELETE

response

  • OpenAI::PHP_OPENAI_RESPONSE_ARRAY (default)
  • OpenAI::PHP_OPENAI_RESPONSE_JSON

Return values

Depending on the response parameter, the returned value is an array or text in JSON format.

Example 1 (Create fine-tune)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Create fine-tune */
    $finetune_create = $OpenAI->fineTune(request: [
        "training_file" => "FILE_ID"
    ],
        command: OpenAI::PHP_OPENAI_FINETUNE_CREATE, 
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($finetune_create);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [created_at] => 1684167678
    [events] => Array
        (
            [created_at] => 1684167678
            [level] => info
            [message] => Created fine-tune: FINE_TUNE_ID
            [object] => fine-tune-event
        )

    [fine_tuned_model] => null
    [hyperparams] => Array
        (
            [batch_size] => null
            [learning_rate_multiplier] => null
            [n_epochs] => 4
            [prompt_loss_weight] => 0.01
        )

    [id] => FINE_TUNE_ID
    [model] => curie
    [object] => fine-tune
    [organization_id] => ORG_ID
    [result_files] => 
    [status] => pending
    [training_files] => Array
        (
            [bytes] => 101
            [created_at] => 1684166713
            [filename] => fine-tune-01.jsonl
            [id] => FILE_ID
            [object] => file
            [purpose] => fine-tune
            [status] => processed
            [status_details] => null
        )

    [updated_at] => 1684167678
    [validation_files] => 
)

Example 2 (List fine-tunes)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* List fine-tunes */
    $finetune_list = $OpenAI->fineTune(request: [],
        command: OpenAI::PHP_OPENAI_FINETUNE_LIST, 
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($finetune_list);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [data] => Array
        (
            [created_at] => 1684167678
            [fine_tuned_model] => curie:ft-personal-2023-05-15-16-05-13
            [hyperparams] => Array
                (
                    [batch_size] => 1
                    [learning_rate_multiplier] => 0.1
                    [n_epochs] => 4
                    [prompt_loss_weight] => 0.01
                )

            [id] => FINE_TUNE_ID
            [model] => curie
            [object] => fine-tune
            [organization_id] => ORG_ID
            [result_files] => Array
                (
                    [bytes] => 347
                    [created_at] => 1684166713
                    [filename] => compiled_results.csv
                    [id] => RESULT_FILE_ID
                    [object] => file
                    [purpose] => fine-tune-results
                    [status] => processed
                    [status_details] => null
                )

            [status] => succeeded
            [training_files] => Array
                (
                    [bytes] => 101
                    [created_at] => 1684166713
                    [filename] => fine-tune-01.jsonl
                    [id] => FILE_ID
                    [object] => file
                    [purpose] => fine-tune
                    [status] => processed
                    [status_details] => null
                )

            [updated_at] => 1684167679
            [validation_files] => 
        )

    [object] => list
)

Example 3 (Retrieve fine-tune)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Retrieve fine-tune */
    $finetune_info = $OpenAI->fineTune(request: [
        "fine_tune_id" => "FINE_TUNE_ID"
    ],
        command: OpenAI::PHP_OPENAI_FINETUNE_RETRIEVE, 
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($finetune_info);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [created_at] => 1684167678
    [events] => Array
        (
            [0] => Array
                (
                    [created_at] => 1684167678
                    [level] => info
                    [message] => Created fine-tune: FINE_TUNE_ID
                    [object] => fine-tune-event
                )

            [1] => Array
                (
                    [created_at] => 1684167725
                    [level] => info
                    [message] => Fine-tune costs $0.00
                    [object] => fine-tune-event
                )

            [2] => Array
                (
                    [created_at] => 1684167725
                    [level] => info
                    [message] => Fine-tune enqueued. Queue number: 1
                    [object] => fine-tune-event
                )

            [3] => Array
                (
                    [created_at] => 1684167746
                    [level] => info
                    [message] => Fine-tune is in the queue. Queue number: 0
                    [object] => fine-tune-event
                )

            [4] => Array
                (
                    [created_at] => 1684167831
                    [level] => info
                    [message] => Fine-tune started
                    [object] => fine-tune-event
                )

            [5] => Array
                (
                    [created_at] => 1684167890
                    [level] => info
                    [message] => Completed epoch 1/4
                    [object] => fine-tune-event
                )

            [6] => Array
                (
                    [created_at] => 1684167891
                    [level] => info
                    [message] => Completed epoch 2/4
                    [object] => fine-tune-event
                )

            [7] => Array
                (
                    [created_at] => 1684167891
                    [level] => info
                    [message] => Completed epoch 3/4
                    [object] => fine-tune-event
                )

            [8] => Array
                (
                    [created_at] => 1684167891
                    [level] => info
                    [message] => Completed epoch 4/4
                    [object] => fine-tune-event
                )

            [9] => Array
                (
                    [created_at] => 1684167913
                    [level] => info
                    [message] => Uploaded model: curie:ft-personal-2023-05-15-16-05-13
                    [object] => fine-tune-event
                )

            [10] => Array
                (
                    [created_at] => 1684167914
                    [level] => info
                    [message] => Uploaded result file: FILE_ID
                    [object] => fine-tune-event
                )

            [11] => Array
                (
                    [created_at] => 1684167914
                    [level] => info
                    [message] => Fine-tune succeeded
                    [object] => fine-tune-event
                )

        )

    [fine_tuned_model] => curie:ft-personal-2023-05-15-16-05-13
    [hyperparams] => Array
        (
            [batch_size] => 1
            [learning_rate_multiplier] => 0.1
            [n_epochs] => 4
            [prompt_loss_weight] => 0.01
        )

    [id] => FINE_TUNE_ID
    [model] => curie
    [object] => fine-tune
    [organization_id] => ORG_ID
    [result_files] => Array
        (
            [bytes] => 347
            [created_at] => 1684166713
            [filename] => compiled_results.csv
            [id] => RESULT_FILE_ID
            [object] => file
            [purpose] => fine-tune-results
            [status] => processed
            [status_details] => null
        )

    [status] => succeeded
    [training_files] => Array
        (
            [bytes] => 101
            [created_at] => 1684166713
            [filename] => fine-tune-01.jsonl
            [id] => FILE_ID
            [object] => file
            [purpose] => fine-tune
            [status] => processed
            [status_details] => null
        )

    [updated_at] => 1684167679
    [validation_files] => 
)

Example 4 (Cancel fine-tune)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Cancel fine-tune */
    $finetune_cancel = $OpenAI->fineTune(request: [
        "fine_tune_id" => "FINE_TUNE_ID"
    ],
        command: OpenAI::PHP_OPENAI_FINETUNE_CANCEL, 
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($finetune_cancel);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Example 5 (List fine-tune events)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* List fine-tune events */
    $finetune_events = $OpenAI->fineTune(request: [
        "fine_tune_id" => "FINE_TUNE_ID"
    ],
        command: OpenAI::PHP_OPENAI_FINETUNE_EVENTS,
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($finetune_events);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [created_at] => 1684167678
                    [level] => info
                    [message] => Created fine-tune: FINE_TUNE_ID
                    [object] => fine-tune-event
                )

            [1] => Array
                (
                    [created_at] => 1684167725
                    [level] => info
                    [message] => Fine-tune costs $0.00
                    [object] => fine-tune-event
                )

            [2] => Array
                (
                    [created_at] => 1684167725
                    [level] => info
                    [message] => Fine-tune enqueued. Queue number: 1
                    [object] => fine-tune-event
                )

            [3] => Array
                (
                    [created_at] => 1684167746
                    [level] => info
                    [message] => Fine-tune is in the queue. Queue number: 0
                    [object] => fine-tune-event
                )

            [4] => Array
                (
                    [created_at] => 1684167831
                    [level] => info
                    [message] => Fine-tune started
                    [object] => fine-tune-event
                )

            [5] => Array
                (
                    [created_at] => 1684167890
                    [level] => info
                    [message] => Completed epoch 1/4
                    [object] => fine-tune-event
                )

            [6] => Array
                (
                    [created_at] => 1684167891
                    [level] => info
                    [message] => Completed epoch 2/4
                    [object] => fine-tune-event
                )

            [7] => Array
                (
                    [created_at] => 1684167891
                    [level] => info
                    [message] => Completed epoch 3/4
                    [object] => fine-tune-event
                )

            [8] => Array
                (
                    [created_at] => 1684167891
                    [level] => info
                    [message] => Completed epoch 4/4
                    [object] => fine-tune-event
                )

            [9] => Array
                (
                    [created_at] => 1684167913
                    [level] => info
                    [message] => Uploaded model: curie:ft-personal-2023-05-15-16-05-13
                    [object] => fine-tune-event
                )

            [10] => Array
                (
                    [created_at] => 1684167914
                    [level] => info
                    [message] => Uploaded result file: FILE_ID
                    [object] => fine-tune-event
                )

            [11] => Array
                (
                    [created_at] => 1684167914
                    [level] => info
                    [message] => Fine-tune succeeded
                    [object] => fine-tune-event
                )

        )

    [object] => list
)

Example 6 (Delete fine-tune model)

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Delete fine-tune model */
    $finetune_delete = $OpenAI->fineTune(request: [
        "model" => "MODEL_ID"
    ],
        command: OpenAI::PHP_OPENAI_FINETUNE_DELETE, 
        response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY
    );

    print_r($finetune_delete);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [deleted] => true
    [id] => curie:ft-personal-2023-05-15-16-05-13
    [object] => model
)

OpenAI moderations

The OpenAI Moderations provides developers with a way to automatically detect and filter harmful or inappropriate content in text, images, and other forms of media. The API uses machine learning models to classify content into different categories, including:

  • Identity attack: content that attacks an individual or group based on their race, religion, nationality, gender, or other personal characteristics.
  • Insult: content that is intended to insult, offend, or humiliate an individual or group.
  • Profanity: content that contains vulgar or obscene language.
  • Sexually explicit: content that contains nudity, sexual acts, or sexually suggestive material.
  • Threat: content that contains threats of violence or harm.

Method

public moderation(array request, ?int response): array|string

Parameters

request

  • array with parameters:
    • input: string|array (required)
    • model: string

response

  • OpenAI::PHP_OPENAI_RESPONSE_ARRAY (default)
  • OpenAI::PHP_OPENAI_RESPONSE_JSON

Return values

Depending on the response parameter, the returned value is an array or text in JSON format.

Example

<?php
namespace OpenAI;
use Exception;

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Create moderation */
    $moderation = $OpenAI->moderation(request: [
        "input" => "I'm going to kill these sons of bitches.",
        "model" => "text-moderation-stable"
    ], response: OpenAI::PHP_OPENAI_RESPONSE_ARRAY);

    print_r($moderation);
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);

Sample result:

Array
(
    [id] => modr-7GDGAEFpEosTfJi7bYUraAULhk9wQ
    [model] => text-moderation-001
    [results] => Array
        (
            [categories] => Array
                (
                    [hate] => true
                    [hate/threatening] => true
                    [self-harm] => false
                    [sexual] => false
                    [sexual/minors] => false
                    [violence] => true
                    [violence/graphic] => false
                )

            [category_scores] => Array
                (
                    [hate] => 0.9131612777709961
                    [hate/threatening] => 0.9507471919059753
                    [self-harm] => 0.036395784467458725
                    [sexual] => 0.16836169362068176
                    [sexual/minors] => 0.08703794330358505
                    [violence] => 0.9897998571395874
                    [violence/graphic] => 0.2577230632305145
                )

            [flagged] => true
        )

)

Practical use

How to use OpenAI in practice?

Chat is a good idea, preferably with a good sense of humor. An interesting example of such a bot is described here. There you will find a guide to creating a chat in HTML, JavaScript, CSS and PHP. This source code is allowed for personal and professional use.

Chatbot GPT

The chat can be quickly adapted to support the OpenAI library for PHP. Below is the modified PHP file (request.php) supporting the bot. You can download the full code of the bot here.

Download full code

request.php

<?php
namespace OpenAI;
use Exception;

$prompt = 'Marv is a chatbot that reluctantly answers questions '. 
          'with sarcastic responses:' . $_POST['prompt'];

$OpenAI = new OpenAI(api_key: "YOUR_API_KEY");

try
{
    /* Create completion */
    $completion = $OpenAI->completion(request: 
    [
        "model"             => "text-davinci-003",
        "prompt"            => $prompt,
        "max_tokens"        => 60,
        "temperature"       => 0.5,
        "top_p"             => 0.3,
        "n"                 => 1,
        "frequency_penalty" => 0.5,
        "presence_penalty"  => 0
    ], 
        response: OpenAI::PHP_OPENAI_RESPONSE_JSON);

    echo $completion;
} 
catch(Exception $e)
{
    echo $e->getMessage();
}

unset($OpenAI);