Build SSE streaming for AI agents with FastAPI and fetch
This tutorial builds a first version of AI agent streaming with Server-Sent Events, FastAPI, and the browser Fetch API. It shows how to format multiline SSE frames, stop upstream generation when the client disconnects, clean up the model stream, and buffer browser chunks into complete events. Automatic reconnection, resumption, retry limits, and several shutdown edge cases are intentionally deferred to a later article.
The implementation directly addresses how AI agents can begin displaying responses earlier while avoiding dropped multiline output and continued token consumption after a client disconnects.
前两篇讲了 Agent 的循环和 LangGraph 编排。这一篇聊一个直接影响用户体验的东西——流式输出。没有它,你的 Agent 在用户眼里就是「转圈 5 秒,然后蹦一大段字」的半成品。
这篇的目标是把第一版流式跑通,并且跑通的版本不会在你看不见的地方出丑。重连、续传、重试上限这些边界,下一篇专门讲,这篇只留接口。
一、为什么必须流式
大模型生成是逐 token 的,一次完整回复可能要 3–10 秒。如果等全生成完再返回:
- 用户盯着转圈圈,以为卡了;
- 长文容易触发网关超时;
- 首字延迟(TTFT)极高,体验像拨号上网。
流式输出让第一个字在几百毫秒内就出现,后面边生成边显示,体验天差地别。