Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/phpaisdk/openrouter/llms.txt

Use this file to discover all available pages before exploring further.

OpenRouterTextModel::stream() enables streaming responses by setting stream: true in the /chat/completions request body. Instead of waiting for the full completion, the SDK returns a PHP Generator that yields text chunks as they are received, letting you print tokens to the user in real time.

Basic usage

Replace ->run() with ->stream() on the Generate::text() builder. The return value is a Generator — iterate over it with foreach to consume each chunk as it arrives:
use AiSdk\Generate;
use AiSdk\OpenRouter;

$stream = Generate::text()
    ->model(OpenRouter::model('openai/gpt-4o'))
    ->prompt('Explain closures in PHP.')
    ->stream();

foreach ($stream as $chunk) {
    echo $chunk;
    flush();
}
Each iteration yields a string containing the next piece of text from the model. Calling flush() after each chunk ensures output is pushed to the client immediately in HTTP contexts.

With a system prompt

You can combine instructions() and stream() in the same way as non-streaming requests:
$stream = Generate::text()
    ->model(OpenRouter::model('anthropic/claude-sonnet-4'))
    ->instructions('Reply concisely and in plain text.')
    ->prompt('What is a monad?')
    ->stream();

foreach ($stream as $chunk) {
    echo $chunk;
    flush();
}

How it works

Internally, OpenRouterTextModel::stream() uses ChatRequestBuilder to build the request body with stream: true and POSTs it to /chat/completions. The HTTP runner returns a stream of server-sent events, which ChatStreamParser processes line-by-line to extract the incremental text deltas before yielding them to your foreach loop.

Checking streaming support

You can check whether a specific model declares streaming as a supported capability before attempting to stream from it:
use AiSdk\Capability;
use AiSdk\OpenRouter;

$model = OpenRouter::model('openai/gpt-4o');

if ($model->supports(Capability::Streaming)) {
    $stream = Generate::text()
        ->model($model)
        ->prompt('Hello!')
        ->stream();

    foreach ($stream as $chunk) {
        echo $chunk;
    }
}
Not all models available through OpenRouter support streaming. Models that do not support it will either return an error or fall back to a buffered response. Check model capabilities in the OpenRouter model catalogue before relying on streaming in production.

Build docs developers (and LLMs) love