PHPackages                             aisdk/openai - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. aisdk/openai

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

aisdk/openai
============

Official OpenAI provider for the PHP AI SDK.

v0.8.0(1mo ago)018↓50%MITPHPPHP ^8.3CI passing

Since Jun 30Pushed 4w agoCompare

[ Source](https://github.com/phpaisdk/openai)[ Packagist](https://packagist.org/packages/aisdk/openai)[ Docs](https://github.com/phpaisdk/openai)[ RSS](/packages/aisdk-openai/feed)WikiDiscussions main Synced 2w ago

READMEChangelog (10)Dependencies (13)Versions (14)Used By (0)

aisdk/openai
============

[](#aisdkopenai)

[![GitHub Workflow Status](https://camo.githubusercontent.com/309172b6b648c299aca53c212a1ca6e74676474a9a8015b4283cb2c0e95ec4c3/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f706870616973646b2f6f70656e61692f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d5465737473)](https://github.com/phpaisdk/openai/actions)[![Total Downloads](https://camo.githubusercontent.com/2eeb6a855299c662c20d882cdd7821008ef9fde43465a50a2c66e76832ad3e8d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f616973646b2f6f70656e6169)](https://packagist.org/packages/aisdk/openai)[![Latest Version](https://camo.githubusercontent.com/ae61b2ecf8ede8bda09ca21bdd7c5f84f4687a406b1b61061ba6c6479842dc61/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616973646b2f6f70656e6169)](https://packagist.org/packages/aisdk/openai)[![License](https://camo.githubusercontent.com/cb8b735794e240a81580ad8838c0fee43989ccb9a141e4c3dc516268a72dc013/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f616973646b2f6f70656e6169)](https://packagist.org/packages/aisdk/openai)[![Why PHP in 2026](https://camo.githubusercontent.com/d2b9305e630caf7daae4ca023de39ece0b885c37461629d42961533f00868b76/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5768795f5048502d696e5f323032362d3741383645383f7374796c653d666c61742d737175617265266c6162656c436f6c6f723d313831383162)](https://whyphp.dev)

---

Official OpenAI provider for the PHP AI SDK.

Installation
------------

[](#installation)

```
composer require aisdk/openai
```

Live sessions need a transport. Install the ready-made implementation, or use any application transport that implements the two contracts from `aisdk/core`:

```
composer require aisdk/transport
```

Basic Usage
-----------

[](#basic-usage)

```
use AiSdk\Generate;
use AiSdk\OpenAI;

$result = Generate::text()
    ->model(OpenAI::model('gpt-4o'))
    ->instructions('Write short, clear answers.')
    ->prompt('Explain closures in PHP.')
    ->run();

echo $result->text;
```

Default model shorthand:

```
Generate::model(OpenAI::model('gpt-4o'));

$result = Generate::text('Explain closures in PHP.')->run();
```

Configuration
-------------

[](#configuration)

### Environment Variables

[](#environment-variables)

VariableDescriptionDefault`OPENAI_API_KEY`API key for authenticationRequired`OPENAI_BASE_URL`Base URL for API requests`https://api.openai.com/v1``OPENAI_ORGANIZATION`Organization ID headerNone### Programmatic Configuration

[](#programmatic-configuration)

```
$provider = OpenAI::create([
    'apiKey' => 'sk-...',
    'baseUrl' => 'https://api.openai.com/v1',
    'organization' => 'org-...',
    'headers' => ['X-Custom-Header' => 'value'],
]);
```

Supported Capabilities
----------------------

[](#supported-capabilities)

CapabilitySupportText generationNativeStreamingNativeTool callingNativeStructured outputNative (`json_schema`)ReasoningNative (`reasoning_effort`)Image generationNativeSpeech generationNativeTranscriptionNativeEmbeddingsNativeLive voiceWebSocket, WebRTC, and SIP controlLive transcriptionWebSocket and WebRTCLive translationWebSocket and WebRTCText inputNativeImage inputNativeAudio inputNativeFile inputNativeStreaming
---------

[](#streaming)

```
use AiSdk\Generate;
use AiSdk\OpenAI;

$stream = Generate::text('Tell me a story.')
    ->model(OpenAI::model('gpt-4o'))
    ->stream();

foreach ($stream->chunks() as $chunk) {
    echo $chunk;
}

$result = $stream->run();
```

Embeddings
----------

[](#embeddings)

Generate one or more text embeddings in the same request:

```
use AiSdk\Generate;
use AiSdk\OpenAI;

$result = Generate::embedding(['Search query', 'Document text'])
    ->model(OpenAI::model('text-embedding-3-small'))
    ->dimensions(256)
    ->providerOptions('openai', ['user' => 'user-123'])
    ->run();

$queryVector = $result->embeddings[0]->vector;
$documentVector = $result->embeddings[1]->vector;
```

`dimensions()` is supported by OpenAI's `text-embedding-3` models. Model IDs remain opaque, so OpenAI validates whether the selected model accepts the requested dimensions.

Image Generation
----------------

[](#image-generation)

```
use AiSdk\Generate;
use AiSdk\OpenAI;

$result = Generate::image()
    ->model(OpenAI::model('gpt-image-1'))
    ->prompt('A clean app icon for a PHP AI SDK')
    ->size('1024x1024')
    ->run();

$result->output->save(__DIR__.'/icon.png');
```

Speech Generation
-----------------

[](#speech-generation)

```
use AiSdk\Generate;
use AiSdk\OpenAI;

$result = Generate::speech()
    ->model(OpenAI::model('gpt-4o-mini-tts'))
    ->input('Today is a wonderful day to build something people love.')
    ->voice('coral')
    ->format('mp3')
    ->providerOptions('openai', [
        'instructions' => 'Speak in a cheerful and positive tone.',
    ])
    ->run();

$result->output->save(__DIR__.'/speech.mp3');
```

Transcription
-------------

[](#transcription)

```
use AiSdk\Content;
use AiSdk\Generate;
use AiSdk\OpenAI;

$result = Generate::transcription(Content::audio(__DIR__.'/meeting.mp3'))
    ->model(OpenAI::model('gpt-4o-transcribe'))
    ->providerOptions('openai', ['language' => 'en'])
    ->run();

echo $result->output->text;
```

Live Voice Agents
-----------------

[](#live-voice-agents)

`AiSdk\Live` is part of core. `aisdk/openai` supplies OpenAI authentication, session configuration, event encoding, normalized events, client credentials, WebRTC signalling, and SIP lifecycle operations. The optional `aisdk/transport` package only supplies the network connection.

With the ready-made WebSocket transport:

```
use AiSdk\Live;
use AiSdk\Live\AudioDelta;
use AiSdk\Live\ResponseCompleted;
use AiSdk\OpenAI;
use AiSdk\Transport;
use function Amp\async;

$session = Live::voice()
    ->model(OpenAI::model('gpt-realtime-2.1'))
    ->instructions('Be concise and helpful.')
    ->voice('marin')
    ->turnDetection('disabled')
    ->inputAudioFormat('pcm16')
    ->outputAudioFormat('pcm16')
    ->connect(Transport::auto());

// Read and write concurrently. This example treats STDIN and STDOUT as raw
// 24 kHz mono PCM16, which makes it easy to connect an application audio I/O.
$sender = async(function () use ($session): void {
    while (! feof(STDIN)) {
        $bytes = fread(STDIN, 4096);
        if ($bytes !== false && $bytes !== '') {
            $session->sendAudio($bytes);
        }
    }

    $session->commitAudio();
    $session->requestResponse();
});

foreach ($session->events() as $event) {
    if ($event instanceof AudioDelta) {
        fwrite(STDOUT, $event->bytes);
    }

    if ($event instanceof ResponseCompleted) {
        break;
    }
}

$sender->await();
$session->close();
```

Without `aisdk/transport`, pass your own implementation directly. Core does not require Amp or any particular event loop:

```
use AiSdk\Live;
use AiSdk\OpenAI;
use App\Ai\AppWebSocketTransport;

$session = Live::voice()
    ->model(OpenAI::model('gpt-realtime-2.1'))
    ->voice('marin')
    ->connect(new AppWebSocketTransport());
```

The core repository includes a complete [`AppWebSocketTransport`](https://github.com/phpaisdk/core/blob/main/examples/AppWebSocketTransport.php)implementation using `amphp/websocket-client`. A custom transport moves text and binary frames only; OpenAI protocol handling remains in this package.

### Live tools

[](#live-tools)

Registered tools with handlers run automatically. Tool calls without a local handler remain available for manual authorization or execution:

```
use AiSdk\Live\ToolCallEvent;
use AiSdk\Schema;
use AiSdk\Tool;

$weather = Tool::make('weather', 'Get current weather')
    ->input(Schema::string(name: 'city')->required())
    ->run(fn (string $city): array => ['forecast' => "Sunny in {$city}"]);

$session = Live::voice()
    ->model(OpenAI::model('gpt-realtime-2.1'))
    ->tool($weather)
    ->connect(Transport::auto());

foreach ($session->events() as $event) {
    if ($event instanceof ToolCallEvent && $event->name === 'approval') {
        $session->sendToolResult($event->callId, ['approved' => true]);
    }
}
```

Parallel tool outputs are coordinated by the provider adapter. The next model response is requested once, only after every call in that response has an output.

Live Transcription and Translation
----------------------------------

[](#live-transcription-and-translation)

Streaming transcription sends audio over the Realtime connection and emits normalized transcript events:

```
use AiSdk\Live\TranscriptCompleted;
use AiSdk\Live\TranscriptDelta;

$session = Live::transcribe()
    ->model(OpenAI::model('gpt-realtime-whisper'))
    ->language('en')
    ->audioFormat('pcm16')
    ->connect(Transport::auto());

$session->sendAudio($pcmBytes);
$session->commitAudio();

foreach ($session->events() as $event) {
    if ($event instanceof TranscriptDelta) {
        echo $event->delta;
    }
    if ($event instanceof TranscriptCompleted) {
        echo "\nFinal: {$event->text}\n";
    }
}
```

OpenAI's dedicated Live translation protocol is exposed separately:

```
$session = Live::translate()
    ->model(OpenAI::model('gpt-realtime-translate'))
    ->from('en')
    ->to('es')
    ->inputAudioFormat('pcm16')
    ->outputAudioFormat('pcm16')
    ->connect(Transport::auto());

$session->sendAudio($pcmBytes);
$session->close(); // Sends session.close; keep reading until LiveClosed.

foreach ($session->events() as $event) {
    // AudioDelta and transcript events are normalized by core.
}
```

WebRTC
------

[](#webrtc)

For browser media, use the browser's native `RTCPeerConnection`; no PHP WebRTC stack is required. Your server can issue a scoped ephemeral secret:

```
$secret = Live::voice()
    ->model(OpenAI::model('gpt-realtime-2.1'))
    ->instructions('Help the signed-in user.')
    ->voice('marin')
    ->clientSecret();

return json_encode([
    'value' => $secret->value,
    'expires_at' => $secret->expiresAt,
]);
```

The browser uses that secret for OpenAI's WebRTC `/v1/realtime/calls` flow. Here is the complete browser side of that ephemeral-secret flow:

```
const token = await fetch('/openai/realtime-token').then((response) => response.json());
const peer = new RTCPeerConnection();
const events = peer.createDataChannel('oai-events');
const remoteAudio = new Audio();
remoteAudio.autoplay = true;

peer.ontrack = ({ streams }) => {
    remoteAudio.srcObject = streams[0];
};

events.onmessage = ({ data }) => {
    const event = JSON.parse(data);
    console.log(event);
};

const microphone = await navigator.mediaDevices.getUserMedia({ audio: true });
peer.addTrack(microphone.getAudioTracks()[0], microphone);

const offer = await peer.createOffer();
await peer.setLocalDescription(offer);

const response = await fetch('https://api.openai.com/v1/realtime/calls', {
    method: 'POST',
    headers: {
        Authorization: `Bearer ${token.value}`,
        'Content-Type': 'application/sdp',
    },
    body: offer.sdp,
});

if (! response.ok) {
    throw new Error(await response.text());
}

await peer.setRemoteDescription({
    type: 'answer',
    sdp: await response.text(),
});
```

Alternatively, keep signalling on your server and exchange an SDP offer with the provider adapter:

```
$answer = Live::voice()
    ->model(OpenAI::model('gpt-realtime-2.1'))
    ->voice('marin')
    ->webRtc($offerSdp);

return json_encode(['sdp' => $answer->sdp, 'call_id' => $answer->callId]);
```

`clientSecret()` and `webRtc()` are also available on `Live::transcribe()`. Dedicated translation WebRTC is handled through `Live::translate()->webRtc($offerSdp)`.

SIP Calls and Server Controls
-----------------------------

[](#sip-calls-and-server-controls)

Verify the exact raw webhook body before using its call ID. Then accept the call and optionally attach a WebSocket control session. OpenAI continues to carry the SIP media; the control connection observes events, updates the session, and handles tools.

```
$rawBody = file_get_contents('php://input');
$event = OpenAI::verifyWebhook(
    $rawBody,
    getallheaders(),
    $_ENV['OPENAI_WEBHOOK_SECRET'],
);

if (($event['type'] ?? null) === 'realtime.call.incoming') {
    $call = Live::voice()
        ->model(OpenAI::model('gpt-realtime-2.1'))
        ->instructions('You are the phone support agent.')
        ->voice('marin')
        ->call($event['data']['call_id']);

    $call->accept();
    $control = $call->connect(Transport::auto());

    foreach ($control->events() as $controlEvent) {
        // Handle normalized events and tools on the server.
    }

    $call->hangup();
}
```

Webhook verification enforces the signed raw bytes and the documented five-minute timestamp window. Do not decode and re-encode the body before calling `verifyWebhook()`.

Structured Output
-----------------

[](#structured-output)

```
use AiSdk\Generate;
use AiSdk\OpenAI;
use AiSdk\Schema;

$result = Generate::text()
    ->model(OpenAI::model('gpt-4o'))
    ->prompt('Extract the city and country from: Lahore, Pakistan.')
    ->output(Schema::object(
        name: 'address',
        properties: [
            Schema::string(name: 'city')->required(),
            Schema::string(name: 'country')->required(),
        ],
    ))
    ->run();
```

Tools
-----

[](#tools)

```
use AiSdk\Generate;
use AiSdk\OpenAI;
use AiSdk\Schema;
use AiSdk\Tool;

$weather = Tool::make('weather', 'Get current weather')
    ->input(Schema::string(name: 'city')->required())
    ->run(fn (string $city): string => "Sunny in {$city}");

$result = Generate::text()
    ->model(OpenAI::model('gpt-4o'))
    ->prompt('What is the weather in Lahore?')
    ->tool($weather)
    ->run();
```

Model IDs and Capabilities
--------------------------

[](#model-ids-and-capabilities)

OpenAI model IDs pass through unchanged and do not need to be registered. The package does not ship a model inventory; the OpenAI API remains the authority on whether a particular model accepts a requested feature.

Capabilities describe what the OpenAI adapter can serialize. The OpenAI API returns a normalized SDK exception if the selected model or requested feature is rejected.

Provider-Specific Options
-------------------------

[](#provider-specific-options)

Raw provider options can be passed as an escape hatch:

```
$result = Generate::text('Hello')
    ->model(OpenAI::model('gpt-4o'))
    ->providerOptions('openai', [
        'raw' => ['seed' => 42, 'service_tier' => 'default'],
    ])
    ->run();
```

Testing
-------

[](#testing)

```
composer test
```

The default suite is fixture- and conformance-based. Credentialed Live network verification is separate and is not run by `composer test`.

Documentation
-------------

[](#documentation)

- [PHP AI SDK documentation](https://phpaisdk.com/docs)
- [OpenAI documentation](https://phpaisdk.com/docs/openai)

Community
---------

[](#community)

- [Contributing](https://github.com/phpaisdk/.github/blob/main/CONTRIBUTING.md)
- [Support](https://github.com/phpaisdk/.github/blob/main/SUPPORT.md)
- For private security reports, email .

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance94

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

13

Last Release

31d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ef29d1962da41e7526023f215cf844494e209b2fd163742084cb919a3b508021?d=identicon)[aisdk](/maintainers/aisdk)

---

Top Contributors

[![RanaMoizHaider](https://avatars.githubusercontent.com/u/58527494?v=4)](https://github.com/RanaMoizHaider "RanaMoizHaider (19 commits)")

---

Tags

aiopenaillmaisdk

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/aisdk-openai/health.svg)

```
[![Health](https://phpackages.com/badges/aisdk-openai/health.svg)](https://phpackages.com/packages/aisdk-openai)
```

###  Alternatives

[cognesy/instructor-php

The complete AI toolkit for PHP: unified LLM API, structured outputs, agents, and coding agent control

326127.9k1](/packages/cognesy-instructor-php)[soukicz/llm

LLM client with support for cache, tools and async requests

4417.3k](/packages/soukicz-llm)[alidaaer/laravel-ai-agent

Give your Laravel app a brain, safely. Build AI Agents that can execute real actions in your application.

281.0k](/packages/alidaaer-laravel-ai-agent)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
