#### Model capabilities

# Streaming

Streaming outputs is **supported by all models with text output capability** (Chat, Image Understanding, etc.). It is **not supported by models with image output capability** (Image Generation).

Streaming outputs uses [Server-Sent Events (SSE)](https://en.wikipedia.org/wiki/Server-sent_events) that let the server send back the delta of content in event streams.

Streaming responses are beneficial for providing real-time feedback, enhancing user interaction by allowing text to be displayed as it's generated.

To enable streaming, you must set `"stream": true` in your request.

> [!CAUTION]
>
> When using streaming output with reasoning models, you might want to **manually override request
> timeout** to avoid prematurely closing connection.

These examples stream from the [Responses API](/developers/model-capabilities/text/generate-text), the preferred endpoint for text generation. For the legacy Chat Completions shape, see [Streaming from Chat Completions](#streaming-from-chat-completions-legacy).

```javascript customLanguage="javascriptAISDK"
import { xai } from '@ai-sdk/xai';
import { streamText } from 'ai';

const result = streamText({
  model: xai.responses('grok-4.7'),
  system:
    "You are Grok, a helpful and useful AI built by SpaceXSI.",
  prompt: 'Explain how neural networks learn in two sentences.',
});

for await (const chunk of result.textStream) {
  process.stdout.write(chunk);
}
```

```python customLanguage="pythonOpenAISDK"
import os
import httpx
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1",
    timeout=httpx.Timeout(3600.0)
)

stream = client.responses.create(
    model="grok-4.7",
    input=[
        {"role": "system", "content": "You are Grok, a helpful and useful AI built by SpaceXSI."},
        {"role": "user", "content": "Explain how neural networks learn in two sentences."},
    ],
    stream=True
)

for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
    elif event.type == "response.completed":
        print()
```

```javascript customLanguage="javascriptOpenAISDK"
import OpenAI from "openai";
const openai = new OpenAI({
    apiKey: process.env.XAI_API_KEY,
    baseURL: "https://api.x.ai/v1",
    timeout: 900000,
});

const stream = await openai.responses.create({
    model: "grok-4.7",
    input: [
        { role: "system", content: "You are Grok, a helpful and useful AI built by SpaceXSI." },
        {
            role: "user",
            content: "Explain how neural networks learn in two sentences.",
        }
    ],
    stream: true
});

for await (const event of stream) {
    if (event.type === "response.output_text.delta") {
        process.stdout.write(event.delta);
    } else if (event.type === "response.completed") {
        process.stdout.write("\n");
    }
}
```

```bash customLanguage="bash"
curl https://api.x.ai/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $XAI_API_KEY" \
-m 3600 \
-d '{
    "input": [
        {
            "role": "system",
            "content": "You are Grok, a helpful and useful AI built by SpaceXSI."
        },
        {
            "role": "user",
            "content": "Explain how neural networks learn in two sentences."
        }
    ],
    "model": "grok-4.7",
    "stream": true
}'
```

```python customLanguage="pythonXAI"
import os

from xai_sdk import Client
from xai_sdk.chat import user, system

client = Client(
    api_key=os.getenv('XAI_API_KEY'),
    timeout=3600,
)

chat = client.chat.create(model="grok-4.7")
chat.append(
    system("You are Grok, a helpful and useful AI built by SpaceXSI."),
)
chat.append(
    user("Explain how neural networks learn in two sentences.")
)

for response, chunk in chat.stream():
    print(chunk.content, end="", flush=True)

print()
print(response.content)
```

Example streaming responses in Python/Javascript:

```
Neural networks learn by adjusting connection weights to minimize prediction error. Through backpropagation, they propagate gradients backward through layers so each weight updates in the direction that improves accuracy on training data.
```

## The event stream

Each Responses API event arrives as an SSE frame with an `event:` line naming the event type and a `data:` line holding the event, which repeats the type in its `type` field. A reasoning model streams its reasoning summary first, then the answer:

```json
event: response.created
data: {"sequence_number":0,"type":"response.created","response":{"id":"<response_id>","model":"grok-4.7","object":"response","status":"in_progress","output":[],"temperature":0.7,"top_p":0.95,"store":true,"usage":null}}

event: response.reasoning_summary_text.delta
data: {"sequence_number":4,"type":"response.reasoning_summary_text.delta","delta":"The user asked for a","item_id":"rs_<response_id>","output_index":0,"summary_index":0}

event: response.output_text.delta
data: {"sequence_number":21,"type":"response.output_text.delta","delta":"Neural","item_id":"msg_<response_id>","output_index":1,"content_index":0,"logprobs":[]}

event: response.completed
data: {"sequence_number":66,"type":"response.completed","response":{"id":"<response_id>","status":"completed","usage":{"input_tokens":1270,"input_tokens_details":{"cached_tokens":1152},"output_tokens":294,"output_tokens_details":{"reasoning_tokens":252},"total_tokens":1564,"cost_in_usd_ticks":25760000}}}
```

A full run emits these event types in order:

| Event | Meaning |
|---|---|
| `response.created`, `response.in_progress` | The response object, before any output |
| `response.output_item.added` / `.done` | One output item (reasoning, message, tool call) starts or finishes |
| `response.reasoning_summary_part.added` / `.done` | A reasoning summary part starts or finishes |
| `response.reasoning_summary_text.delta` / `.done` | Reasoning summary text |
| `response.content_part.added` / `.done` | A content part of the message starts or finishes |
| `response.output_text.delta` / `.done` | Answer text |
| `response.completed` | The final response, including `usage` |

There is no `[DONE]` sentinel; `response.completed` ends the stream and carries the complete response, so you do not need to reassemble the deltas yourself. It is recommended that you use a client SDK to parse the event stream.

## Streaming from Chat Completions (legacy)

[Chat Completions](/developers/rest-api-reference/inference/chat-completions) is a legacy endpoint. It streams a different shape: each frame is a `chat.completion.chunk` whose `choices[0].delta` carries `reasoning_content` while the model thinks and `content` as it answers, and the stream ends with a literal `data: [DONE]` line.

```python customLanguage="pythonOpenAISDK"
import os
import httpx
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1",
    timeout=httpx.Timeout(3600.0)
)

stream = client.chat.completions.create(
    model="grok-4.7",
    messages=[
        {"role": "system", "content": "You are Grok, a helpful and useful AI built by SpaceXSI."},
        {"role": "user", "content": "Explain how neural networks learn in two sentences."},
    ],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
```

```javascript customLanguage="javascriptOpenAISDK"
import OpenAI from "openai";
const openai = new OpenAI({
    apiKey: process.env.XAI_API_KEY,
    baseURL: "https://api.x.ai/v1",
    timeout: 900000,
});

const stream = await openai.chat.completions.create({
    model: "grok-4.7",
    messages: [
        { role: "system", content: "You are Grok, a helpful and useful AI built by SpaceXSI." },
        {
            role: "user",
            content: "Explain how neural networks learn in two sentences.",
        }
    ],
    stream: true
});

for await (const chunk of stream) {
    const content = chunk.choices[0].delta.content;
    if (content) {
        process.stdout.write(content);
    }
}
```

```bash customLanguage="bash"
curl https://api.x.ai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $XAI_API_KEY" \
-m 3600 \
-d '{
    "messages": [
        {
            "role": "system",
            "content": "You are Grok, a helpful and useful AI built by SpaceXSI."
        },
        {
            "role": "user",
            "content": "Explain how neural networks learn in two sentences."
        }
    ],
    "model": "grok-4.7",
    "stream": true
}'
```

The frames look like this:

```json
data: {
    "id":"<completion_id>","object":"chat.completion.chunk","created":<creation_time>,
    "model":"grok-4.7",
    "choices":[{"index":0,"delta":{"reasoning_content":"The","role":"assistant"}}],
    "usage":{"prompt_tokens":41,"completion_tokens":1,"total_tokens":42,
    "prompt_tokens_details":{"text_tokens":41,"audio_tokens":0,"image_tokens":0,"cached_tokens":0}},
    "system_fingerprint":"fp_xxxxxxxxxx"
}

data: {
    "id":"<completion_id>","object":"chat.completion.chunk","created":<creation_time>,
    "model":"grok-4.7",
    "choices":[{"index":0,"delta":{"content":"Ah","role":"assistant"}}],
    "usage":{"prompt_tokens":41,"completion_tokens":1,"total_tokens":42,
    "prompt_tokens_details":{"text_tokens":41,"audio_tokens":0,"image_tokens":0,"cached_tokens":0}},
    "system_fingerprint":"fp_xxxxxxxxxx"
}

data: [DONE]
```
