claudeers.
// Uncategorized / Others

client

⚡️ OpenAI PHP is a supercharged community-maintained PHP API client that allows you to interact with OpenAI API.

// Uncategorized / Others[ api ][ web ][ claude ]#claude#api#client#codex#gpt-3#gpt-4#gpt-5#language#uncategorized◷ MIT$open-sourceupdated about 1 month ago
Actively maintained
100/100
last commit 10 days ago
last release 18 days ago
releases 48
open issues 13
// star history

Install with your AI

Paste into Claude Code, Cursor, or any agent — it reads the repo and wires the tool into your project.

Install and set up client (release-binary project) into my current project.
Found on https://claudeers.com/client
Repo: https://github.com/openai-php/client
Homepage/docs: —
Detected install method: release-binary → inspect the README
Category: uncategorized. Platforms: api, web.
Read the repo's README for exact setup and env vars, then install it and wire it into my project.

Claudeers Health Verdict:
active; community-verified: false. Confirm the source before running anything.
// or install directly (release-binary)

Grab the latest release asset from GitHub.

# download a build from https://github.com/openai-php/client/releases
// or clone
git clone https://github.com/openai-php/client

// compatibility

Platformsapi, web
Operating systems—
AI compatibilityclaude
LicenseMIT
Pricingopen-source
LanguagePHP

Get your FREE $2.50 API credits to access TickAtlas financial data ↗

OpenAI PHP


OpenAI PHP is a community-maintained PHP API client that allows you to interact with the Open AI API.

If you or your business relies on this package, it's important to support the developers who have contributed their time and effort to create and maintain this valuable tool:

Get Started

Requires PHP 8.2+

First, install OpenAI via the Composer package manager:

composer require openai-php/client

Ensure that the php-http/discovery composer plugin is allowed to run or install a client manually if your project does not already have a PSR-18 client integrated.

composer require guzzlehttp/guzzle

Then, interact with OpenAI's API:

$yourApiKey = getenv('YOUR_API_KEY');
$client = OpenAI::client($yourApiKey);

$response = $client->responses()->create([
    'model' => 'gpt-4o',
    'input' => 'Hello!',
]);

echo $response->outputText; // Hello! How can I assist you today?

If necessary, it is possible to configure and create a separate client.

$yourApiKey = getenv('YOUR_API_KEY');

$client = OpenAI::factory()
    ->withApiKey($yourApiKey)
    ->withOrganization('your-organization') // default: null
    ->withProject('Your Project') // default: null
    ->withBaseUri('openai.example.com/v1') // default: api.openai.com/v1
    ->withHttpClient($httpClient = new \GuzzleHttp\Client([])) // default: HTTP client found using PSR-18 HTTP Client Discovery
    ->withHttpHeader('X-My-Header', 'foo')
    ->withQueryParam('my-param', 'bar')
    ->withStreamHandler(fn (RequestInterface $request): ResponseInterface => $httpClient->send($request, [
        'stream' => true // Allows to provide a custom stream handler for the http client.
    ]))
    ->make();

Usage

Models Resource

list

Lists the currently available models, and provides basic information about each one such as the owner and availability.

$response = $client->models()->list();

$response->object; // 'list'

foreach ($response->data as $result) {
    $result->id; // 'gpt-3.5-turbo-instruct'
    $result->object; // 'model'
    // ...
}

$response->toArray(); // ['object' => 'list', 'data' => [...]]

retrieve

Retrieves a model instance, providing basic information about the model such as the owner and permissioning.

$response = $client->models()->retrieve('gpt-3.5-turbo-instruct');

$response->id; // 'gpt-3.5-turbo-instruct'
$response->object; // 'model'
$response->created; // 1642018370
$response->ownedBy; // 'openai'

$response->toArray(); // ['id' => 'gpt-3.5-turbo-instruct', ...]

delete

Delete a fine-tuned model.

$response = $client->models()->delete('curie:ft-acmeco-2021-03-03-21-44-20');

$response->id; // 'curie:ft-acmeco-2021-03-03-21-44-20'
$response->object; // 'model'
$response->deleted; // true

$response->toArray(); // ['id' => 'curie:ft-acmeco-2021-03-03-21-44-20', ...]

Responses Resource

create

Creates a model response. Provide text or image inputs to generate text or JSON outputs. Have the model call your own custom code or use built-in tools like web search or file search to use your own data as input for the model's response.

$response = $client->responses()->create([
    'model' => 'gpt-4o-mini',
    'tools' => [
        [
            'type' => 'web_search_preview'
        ]
    ],
    'input' => "what was a positive news story from today?",
    'temperature' => 0.7,
    'max_output_tokens' => 150,
    'tool_choice' => 'auto',
    'parallel_tool_calls' => true,
    'store' => true,
    'metadata' => [
        'user_id' => '123',
        'session_id' => 'abc456'
    ]
]);

$response->id; // 'resp_67ccd2bed1ec8190b14f964abc054267'
$response->object; // 'response'
$response->createdAt; // 1741476542
$response->status; // 'completed'
$response->model; // 'gpt-4o-mini'
$response->outputText; // 'The combined response text of any `output_text` content.'

foreach ($response->output as $output) {
    $output->type; // 'message'
    $output->id; // 'msg_67ccd2bf17f0819081ff3bb2cf6508e6'
    $output->status; // 'completed'
    $output->role; // 'assistant'
    
    foreach ($output->content as $content) {
        $content->type; // 'output_text'
        $content->text; // The response text
        $content->annotations; // Any annotations in the response
    }
}

$response->usage->inputTokens; // 36
$response->usage->outputTokens; // 87
$response->usage->totalTokens; // 123

$response->toArray(); // ['id' => 'resp_67ccd2bed1ec8190b14f964abc054267', ...]

Create a model response with a function tool.

