Instead of waiting for an entire completion to arrive before displaying anything, streaming lets you print each token to the user as soon as xAI produces it. TheDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/phpaisdk/xai/llms.txt
Use this file to discover all available pages before exploring further.
aisdk/xai package exposes streaming through a native PHP Generator, so you can iterate over partial response chunks with a standard foreach loop without pulling in any additional dependencies.
Basic streaming
Replace->run() with ->stream() to get a generator back. Iterate over it and echo each chunk as it arrives:
How streaming works
Calling->stream() on the builder invokes XAITextModel::stream(), which:
- Builds the chat completions request body with
stream: trueviaChatRequestBuilder. - POSTs to
/chat/completionson the xAI base URL (https://api.x.ai/v1by default) using a streaming HTTP client. - Returns a PHP
Generatorproduced byChatStreamParser::parse()from theaisdk/openai-compatiblepackage.
Generator yields one parsed server-sent event (SSE) frame from the API as a partial response object. The loop runs until the API sends the [DONE] sentinel.
Stream chunk fields
Every chunk yielded by the generator contains a partial response object with the following fields:| Field | Description |
|---|---|
$chunk->text | The incremental text fragment produced in this chunk. May be an empty string for the first and last frames. |
->run() instead.
Supported models
Streaming is declared as a first-class capability for every Grok text generation pattern in the model catalog:| Model pattern | Streaming supported |
|---|---|
grok-4* | ✅ Yes |
grok-3* | ✅ Yes |
grok-2* | ✅ Yes |
streaming in their capability set, so $model->supports(Capability::Streaming) returns true for any matching model ID.
HTTP implementation note
Under the hoodXAITextModel::stream() sends a POST request to /chat/completions with "stream": true in the JSON body. The response is consumed as a chunked HTTP stream of newline-delimited SSE frames:
ChatStreamParser from aisdk/openai-compatible, which means the xAI stream format is handled identically to any other OpenAI-compatible provider. You do not need to configure anything differently to enable streaming — xAI honours the standard SSE protocol.