AI Agent Streaming Tokens 2026
Users do not perceive total latency, they perceive time to first visible character. An eight-second answer that starts printing at 0.6s feels fast; the same answer appearing all at once feels stuck. Streaming improves the first number, not the second.
📜 Table of Contents
📖 Keep reading
Streaming Output for AI Agents
Perceived speed is time to first character. An eight-second answer that starts printing at 0.6s feels fast; the same answer delivered in one block feels broken. That is what streaming buys you.
The SSE wire format
The server responds with Content-Type: text/event-stream and separates messages with a blank line:
event: delta
data: {"text": "Beijing"}
event: done
data: {"tokens": 128}
event names the message, data carries the payload, id enables resume. EventSource reconnects automatically and replays Last-Event-ID.
Backend with FastAPI
def sse(event, data):
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
@app.get("/chat")
async def chat(q: str):
async def gen():
yield sse("start", {"q": q})
try:
async for chunk in agent_stream(q):
yield sse("delta", {"text": chunk})
except Exception as e:
yield sse("error", {"message": str(e)})
return
yield sse("done", {"ok": True})
return StreamingResponse(gen(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache",
"X-Accel-Buffering": "no"})
X-Accel-Buffering: no tells nginx not to buffer. Without it users see five seconds of nothing followed by the whole answer.
Frontend: fetch, not EventSource
EventSource is GET-only, cannot send a body, and cannot set custom headers. Use fetch and read the stream:
const reader = res.body.getReader();
const dec = new TextDecoder();
let buf = '';
while (true) {
const {value, done} = await reader.read();
if (done) break;
buf += dec.decode(value, {stream: true});
let i;
while ((i = buf.indexOf('\n\n')) >= 0) {
handleEvent(buf.slice(0, i));
buf = buf.slice(i + 2);
}
}
Split on \n\n, never on network chunks. Chunk boundaries are not event boundaries; assuming otherwise is the classic streaming bug.
Emit typed events
| Event | Payload | UI use |
|---|---|---|
| start | request id | Show a thinking indicator |
| delta | text fragment | Append to the bubble |
| tool_start | tool name, args | "Checking weather…" |
| tool_end | tool, latency | Collapse progress |
| done | token counts | Final state, cost log |
| error | code, message | Retry button |
Raw text alone cannot distinguish "model thinking" from "tool running", which kills progress UI.
Proxy settings
Disable proxy_buffering, raise proxy_read_timeout, use HTTP/1.1 for chunked transfer, and skip gzip on streaming routes. CDNs buffer too; give streaming its own uncached path.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Everything appears at once | Buffering proxy | Disable buffering, send X-Accel-Buffering |
| Drops at 30s | Read timeout | Raise timeout, add heartbeat |
| Garbled CJK | Byte-level slicing | TextDecoder with stream: true |
| Upstream keeps billing after client leaves | No cancellation | Watch for disconnect, cancel the task |
Cancel on disconnect
A closed tab does not stop generation unless you make it. Check request.is_disconnected() or cancel in finally. Long answers and batch jobs waste the most here.
FAQ
Does streaming hurt quality? No, generation is unchanged. Avoid injecting instructions mid-stream.
Can I stream JSON? Use JSON Lines or assemble incrementally. Truncated JSON breaks parsers.
SSE or WebSocket? SSE for one-way, WebSocket for bidirectional. Most chat products use streaming down and plain POST up.
Heartbeat? Every 15-30s send a : ping comment so idle proxies do not cut the connection.
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.