$response = $client->responses()->create([
    'model' => 'gpt-4o-mini',
    'tools' => [
        [
            'type' => 'function',
            'name' => 'get_temperature',
            'description' => 'Get the current temperature in a given location',
            'parameters' => [
                'type' => 'object',
                'properties' => [
                    'location' => [
                        'type' => 'string',
                        'description' => 'The city and state, e.g. San Francisco, CA',
                    ],
                    'unit' => [
                        'type' => 'string',
                        'enum' => ['celsius', 'fahrenheit'],
                    ],
                ],
                'required' => ['location'],
            ],
        ]
    ],
    'input' => "What is the temperature in Rio Grande do Norte, Brazil?",
]);

foreach ($response->output as $item) {
    if ($item->type === 'function_call') {
        $name = $item->name ?? null;
        $args = json_decode($item->arguments ?? '{}', true) ?: [];

        if ($name === 'get_temperature') {
            // ✅ Call your custom function here with the extracted arguments
            // Example:
            // $temperature = get_temperature($args['location'], $args['unit'] ?? 'celsius');
            // Then, send the result back to the model if needed.
        }
    }
}

Create a response with hosted shell and an uploaded skill. See Shell and Skills for the execution environments and attachment formats.

$response = $client->responses()->create([
    'model' => 'gpt-5.4',
    'tools' => [
        [
            'type' => 'shell',
            'environment' => [
                'type' => 'container_auto',
                'skills' => [
                    ['type' => 'skill_reference', 'skill_id' => 'skill_abc123'],
                ],
            ],
        ],
    ],
    'input' => 'Use the uploaded skill to count these words: one two three.',
]);

foreach ($response->output as $item) {
    if ($item->type === 'shell_call') {
        $item->action->commands; // Shell commands requested by the model
        $item->action->timeoutMs; // Optional execution timeout
        $item->environment; // Local environment or container reference
    }

    if ($item->type === 'shell_call_output') {
        foreach ($item->output as $output) {
            $output->stdout;
            $output->stderr;
            $output->outcome->type; // 'exit' or 'timeout'

            if ($output->outcome->type === 'exit') {
                $output->outcome->exitCode;
            }
        }
    }
}

$response->toArray();

Hosted shell runs on OpenAI. An automatically provisioned container can appear as container_reference in the response. Attachments may also use inline with a base64 ZIP source. With environment.type = local, your application executes the commands and supplies shell_call_output items; the client only parses and serializes these data structures.

create streamed

When you create a Response with stream set to true, the server will emit server-sent events to the client as the Response is generated. All events and their payloads can be found in OpenAI docs.

$stream = $client->responses()->createStreamed([
    'model' => 'gpt-4o-mini',
    'tools' => [
        [
            'type' => 'web_search_preview'
        ]
    ],
    'input' => "what was a positive news story from today?",
]);

foreach ($stream as $response) {
    $response->event; // 'response.created'
}

retrieve

Retrieves a model response with the given ID.

$response = $client->responses()->retrieve('resp_67ccd2bed1ec8190b14f964abc054267');

$response->id; // 'resp_67ccd2bed1ec8190b14f964abc054267'
$response->object; // 'response'
$response->createdAt; // 1741476542
$response->status; // 'completed'
$response->error; // null
$response->incompleteDetails; // null
$response->instructions; // null
$response->maxOutputTokens; // null
$response->model; // 'gpt-4o-mini-2024-07-18"'
$response->parallelToolCalls; // true
$response->previousResponseId; // null
$response->store; // true
$response->temperature; // 1.0
$response->toolChoice; // 'auto'
$response->topP; // 1.0
$response->truncation; // 'disabled'

$response->toArray(); // ['id' => 'resp_67ccd2bed1ec8190b14f964abc054267', ...]

retrieve streamed

When you retrieve a Response with stream set to true, the server will emit server-sent events to the client as the Response is generated. All events and their payloads can be found in OpenAI docs.

$stream = $client->responses()->retrieveStreamed('resp_67ccd2bed1ec8190b14f964abc054267', [
    'starting_after' => '2',
]);

foreach ($stream as $response) {
    $response->event; // 'response.created'
}

cancel

Cancel a model response (background request) with the given ID.

$response = $client->responses()->cancel('resp_67ccd2bed1ec8190b14f964abc054267');

$response->id; // 'resp_67ccd2bed1ec8190b14f964abc054267'
$response->status; // 'canceled'

$response->toArray(); // ['id' => 'resp_67ccd2bed1ec8190b14f964abc054267', 'status' => 'canceled', ...]

delete

Deletes a model response with the given ID.

$response = $client->responses()->delete('resp_67ccd2bed1ec8190b14f964abc054267');

$response->id; // 'resp_67ccd2bed1ec8190b14f964abc054267'
$response->object; // 'response'
$response->deleted; // true

$response->toArray(); // ['id' => 'resp_67ccd2bed1ec8190b14f964abc054267', 'deleted' => true, ...]

list

Lists input items for a response with the given ID. All events and their payloads can be found in OpenAI docs.

$response = $client->responses()->list('resp_67ccd2bed1ec8190b14f964abc054267', [
    'limit' => 10,
    'order' => 'desc'
]);

$response->object; // 'list'

foreach ($response->data as $item) {
    $item->type; // 'message'
    $item->id; // 'msg_680bf4e8c1948192b64abf0bad54b30806e0834f49400fc3'
    $item->status; // 'completed'
    $item->role; // 'user'
}

$response->firstId; // 'msg_680bf4e8c1948192b64abf0bad54b30806e0834f49400fc3'
$response->lastId; // 'msg_680bf4e8c1948192b64abf0bad54b30806e0834f49400fc3'
$response->hasMore; // false

$response->toArray(); // ['object' => 'list', 'data' => [...], ...]

Conversations Resource

create

Create a conversation.

$response = $client->conversations()->create([
    'metadata' => ['topic' => 'demo'],
    'items' => [
        [
            'type' => 'message',
            'role' => 'user',
            'content' => 'Hello!'
        ],
    ],
]);

$response->id; // 'conv_123'
$response->object; // 'conversation'
$response->createdAt; // 1741900000
$response->metadata; // ['topic' => 'demo']

$response->toArray(); // ['id' => 'conv_123', 'object' => 'conversation', ...]

retrieve

Retrieve a conversation by ID.

$response = $client->conversations()->retrieve('conv_123');

