Client
⚡️ OpenAI PHP is a supercharged community-maintained PHP API client that allows you to interact with OpenAI API.
Install / Use
/learn @openai-php/ClientREADME
OpenAI PHP is a community-maintained PHP API client that allows you to interact with the Open AI API.
- Follow the creator Nuno Maduro:
- YouTube: youtube.com/@nunomaduro — Videos every weekday
- Twitch: twitch.tv/enunomaduro — Streams (almost) every weekday
- Twitter / X: x.com/enunomaduro
- LinkedIn: linkedin.com/in/nunomaduro
- Instagram: instagram.com/enunomaduro
- Tiktok: tiktok.com/@enunomaduro
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:
- Nuno Maduro: github.com/sponsors/nunomaduro
- Sandro Gehri: github.com/sponsors/gehrisandro
- Connor Tumbleson: github.com/sponsors/iBotPeaches
Table of Contents
- Get Started
- Usage
- Models Resource
- Responses Resource
- Conversations Resource
- Conversations Items Resource
- Containers Resource
- Containers Files Resource
- Chat Resource
- Audio Resource
- Embeddings Resource
- Files Resource
- FineTuning Resource
- Moderations Resource
- Images Resource
- Vector Stores Resource
- Vector Stores Files Resource
- Vector Stores File Batches Resource
- Batches Resource
- Realtime Ephemeral Keys
- Completions Resource (legacy)
- Assistants Resource (deprecated)
- Thread Resource (deprecated)
- Thread Messages Resource (deprecated)
- Thread Runs Resource (deprecated)
- Thread Runs Steps Resource (deprecated)
- FineTunes Resource (deprecated)
- Edits Resource (deprecated)
- Meta Information
- Troubleshooting
- Testing
- [Webhooks][#webhooks]
- Services
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 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' => [
[
