Streaming
Get responses in real-time as they're generated.
Overview
Streaming delivers the model's response piece by piece instead of waiting for the complete answer. This provides:
Better user experience - Show progress immediately
Lower perceived latency - Users see content within milliseconds
Efficient for long responses - Don't wait for entire generation
Basic Usage
Add stream: true to your request:
from openai import OpenAI
client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://api.tensorx.ai/v1"
)
stream = client.chat.completions.create(
model="z-ai/glm-5.2",
messages=[{"role": "user", "content": "Write a haiku about coding"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)import OpenAI from 'openai';
const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://api.tensorx.ai/v1'
});
const stream = await client.chat.completions.create({
model: 'z-ai/glm-5.2',
messages: [{ role: 'user', content: 'Write a haiku about coding' }],
stream: true
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) {
process.stdout.write(content);
}
}Getting Token Usage
To track token usage with streaming, add stream_options:
Server-Sent Events Format
Under the hood, streaming uses Server-Sent Events (SSE):
Each line:
Starts with
data:Contains a JSON chunk or
[DONE]deltacontains the new content piecefinish_reasonappears in the final content chunk
Raw HTTP Streaming
If you're not using an SDK:
Accumulating the Full Response
Sometimes you need both streaming display AND the complete text:
When to Use Streaming
Use Streaming For
Chat interfaces
Users see responses immediately
Long-form content
Articles, stories, documentation
Code generation
See code as it's written
Real-time applications
Live transcription, assistants
Large outputs (>500 tokens)
Better user experience
Don't Use Streaming For
Batch processing
Adds complexity, no UX benefit
Background jobs
No one watching
JSON mode / structured output
Need complete valid JSON
Function calling
Wait for complete tool_calls
Short responses (<100 tokens)
Negligible difference
Validation required
Need full response first
Handling Finish Reasons
Check finish_reason in the final chunk:
Error Handling
Streams can fail mid-response. Always handle errors:
Streaming with Function Calling
When using tools, the model may return tool calls. These come all at once (not streamed character by character):
See Also
Chat Completions - Full API reference
Function Calling - Using tools
Rate Limits - Request limits
Last updated
Was this helpful?