$response->id; // 'conv_123'
$response->object; // 'conversation'
$response->createdAt; // 1741900000

$response->toArray(); // ['id' => 'conv_123', 'object' => 'conversation', ...]

update

Update a conversation by ID.

$response = $client->conversations()->update('conv_123', [
    'metadata' => ['foo' => 'bar'],
]);

$response->id; // 'conv_123'
$response->metadata; // ['foo' => 'bar']

delete

Delete a conversation by ID.

$response = $client->conversations()->delete('conv_123');

$response->id; // 'conv_123'
$response->object; // 'conversation.deleted'
$response->deleted; // true

$response->toArray(); // ['id' => 'conv_123', 'object' => 'conversation.deleted', 'deleted' => true]

Conversations Items Resource

create

Create items for a conversation.

$response = $client->conversations()->items()->create('conv_123', [
    'items' => [
        [
            'role' => 'system',
            'content' => 'Refer to me as PHPBot.',
        ],
    ],
]);

foreach ($response->data as $listItem) {
    $listItem->item; // The created item (e.g., message)
}

$response->firstId; // 'msg_abc'
$response->lastId; // 'msg_abc'
$response->hasMore; // false

$response->toArray(); // ['object' => 'list', 'data' => [...], ...]

list

List items for a conversation.

$response = $client->conversations()->items()->list('conv_123', [
    'limit' => 10,
]);

$response->object; // 'list'

retrieve

Retrieve a specific item from a conversation.

$response = $client->conversations()->items()->retrieve('conv_123', 'msg_abc', [
    'include' => ['step_details'],
]);

$response->id; // 'msg_abc'
$response->type; // 'message'
$response->status; // 'completed'

delete

Delete a specific item from a conversation. Returns the updated conversation.

$response = $client->conversations()->items()->delete('conv_123', 'msg_abc');

$response->id; // 'conv_123'
$response->object; // 'conversation'

Containers Resource

create

Creates a container for use with the Code Interpreter tool.

$response = $client->containers()->create([
    'name' => 'My Container',
    'expires_after' => [
        'anchor' => 'last_active_at',
        'minutes' => 60,
    ],
]);

$response->id; // 'container_abc123'
$response->object; // 'container'
$response->createdAt; // 1690000000
$response->status; // 'active'
$response->expiresAfter->anchor; // 'last_active_at'
$response->expiresAfter->minutes; // 60
$response->lastActiveAt; // 1690001000
$response->name; // 'My Container'

$response->toArray(); // ['id' => 'container_abc123', 'object' => 'container', ...]

list

Returns a list of containers.

$response = $client->containers()->list([
    'limit' => 10,
    'order' => 'desc',
]);

$response->object; // 'list'

foreach ($response->data as $container) {
    $container->id; // 'container_abc123'
    $container->object; // 'container'
    $container->createdAt; // 1690000000
    $container->status; // 'active'
    $container->expiresAfter->anchor; // 'last_active_at'
    $container->expiresAfter->minutes; // 60
    $container->lastActiveAt; // 1690001000
    $container->name; // 'Test Container'
}

$response->firstId; // 'container_abc123'
$response->lastId; // 'container_def456'
$response->hasMore; // false

$response->toArray(); // ['object' => 'list', 'data' => [...], ...]

retrieve

Retrieves a container with the given ID.

$response = $client->containers()->retrieve('container_abc123');

$response->id; // 'container_abc123'
$response->object; // 'container'
$response->createdAt; // 1690000000
$response->status; // 'active'
$response->expiresAfter->anchor; // 'last_active_at'
$response->expiresAfter->minutes; // 60
$response->lastActiveAt; // 1690001000
$response->name; // 'Test Container'

$response->toArray(); // ['id' => 'container_abc123', 'object' => 'container', ...]

delete

Delete a container with the given ID.

$response = $client->containers()->delete('container_abc123');

$response->id; // 'container_abc123'
$response->object; // 'container'
$response->deleted; // true

$response->toArray(); // ['id' => 'container_abc123', 'object' => 'container', 'deleted' => true]

Containers Files Resource

create

Create or upload a file into a container.

$response = $client->containers()->files()->create('container_abc123', [
    'file' => fopen('path/to/local-file.txt', 'r'),
]);
$response = $client->containers()->files()->create('container_abc123', [
    'file_id' => 'file_XjGxS3KTG0uNmNOK362iJua3',
]);

$response->id; // 'cfile_682e0e8a43c88191a7978f477a09bdf5'
$response->object; // 'container.file'
$response->createdAt; // 1747848842
$response->bytes; // 880
$response->containerId; // 'container_abc123'
$response->path; // '/mnt/data/local-file.txt'
$response->source; // 'user'

$response->toArray(); // ['id' => 'cfile_...', 'object' => 'container.file', ...]

[!NOTE] You must provide either file or file_id, but not both.

list

Returns a list of files in the container.

$response = $client->containers()->files()->list('container_abc123', [
    'limit' => 10,
    'order' => 'desc',
]);

$response->object; // 'list'

foreach ($response->data as $file) {
    $file->id; // 'cfile_682e0e8a43c88191a7978f477a09bdf5'
    $file->object; // 'container.file'
    $file->createdAt; // 1747848842
    $file->bytes; // 880
    $file->containerId; // 'container_abc123'
    $file->path; // '/mnt/data/...' 
    $file->source; // 'user'
}

$response->firstId; // 'cfile_...'
$response->lastId; // 'cfile_...'
$response->hasMore; // false

$response->toArray(); // ['object' => 'list', 'data' => [...], ...]

retrieve

Retrieve information about a container file.

$response = $client->containers()->files()->retrieve('container_abc123', 'cfile_682e0e8a43c88191a7978f477a09bdf5');

$response->id; // 'cfile_682e0e8a43c88191a7978f477a09bdf5'
$response->object; // 'container.file'
$response->createdAt; // 1747848842
$response->bytes; // 880
$response->containerId; // 'container_abc123'
$response->path; // '/mnt/data/...'
$response->source; // 'user'

$response->toArray(); // ['id' => 'cfile_...', 'object' => 'container.file', ...]

retrieve content

