Streaming
Streaming sends each token as it is generated, so users see the first word in milliseconds instead of waiting for the full reply.
In this guide
- Read the SSE event format Studio returns
- Stream tokens in Python and curl
- Render partial tokens safely in the browser
- Decide when to stream, when to batch, and how to reconnect
Understand the SSE event format
Set stream: true on a chat request. The response is text/event-stream — a sequence of data: lines, each holding a small JSON delta, terminated by data: [DONE].
Deltas append in order. Concatenate choices[0].delta.content to rebuild the reply, and watch for empty heartbeat lines the proxy may inject. Full field details are in the Chat Completions reference.
Stream with Python and curl
Use the SDK iterator in Python for chat UIs and workers. Use curl -N to inspect raw events when debugging prompt or latency issues.
Prefer sage-2-5-celer for snappy streamed chat and sage-2-4-actus when streamed reasoning quality matters more than first-token speed.
Render tokens in the browser
Read the ReadableStream with fetch, split on newlines, and append each data: payload to the bubble. Buffer partial lines — a multibyte Nepali character can split across chunks.
Flush Markdown rendering progressively but debounce heavy layouts. Never eval streamed content — treat it as text.
Stream vs batch, and how to reconnect
Stream for anything a human watches: support chat, playgrounds, voice-agent transcripts. Prefer non-streamed or Batch API calls for nightly jobs, grading, and bulk translation where throughput beats interactivity.
| Path | First token | Best for |
|---|---|---|
| Streaming | sub-second | Live chat, demos, agent UX |
| Realtime call | seconds | Single short answers, webhooks |
| Batch | minutes to hours | Thousands of rows, 50 percent off |
Reconnects are normal on mobile networks. Retry strategy:
Send Last-Event-ID or your own turn ID when reconnecting, and dedupe by it server-side so a retried turn does not double-charge or double-send an SMS.
Best practices
- Show a typing indicator until the first token arrives, then stream words.
- Set tight timeouts on first-token (5s) and looser ones on full completion.
- Accumulate the full text server-side for logging even when streaming to the client.
- Fall back to a non-streamed call after two reconnect failures.
- Test with long Nepali replies to catch grapheme-splitting bugs early.
