OpenAI PHP SDK: Complete Guide with Code Examples (2026)
The openai-php/client is the official PHP library for the OpenAI API. This guide covers every major feature: chat completions, streaming, function calling, embeddings, image generation, audio, and error handling.
Installation
composer require openai-php/client
Initialization
$client = OpenAI::client(getenv('OPENAI_API_KEY'));
Chat Completions
$response = $client->chat()->create([
'model' => 'gpt-4o-mini',
'messages' => [
['role' => 'system', 'content' => 'You are a helpful assistant.'],
['role' => 'user', 'content' => 'What is the capital of France?'],
],
]);
echo $response->choices[0]->message->content; // Paris
Streaming
$stream = $client->chat()->createStreamed([
'model' => 'gpt-4o-mini',
'messages' => [['role' => 'user', 'content' => 'Write a poem about PHP.']],
]);
foreach ($stream as $response) {
echo $response->choices[0]->delta->content;
}
Function Calling
$response = $client->chat()->create([
'model' => 'gpt-4o-mini',
'messages' => [['role' => 'user', 'content' => "What's the weather in Kyiv?"]],
'tools' => [[
'type' => 'function',
'function' => ['name' => 'get_weather', 'description' => 'Get city weather',
'parameters' => ['type' => 'object',
'properties' => ['city' => ['type' => 'string']], 'required' => ['city']]],
]],
]);
$toolCalls = $response->choices[0]->message->toolCalls;
Embeddings
$response = $client->embeddings()->create([
'model' => 'text-embedding-3-small',
'input' => 'Laravel is a PHP framework.',
]);
$vector = $response->embeddings[0]->embedding; // 1536-dim float array
Image Generation
$response = $client->images()->create([
'model' => 'dall-e-3', 'prompt' => 'A futuristic PHP elephant',
'n' => 1, 'size' => '1024x1024',
]);
echo $response->data[0]->url;
Error Handling
use OpenAI\Exceptions\ErrorException;
use OpenAI\Exceptions\TransporterException;
try {
$reply = $client->chat()->create([...]);
} catch (ErrorException $e) {
// API error (rate limit, auth, etc.)
} catch (TransporterException $e) {
// Network error
}
Summary
-
chat()->create()for completions,createStreamed()for streaming -
embeddings()->create()for vectors,images()->create()for DALL·E -
audio()->transcribe()for Whisper,moderations()->create()for safety - Catch
ErrorException+TransporterExceptionin production
Originally published at kalyna.pro