Returns the raw content of the specified container file.

$content = $client->containers()->files()->content('container_abc123', 'cfile_682e0e8a43c88191a7978f477a09bdf5');
// $content => string

delete

Delete a container file.

$response = $client->containers()->files()->delete('container_abc123', 'cfile_682e0e8a43c88191a7978f477a09bdf5');

$response->id; // 'cfile_682e0e8a43c88191a7978f477a09bdf5'
$response->object; // 'container.file.deleted'
$response->deleted; // true

$response->toArray(); // ['id' => 'cfile_...', 'object' => 'container.file.deleted', 'deleted' => true]

Skills Resource

Skills give an agent reusable instructions and supporting files. Upload a skill either as a zip bundle or as a directory of files, then reference it from the Responses API shell tool via skill_reference.

create

Creates a skill from a zip bundle, or from several files that share a single top-level folder.

// Zip upload
$response = $client->skills()->create([
    'files' => fopen('basic_math.zip', 'r'),
]);

// Directory upload
$response = $client->skills()->create([
    'files' => [
        fopen('basic_math/SKILL.md', 'r'),
        fopen('basic_math/calculate.py', 'r'),
    ],
]);

$response->id; // 'skill_abc123'
$response->name; // 'basic-math'
$response->defaultVersion; // '1'
$response->latestVersion; // '1'

$response->toArray(); // ['id' => 'skill_abc123', ...]

list

Lists the skills in the current project.

$response = $client->skills()->list([
    'limit' => 10,
]);

$response->object; // 'list'
$response->hasMore; // false

foreach ($response->data as $result) {
    $result->id; // 'skill_abc123'
    $result->name; // 'basic-math'
}

$response->toArray(); // ['object' => 'list', 'data' => [...], ...]

retrieve

Retrieves a skill by its ID.

$response = $client->skills()->retrieve('skill_abc123');

$response->id; // 'skill_abc123'
$response->description; // 'Add or multiply numbers.'

$response->toArray(); // ['id' => 'skill_abc123', ...]

update

Updates the default version pointer for a skill.

$response = $client->skills()->update('skill_abc123', [
    'default_version' => '2',
]);

$response->defaultVersion; // '2'

content

Downloads the zip bundle for a skill's default version.

$zip = $client->skills()->content('skill_abc123');

file_put_contents('basic_math.zip', $zip);

delete

Deletes a skill and all of its versions.

$response = $client->skills()->delete('skill_abc123');

$response->id; // 'skill_abc123'
$response->object; // 'skill.deleted'
$response->deleted; // true

$response->toArray(); // ['id' => 'skill_abc123', ...]

Skills Versions Resource

create

Creates a new immutable version of a skill. Pass default to make it the default version.

$response = $client->skills()->versions()->create('skill_abc123', [
    'files' => fopen('basic_math_v2.zip', 'r'),
    'default' => 'true',
]);

$response->id; // 'skillver_abc123'
$response->version; // '2'

$response->toArray(); // ['id' => 'skillver_abc123', ...]

list

Lists the versions of a skill.

$response = $client->skills()->versions()->list('skill_abc123', [
    'order' => 'desc',
]);

foreach ($response->data as $result) {
    $result->version; // '2'
}

retrieve

Retrieves a specific version of a skill.

$response = $client->skills()->versions()->retrieve('skill_abc123', '2');

$response->skillId; // 'skill_abc123'
$response->version; // '2'

content

Downloads the zip bundle for a specific skill version.

$zip = $client->skills()->versions()->content('skill_abc123', '2');

delete

Deletes a skill version. The default version cannot be deleted; set another default first.

$response = $client->skills()->versions()->delete('skill_abc123', '1');

$response->object; // 'skill.version.deleted'
$response->deleted; // true

Chat Resource

create

Creates a completion for the chat message.

$response = $client->chat()->create([
    'model' => 'gpt-3.5-turbo',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello!'],
    ],
]);

$response->id; // 'chatcmpl-6pMyfj1HF4QXnfvjtfzvufZSQq6Eq'
$response->object; // 'chat.completion'
$response->created; // 1677701073
$response->model; // 'gpt-3.5-turbo-0301'

foreach ($response->choices as $choice) {
    $choice->index; // 0
    $choice->message->role; // 'assistant'
    $choice->message->content; // '\n\nHello there! How can I assist you today?'
    $choice->logprobs; // null
    $choice->finishReason; // 'stop'
}

$response->usage->promptTokens; // 9,
$response->usage->completionTokens; // 12,
$response->usage->totalTokens; // 21

$response->toArray(); // ['id' => 'chatcmpl-6pMyfj1HF4QXnfvjtfzvufZSQq6Eq', ...]

Creates a completion for the chat message with a tool call.

$response = $client->chat()->create([
    'model' => 'gpt-3.5-turbo-0613',
    'messages' => [
        ['role' => 'user', 'content' => 'What\'s the weather like in Boston?'],
    ],
    'tools' => [
        [
            'type' => 'function',
            'function' => [
                'name' => 'get_current_weather',
                'description' => 'Get the current weather in a given location',
                'parameters' => [
                    'type' => 'object',
                    'properties' => [
                        'location' => [
                            'type' => 'string',
                            'description' => 'The city and state, e.g. San Francisco, CA',
                        ],
                        'unit' => [
                            'type' => 'string',
                            'enum' => ['celsius', 'fahrenheit']
                        ],
                    ],
                    'required' => ['location'],
                ],
            ],
        ]
    ]
]);

$response->id; // 'chatcmpl-6pMyfj1HF4QXnfvjtfzvufZSQq6Eq'
$response->object; // 'chat.completion'
$response->created; // 1677701073
$response->model; // 'gpt-3.5-turbo-0613'

foreach ($response->choices as $choice) {
    $choice->index; // 0
    $choice->message->role; // 'assistant'
    $choice->message->content; // null
    $choice->message->toolCalls[0]->id; // 'call_123'
    $choice->message->toolCalls[0]->type; // 'function'
    $choice->message->toolCalls[0]->function->name; // 'get_current_weather'
    $choice->message->toolCalls[0]->function->arguments; // "{\n  \"location\": \"Boston, MA\"\n}"
    $choice->finishReason; // 'tool_calls'
}

