OpenAI PHP SDK: Complete Guide with Code Examples (2026)

php dev.to

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
Enter fullscreen mode Exit fullscreen mode

Initialization

$client = OpenAI::client(getenv('OPENAI_API_KEY'));
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Image Generation

$response = $client->images()->create([
    'model' => 'dall-e-3', 'prompt' => 'A futuristic PHP elephant',
    'n' => 1, 'size' => '1024x1024',
]);
echo $response->data[0]->url;
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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 + TransporterException in production

Originally published at kalyna.pro

Source: dev.to

arrow_back Back to Tutorials