Skip to content
Guides

Streaming (SSE) ​

Enable Server-Sent Events (stream: true) to deliver tokens to users as they are generated, cutting perceived latency (TTFT) from seconds to hundreds of milliseconds.

OpenAI SSE Streaming with Usage Telemetry ​

Always pass stream_options: {"include_usage": true} when streaming OpenAI-compatible requests so the final SSE chunk includes exact prompt, completion, and cached token counts.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["VANIX_API_KEY"],
    base_url="https://api.vanix.io/v1",
)

stream = client.chat.completions.create(
    model="gpt-4o-mini",
    stream=True,
    stream_options={"include_usage": True},
    messages=[{"role": "user", "content": "Explain SSE chunk framing in 3 lines."}],
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        print("\n--- Usage:", chunk.usage)
ts
import OpenAI from 'openai'

const client = new OpenAI({
  apiKey: process.env.VANIX_API_KEY,
  baseURL: 'https://api.vanix.io/v1',
})

const stream = await client.chat.completions.create({
  model: 'gpt-4o-mini',
  stream: true,
  stream_options: { include_usage: true },
  messages: [{ role: 'user', content: 'Explain SSE chunk framing in 3 lines.' }],
})

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? '')
}

Reasoning Deltas in Streams ​

Reasoning models (deepseek-reasoner, o3, Claude Extended Thinking) emit thinking tokens before the final answer:

  • OpenAI-compatible stream: Check chunk.choices[0].delta.reasoning_content for chain-of-thought deltas and delta.content for final output.
  • Anthropic native stream (/v1/messages): Listen for content_block_delta events with delta.type === "thinking_delta" vs "text_delta".

Gateway Streaming Guarantees ​

  • 300s+ Idle Timeout: Vanix AI load balancers keep long-running reasoning streams open during extended thinking pauses without premature 504 resets.
  • Graceful Drain: During rolling updates, in-flight streaming connections receive up to 120 seconds to complete cleanly before replica shutdown.
  • Client-Side Best Practice: Always set HTTP client read timeouts to at least 120s (or 300s for deep reasoning workloads) and pass an AbortSignal / context.WithCancel so canceled user sessions stop billing upstream immediately.

Vanix AI Unified Model Gateway · https://api.vanix.io