$response->usage->promptTokens; // 82,
$response->usage->completionTokens; // 18,
$response->usage->totalTokens; // 100

Creates a completion for the chat message with a function call.

$response = $client->chat()->create([
    'model' => 'gpt-3.5-turbo-0613',
    'messages' => [
        ['role' => 'user', 'content' => 'What\'s the weather like in Boston?'],
    ],
    'functions' => [
        [
            'name' => 'get_current_weather',
            'description' => 'Get the current weather in a given location',
            'parameters' => [
                'type' => 'object',
                'properties' => [
                    'location' => [
                        'type' => 'string',
                        'description' => 'The city and state, e.g. San Francisco, CA',
                    ],
                    'unit' => [
                        'type' => 'string',
                        'enum' => ['celsius', 'fahrenheit']
                    ],
                ],
                'required' => ['location'],
            ],
        ]
    ]
]);

$response->id; // 'chatcmpl-6pMyfj1HF4QXnfvjtfzvufZSQq6Eq'
$response->object; // 'chat.completion'
$response->created; // 1677701073
$response->model; // 'gpt-3.5-turbo-0613'

foreach ($response->choices as $choice) {
    $choice->index; // 0
    $choice->message->role; // 'assistant'
    $choice->message->content; // null
    $choice->message->functionCall->name; // 'get_current_weather'
    $choice->message->functionCall->arguments; // "{\n  \"location\": \"Boston, MA\"\n}"
    $choice->finishReason; // 'function_call'
}

$response->usage->promptTokens; // 82,
$response->usage->completionTokens; // 18,
$response->usage->totalTokens; // 100

Creates a chat completion with image input via image_url.
Useful for describing and analyzing visual content.

$response = $client->chat()->create([
    'model' => 'gpt-4o',
    'messages' => [
        [
            'role' => 'user',
            'content' => [
                ['type' => 'text', 'text' => 'What is in this image?'],
                // Replace with a real, accessible image
                ['type' => 'image_url', 'image_url' => ['url' => 'https://example.com/image.jpg']], 
            ]
        ]
    ]
]);

create streamed

Creates a streamed completion for the chat message.

$stream = $client->chat()->createStreamed([
    'model' => 'gpt-4o',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello!'],
    ],
]);

foreach($stream as $response){
    $response->choices[0]->toArray();
}
// 1. iteration => ['index' => 0, 'delta' => ['role' => 'assistant'], 'finish_reason' => null]
// 2. iteration => ['index' => 0, 'delta' => ['content' => 'Hello'], 'finish_reason' => null]
// 3. iteration => ['index' => 0, 'delta' => ['content' => '!'], 'finish_reason' => null]
// ...

To get usage report when using stream you can use include_usage in stream_options .

$stream = $client->chat()->createStreamed([
    'model' => 'gpt-4',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello!'],
    ],
    'stream_options'=>[
        'include_usage' => true,
    ]
]);

foreach($stream as $response){
    if($response->usage !== null){
        $response->usage->promptTokens; // 9,
        $response->usage->completionTokens; // 12,
        $response->usage->totalTokens; // 21
    }
}

usage is always null except for the last chunk which contains the token usage statistics for the entire request.

Audio Resource

speech

Generates audio from the input text.

$client->audio()->speech([
    'model' => 'tts-1',
    'input' => 'The quick brown fox jumped over the lazy dog.',
    'voice' => 'alloy',
]); // audio file content as string

speechStreamed

Generates streamed audio from the input text.

$stream = $client->audio()->speechStreamed([
    'model' => 'tts-1',
    'input' => 'The quick brown fox jumped over the lazy dog.',
    'voice' => 'alloy',
]);

foreach($stream as $chunk){
    $chunk; // chunk of audio file content as string
}

transcribe

Transcribes audio into the input language.

$response = $client->audio()->transcribe([
    'model' => 'whisper-1',
    'file' => fopen('audio.mp3', 'r'),
    'response_format' => 'verbose_json',
    'timestamp_granularities' => ['segment', 'word']
]);

$response->task; // 'transcribe'
$response->language; // 'english'
$response->duration; // 2.95
$response->text; // 'Hello, how are you?'

foreach ($response->segments as $segment) {
    $segment->index; // 0
    $segment->seek; // 0
    $segment->start; // 0.0
    $segment->end; // 4.0
    $segment->text; // 'Hello, how are you?'
    $segment->tokens; // [50364, 2425, 11, 577, 366, 291, 30, 50564]
    $segment->temperature; // 0.0
    $segment->avgLogprob; // -0.45045216878255206
    $segment->compressionRatio; // 0.7037037037037037
    $segment->noSpeechProb; // 0.1076972484588623
    $segment->transient; // false
}

foreach ($response->words as $word) {
    $word->word; // 'Hello'
    $word->start; // 0.31
    $word->end; // 0.92
}

$response->toArray(); // ['task' => 'transcribe', ...]

transcribe streamed

Transcribes audio into the input language with streaming.

$stream = $client->audio()->transcribeStreamed([
    'model' => 'gpt-4o-transcribe',
    'file' => fopen('audio.mp3', 'r'),
]);

foreach ($stream as $event) {
    echo json_encode($event->toArray()); // {"event":"transcript.text.delta","data":{"delta":"The"}}
}

translate

Translates audio into English.

$response = $client->audio()->translate([
    'model' => 'whisper-1',
    'file' => fopen('german.mp3', 'r'),
    'response_format' => 'verbose_json',
]);

$response->task; // 'translate'
$response->language; // 'english'
$response->duration; // 2.95
$response->text; // 'Hello, how are you?'

foreach ($response->segments as $segment) {
    $segment->index; // 0
    $segment->seek; // 0
    $segment->start; // 0.0
    $segment->end; // 4.0
    $segment->text; // 'Hello, how are you?'
    $segment->tokens; // [50364, 2425, 11, 577, 366, 291, 30, 50564]
    $segment->temperature; // 0.0
    $segment->avgLogprob; // -0.45045216878255206
    $segment->compressionRatio; // 0.7037037037037037
    $segment->noSpeechProb; // 0.1076972484588623
    $segment->transient; // false
}

