For the complete documentation index, see llms.txt. This page is also available as Markdown.

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="deepseek/deepseek-chat-v3.1",
    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)

Getting Token Usage

To track token usage with streaming, add stream_options:

Token usage is included in the final chunk when include_usage: true.


Server-Sent Events Format

Under the hood, streaming uses Server-Sent Events (SSE):

Each line:

  • Starts with data:

  • Contains a JSON chunk or [DONE]

  • delta contains the new content piece

  • finish_reason appears 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

Use Case
Why

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

Use Case
Why

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):

For simpler code, consider using non-streaming requests when function calling is involved.


See Also

Last updated

Was this helpful?