$response->toArray(); // ['task' => 'translate', ...]

Embeddings Resource

create

Creates an embedding vector representing the input text.

$response = $client->embeddings()->create([
    'model' => 'text-similarity-babbage-001',
    'input' => 'The food was delicious and the waiter...',
]);

$response->object; // 'list'

foreach ($response->embeddings as $embedding) {
    $embedding->object; // 'embedding'
    $embedding->model; // 'text-similarity-babbage-001'
    $embedding->embedding; // [0.018990106880664825, -0.0073809814639389515, ...]
    $embedding->index; // 0
}

$response->usage->promptTokens; // 8,
$response->usage->totalTokens; // 8

$response->toArray(); // ['data' => [...], ...]

Files Resource

list

Returns a list of files that belong to the user's organization.

$response = $client->files()->list();

$response->object; // 'list'

foreach ($response->data as $result) {
    $result->id; // 'file-XjGxS3KTG0uNmNOK362iJua3'
    $result->object; // 'file'
    // ...
}

$response->toArray(); // ['object' => 'list', 'data' => [...]]

delete

Delete a file.

$response = $client->files()->delete($file);

$response->id; // 'file-XjGxS3KTG0uNmNOK362iJua3'
$response->object; // 'file'
$response->deleted; // true

$response->toArray(); // ['id' => 'file-XjGxS3KTG0uNmNOK362iJua3', ...]

retrieve

Returns information about a specific file.

$response = $client->files()->retrieve('file-XjGxS3KTG0uNmNOK362iJua3');

$response->id; // 'file-XjGxS3KTG0uNmNOK362iJua3'
$response->object; // 'file'
$response->bytes; // 140
$response->createdAt; // 1613779657
$response->filename; // 'mydata.jsonl'
$response->purpose; // 'fine-tune'
$response->status; // 'succeeded'
$response->status_details; // null

$response->toArray(); // ['id' => 'file-XjGxS3KTG0uNmNOK362iJua3', ...]

upload

Upload a file that contains document(s) to be used across various endpoints/features.

$response = $client->files()->upload([
        'purpose' => 'fine-tune',
        'file' => fopen('my-file.jsonl', 'r'),
    ]);

$response->id; // 'file-XjGxS3KTG0uNmNOK362iJua3'
$response->object; // 'file'
$response->bytes; // 140
$response->createdAt; // 1613779657
$response->filename; // 'mydata.jsonl'
$response->purpose; // 'fine-tune'
$response->status; // 'succeeded'
$response->status_details; // null

$response->toArray(); // ['id' => 'file-XjGxS3KTG0uNmNOK362iJua3', ...]

download

Returns the contents of the specified file.

$client->files()->download($file); // '{"prompt": "<prompt text>", ...'

FineTuning Resource

create job

Creates a job that fine-tunes a specified model from a given dataset.

$response = $client->fineTuning()->createJob([
    'training_file' => 'file-abc123',
    'validation_file' => null,
    'model' => 'gpt-3.5-turbo',
    'hyperparameters' => [
        'n_epochs' => 4,
    ],
    'suffix' => null,
]);

$response->id; // 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F'
$response->object; // 'fine_tuning.job'
$response->model; // 'gpt-3.5-turbo-0613'
$response->fineTunedModel; // null
// ...

$response->toArray(); // ['id' => 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F', ...]

list jobs

List your organization's fine-tuning jobs.

$response = $client->fineTuning()->listJobs();

$response->object; // 'list'

foreach ($response->data as $result) {
    $result->id; // 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F'
    $result->object; // 'fine_tuning.job'
    // ...
}

$response->toArray(); // ['object' => 'list', 'data' => [...]]

You can pass additional parameters to the listJobs method to narrow down the results.

$response = $client->fineTuning()->listJobs([
    'limit' => 3, // Number of jobs to retrieve (Default: 20)
    'after' => 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F', // Identifier for the last job from the previous pagination request.
]);

retrieve job

Get info about a fine-tuning job.

$response = $client->fineTuning()->retrieveJob('ftjob-AF1WoRqd3aJAHsqc9NY7iL8F');

$response->id; // 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F'
$response->object; // 'fine_tuning.job'
$response->model; // 'gpt-3.5-turbo-0613'
$response->createdAt; // 1614807352
$response->finishedAt; // 1692819450
$response->fineTunedModel; // 'ft:gpt-3.5-turbo-0613:jwe-dev::7qnxQ0sQ'
$response->organizationId; // 'org-jwe45798ASN82s'
$response->resultFiles[0]; // 'file-1bl05WrhsKDDEdg8XSP617QF'
$response->status; // 'succeeded'
$response->validationFile; // null
$response->trainingFile; // 'file-abc123'
$response->trainedTokens; // 5049

$response->hyperparameters->nEpochs; // 9

$response->toArray(); // ['id' => 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F', ...]

cancel job

Immediately cancel a fine-tune job.

$response = $client->fineTuning()->cancelJob('ftjob-AF1WoRqd3aJAHsqc9NY7iL8F');

$response->id; // 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F'
$response->object; // 'fine_tuning.job'
// ...
$response->status; // 'cancelled'
// ...

$response->toArray(); // ['id' => 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F', ...]

list job events

Get status updates for a fine-tuning job.

$response = $client->fineTuning()->listJobEvents('ftjob-AF1WoRqd3aJAHsqc9NY7iL8F');

$response->object; // 'list'

foreach ($response->data as $result) {
    $result->object; // 'fine_tuning.job.event' 
    $result->createdAt; // 1614807352
    // ...
}

$response->toArray(); // ['object' => 'list', 'data' => [...]]

You can pass additional parameters to the listJobEvents method to narrow down the results.

$response = $client->fineTuning()->listJobEvents('ftjob-AF1WoRqd3aJAHsqc9NY7iL8F', [
    'limit' => 3, // Number of events to retrieve (Default: 20)
    'after' => 'ftevent-kLPSMIcsqshEUEJVOVBVcHlP', // Identifier for the last event from the previous pagination request.
]);

Decisions Resource

create

Evaluates text, images, or both against a list of questions. A question has the type predicate, choice, or score.

$response = $client->decisions()->create([
    'model' => 'gpt-6-luna',
    'input' => 'Please refund my order. This is the third time I ask.',
    'questions' => [
        [
            'type' => 'predicate',
            'name' => 'wants_refund',
            'instructions' => 'The customer asks for a refund.',
        ],
        [
            'type' => 'choice',
            'name' => 'sentiment',
            'instructions' => 'Pick the tone of the message.',
            'choices' => [
                ['value' => 'positive', 'description' => 'The tone is happy.'],
                ['value' => 'negative', 'description' => 'The tone is angry or upset.'],
            ],
        ],
        [
            'type' => 'score',
            'name' => 'urgency',
            'instructions' => 'Rate how urgent the request is.',
            'levels' => [
                ['label' => 'low', 'description' => 'No time pressure.'],
                ['label' => 'high', 'description' => 'The customer needs help now.'],
            ],
        ],
    ],
]);

foreach ($response->answers as $answer) {
    $answer->type; // 'predicate', 'choice', 'score' or 'refusal'
    $answer->name; // 'wants_refund'
}

$response->answer('wants_refund')->probability; // 0.98
$response->answer('sentiment')->choice; // 'negative'
$response->answer('urgency')->score; // 1.7

$response->toArray(); // ['answers' => [...]]

Moderations Resource

create

Classifies if text violates OpenAI's Content Policy.


$response = $client->moderations()->create([
    'model' => 'text-moderation-latest',
    'input' => 'I want to k*** them.',
]);

$response->id; // modr-5xOyuS
$response->model; // text-moderation-003

foreach ($response->results as $result) {
    $result->flagged; // true

    foreach ($result->categories as $category) {
        $category->category->value; // 'violence'
        $category->violated; // true
        $category->score; // 0.97431367635727
    }
}

$response->toArray(); // ['id' => 'modr-5xOyuS', ...]

Images Resource

create

Creates an image given a prompt.

$response = $client->images()->create([
    'model' => 'dall-e-3',
    'prompt' => 'A cute baby sea otter',
    'n' => 1,
    'size' => '1024x1024',
    'response_format' => 'url',
]);

$response->created; // 1589478378

foreach ($response->data as $data) {
    $data->url; // 'https://oaidalleapiprodscus.blob.core.windows.net/private/...'
    $data->b64_json; // null
}

$response->toArray(); // ['created' => 1589478378, data => ['url' => 'https://oaidalleapiprodscus...', ...]]

create streamed

When you create an image with stream set to true, the server will emit server-sent events to the client as the image is generated. All events and their payloads can be found in OpenAI docs.

$stream = $client->images()->createStreamed([
    'model' => 'gpt-image-1',
    'prompt' => 'A cute baby sea otter',
    'n' => 1,
    'size' => '1024x1024',
    'response_format' => 'url',
]);

foreach ($stream as $image) {
    $image->type; // 'image_generation.partial_image'
}

edit

Creates an edited or extended image given an original image and a prompt.

$response = $client->images()->edit([
    'image' => fopen('image_edit_original.png', 'r'),
    'mask' => fopen('image_edit_mask.png', 'r'),
    'prompt' => 'A sunlit indoor lounge area with a pool containing a flamingo',
    'n' => 1,
    'size' => '256x256',
    'response_format' => 'url',
]);

$response->created; // 1589478378

foreach ($response->data as $data) {
    $data->url; // 'https://oaidalleapiprodscus.blob.core.windows.net/private/...'
    $data->b64_json; // null
}

$response->toArray(); // ['created' => 1589478378, data => ['url' => 'https://oaidalleapiprodscus...', ...]]

edit streamed

When you edit an image with stream set to true, the server will emit server-sent events to the client as the image is generated. All events and their payloads can be found in OpenAI docs.

$stream = $client->images()->editStreamed([
    'model' => 'gpt-image-1',
    'prompt' => 'A cute baby sea otter',
    'n' => 1,
    'size' => '1024x1024',
    'response_format' => 'url',
]);

foreach ($stream as $image) {
    $image->type; // 'image_generation.partial_image'
}

variation

Creates a variation of a given image.

$response = $client->images()->variation([
    'image' => fopen('image_edit_original.png', 'r'),
    'n' => 1,
    'size' => '256x256',
    'response_format' => 'url',
]);

$response->created; // 1589478378

foreach ($response->data as $data) {
    $data->url; // 'https://oaidalleapiprodscus.blob.core.windows.net/private/...'
    $data->b64_json; // null
}

$response->toArray(); // ['created' => 1589478378, data => ['url' => 'https://oaidalleapiprodscus...', ...]]

Batches Resource

create

Creates a batch.


$fileResponse = $client->files()->upload(
     parameters: [
          'purpose' => 'batch',
          'file' => fopen('commands.jsonl', 'r'),
    ]
);

$fileId = $fileResponse->id;

$response = $client->batches()->create(
    parameters: [
        'input_file_id' => $fileId,
        'endpoint' => '/v1/chat/completions',
        'completion_window' => '24h'
    ]
 );

$response->id; // 'batch_abc123'
$response->object; // 'batch'
$response->endpoint; // /v1/chat/completions
$response->errors; // null
$response->completionWindow; // '24h'
$response->status; // 'validating'
$response->outputFileId; // null
$response->errorFileId; // null
$response->createdAt; // 1714508499
$response->inProgressAt; // null
$response->expiresAt; // 1714536634
$response->completedAt; // null
$response->failedAt; // null
$response->expiredAt; // null
$response->requestCounts; // null
$response->metadata; // ['name' => 'My batch name']

$response->toArray(); // ['id' => 'batch_abc123', ...]

retrieve

Retrieves a batch.

$response = $client->batches()->retrieve(id: 'batch_abc123');

$response->id; // 'batch_abc123'
$response->object; // 'batch'
$response->endpoint; // /v1/chat/completions
$response->errors; // null
$response->completionWindow; // '24h'
$response->status; // 'validating'
$response->outputFileId; // null
$response->errorFileId; // null
$response->createdAt; // 1714508499
$response->inProgressAt; // null
$response->expiresAt; // 1714536634
$response->completedAt; // null
$response->failedAt; // null
$response->expiredAt; // null
$response->requestCounts->total; // 100
$response->requestCounts->completed; // 95
$response->requestCounts->failed; // 5
$response->metadata; // ['name' => 'My batch name']

$response->toArray(); // ['id' => 'batch_abc123', ...]

cancel

Cancels a batch.

$response = $client->batches()->cancel(id: 'batch_abc123');

$response->id; // 'batch_abc123'
$response->object; // 'batch'
$response->endpoint; // /v1/chat/completions
$response->errors; // null
$response->completionWindow; // '24h'
$response->status; // 'cancelling'
$response->outputFileId; // null
$response->errorFileId; // null
$response->createdAt; // 1711471533
$response->inProgressAt; // 1711471538
$response->expiresAt; // 1711557933
$response->cancellingAt; // 1711475133
$response->cancelledAt; // null
$response->requestCounts->total; // 100
$response->requestCounts->completed; // 23
$response->requestCounts->failed; // 1
$response->metadata; // ['name' => 'My batch name']

$response->toArray(); // ['id' => 'batch_abc123', ...]

list

Returns a list of batches.

$response = $client->batches()->list(
    parameters: [
        'limit' => 10, 
    ],
);

$response->object; // 'list'
$response->firstId; // 'batch_abc123'
$response->lastId; // 'batch_abc456'
$response->hasMore; // true

foreach ($response->data as $result) {
    $result->id; // 'batch_abc123'
    // ...
}

$response->toArray(); // ['object' => 'list', ...]]

Vector Stores Resource

create

Create a vector store.

$response = $client->vectorStores()->create([
    'file_ids' => [
        'file-fUU0hFRuQ1GzhOweTNeJlCXG',
    ],
    'name' => 'My first Vector Store',
]);

$response->id; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->object; // 'vector_store'
$response->createdAt; // 1717703267
$response->name; // 'My first Vector Store'
$response->usageBytes; // 0
$response->fileCounts->inProgress; // 1
$response->fileCounts->completed; // 0
$response->fileCounts->failed; // 0
$response->fileCounts->cancelled; // 0
$response->fileCounts->total; // 1
$response->status; // 'in_progress'
$response->expiresAfter; // null
$response->expiresAt; // null
$response->lastActiveAt; // 1717703267

$response->toArray(); // ['id' => 'vs_vzfQhlTWVUl38QGqQAoQjeDF', ...]

retrieve

Retrieves a vector store.

$response = $client->vectorStores()->retrieve(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
);

$response->id; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->object; // 'vector_store'
$response->createdAt; // 1717703267
$response->name; // 'My first Vector Store'
$response->usageBytes; // 0
$response->fileCounts->inProgress; // 1
$response->fileCounts->completed; // 0
$response->fileCounts->failed; // 0
$response->fileCounts->cancelled; // 0
$response->fileCounts->total; // 1
$response->status; // 'in_progress'
$response->expiresAfter; // null
$response->expiresAt; // null
$response->lastActiveAt; // 1717703267

$response->toArray(); // ['id' => 'vs_vzfQhlTWVUl38QGqQAoQjeDF', ...]

modify

Modifies a vector store.

$response = $client->vectorStores()->modify(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
    parameters:  [
        'name' => 'New name',
    ],
);

$response->id; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->object; // 'vector_store'
$response->createdAt; // 1717703267
$response->name; // 'New name'
$response->usageBytes; // 0
$response->fileCounts->inProgress; // 1
$response->fileCounts->completed; // 0
$response->fileCounts->failed; // 0
$response->fileCounts->cancelled; // 0
$response->fileCounts->total; // 1
$response->status; // 'in_progress'
$response->expiresAfter; // null
$response->expiresAt; // null
$response->lastActiveAt; // 1717703267

$response->toArray(); // ['id' => 'vs_vzfQhlTWVUl38QGqQAoQjeDF', ...]

delete

Delete a vector store.

$response = $client->vectorStores()->delete(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
);

$response->id; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->object; // 'vector_store.deleted'
$response->deleted; // true

$response->toArray(); // ['id' => 'vs_vzfQhlTWVUl38QGqQAoQjeDF', ...]

list

Returns a list of vector stores.


_…[view the full README on GitHub](https://github.com/openai-php/client)._

// faq

What is client?

⚡️ OpenAI PHP is a supercharged community-maintained PHP API client that allows you to interact with OpenAI API.. It is open-source on GitHub.

Is client free to use?

client is open-source under the MIT license, so it is free to use.

What category does client belong to?

client is listed under uncategorized in the Claudeers registry of Claude-compatible tools.

14 views
★ 5,836 stars
unclaimed
updated about 1 month ago

// embed badge

client on Claudeers
[![Claudeers](https://claudeers.com/api/badge/client.svg)](https://claudeers.com/client)

// retro hit counter

client hit counter
[![Hits](https://claudeers.com/api/counter/client.svg)](https://claudeers.com/client)

// reviews

// guestbook

0/500

// related in Uncategorized / Others

🔓

Reverse engineer anything with agents, from app behavior down to native binaries.

// uncategorizedmorluto/⟨TypeScript⟩★ 423,040◷ MIT[ claude ]
🔓

Fair-code workflow automation platform with native AI capabilities. Combine visual building with custom code, self-host or cloud, 400+ integrations.

// uncategorizedn8n-io/⟨TypeScript⟩★ 209,482◷ NOASSERTION[ claude ]
🔓

The agent engineering platform.

// uncategorizedlangchain-ai/⟨Python⟩★ 148,973◷ MIT[ claude ]
🔓

100+ AI Agent & RAG apps you can actually run — clone, customize, ship.

// uncategorizedShubhamsaboo/⟨Python⟩★ 144,747◷ Apache-2.0[ claude ]

// built by

1 of its contributors also build on official projects — claude-code-security-review

→ see how client connects across the ecosystem