SSE Streaming
How the support graph's steps, text and citations stream from FastAPI to the Next.js frontend over Server-Sent Events.
The chat endpoint returns a StreamingResponse immediately. As the graph runs, it yields SSE frames (step records, text deltas, citation events) that the frontend consumes incrementally.
SSE works over plain HTTP with no upgrade handshake and passes through any proxy. For server→client-only streaming, WebSockets add complexity for no benefit.
Event contract
Every frame is event: <name>\ndata: <json>\n\n.
| Event | Payload | When |
|---|---|---|
run | {run_id, conversation_id} | Once, before the first node |
step | {seq, stage, status, level, reasoning, latency_ms, ts, …} | As each node finishes |
text | {delta: str} | Each text chunk |
citation | {index, source, title, cited_text} | Each inline citation |
ticket_proposal | {run_id, subject, category, product_area, priority, body} | When a turn offers to file a ticket |
done | {conversation_id, run_id, outcome, confidence, ticket_id, input_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens, cost_usd, latency_ms} | After DB commit |
error | {message: str} | On any exception, instead of done |
outcome is "answer", "converse" or "ticket". It is three-way because a boolean cannot express this was not a support question. cost_usd is priced at the client model’s row in config/pricing/claude.yaml.
ticket_proposal is an offer, not a record: the ticket has not been filed when it arrives. The client renders it as a card with a confirm button, which posts to /api/c/{client_id}/runs/{run_id}/ticket. Nothing about the ticket travels in that request. The draft stays in the graph’s checkpoint, so a client can accept an offer but never author one.
The step event
The payload is the same dict written to Run.steps, returned by the same call that persists it. Runs & Durability lists the node-specific fields.
event: step
data: {"seq": 2, "stage": "grade", "status": "ok", "level": 1, "reasoning": "The passages cover Cloud Run deployment…", "confidence": 0.05, "kind": "question", "latency_ms": 4110, "cost_usd": 0.0008}
Unknown events are dropped silently by the frontend’s handleEvent, so backend work on a new event type stays invisible until the client learns to render it.
Sample streams
A turn answered at Level 1:
event: run
data: {"run_id": "3f2b...", "conversation_id": "..."}
event: step
data: {"seq": 1, "stage": "retrieve", "level": 1, "n_hits": 5, "top_similarity": 0.62, ...}
event: step
data: {"seq": 2, "stage": "grade", "level": 1, "confidence": 0.95, "kind": "question", ...}
event: text
data: {"delta": "That error means the container never listened on the port Cloud Run expects"}
event: citation
data: {"index": 1, "source": "corpus://gcp-platform-support/cloud-run-troubleshooting.md", "title": "Cloud Run troubleshooting", "cited_text": "Container failed to start. Failed to start and then listen on the port..."}
event: step
data: {"seq": 3, "stage": "answer", "level": 1, "n_citations": 2, ...}
event: done
data: {"conversation_id": "...", "run_id": "3f2b...", "outcome": "answer", "confidence": 0.95, "ticket_id": null, ...}
The answer step arrives after its text. The node records its step once the stream has closed and the final message’s usage is known.
A turn that falls through all three tiers:
event: run
data: {"run_id": "3f2b...", "conversation_id": "..."}
event: step
data: {"seq": 1, "stage": "retrieve", "level": 1, "n_hits": 5, "top_similarity": 0.5007, ...}
event: step
data: {"seq": 2, "stage": "grade", "level": 1, "confidence": 0.05, "kind": "question", ...}
event: step
data: {"seq": 3, "stage": "rewrite", "level": 2, "queries": ["request increase Cloud Run instance quota europe-west1", ...], "keywords": "Cloud Run quota europe-west1", ...}
event: step
data: {"seq": 4, "stage": "hybrid_retrieve", "level": 2, "n_hits": 5, ...}
event: step
data: {"seq": 5, "stage": "regrade", "level": 2, "confidence": 0.05, ...}
event: step
data: {"seq": 6, "stage": "escalate", "level": 3, "category": "quota_or_billing", ...}
event: ticket_proposal
data: {"run_id": "3f2b...", "subject": "Cloud Run instance quota increase in europe-west1", ...}
event: text
data: {"delta": "That one needs a human… I can open a quota or billing ticket for the platform team."}
event: done
data: {"conversation_id": "...", "run_id": "3f2b...", "outcome": "ticket", "ticket_id": null, ...}
There is no ticket step in that stream. The graph is paused, and the step arrives on the run when the user confirms. ticket_id is null because nothing has been filed.
A turn that is not a support question leaves at Level 1:
event: step
data: {"seq": 1, "stage": "retrieve", "level": 1, "n_hits": 0, "top_similarity": 0.0, ...}
event: step
data: {"seq": 2, "stage": "grade", "level": 1, "confidence": 0.0, "kind": "conversation", ...}
event: step
data: {"seq": 3, "stage": "converse", "level": 1, ...}
event: text
data: {"delta": "Hey — I answer Cloud Run, GKE and IAM questions from Google's public docs…"}
event: done
data: {"conversation_id": "...", "run_id": "3f2b...", "outcome": "converse", "ticket_id": null, ...}
The escalation and converse replies are
textevents too. A streaming client renders them exactly like an answer. Without them the UI shows a step trail above an empty bubble, which reads as a crash rather than a decision.
FastAPI endpoint
@router.post("/c/{client_id}/chat/stream")
async def chat_stream(client_id: str, req: ChatRequest):
cfg = _client(client_id)
_enforce_rate_limit(client_id, cfg)
async with AsyncSessionLocal() as preflight_db:
await _check_conversation_ownership(preflight_db, client_id, req.conversation_id)
await _enforce_daily_budget(preflight_db, cfg)
async def event_source():
async with AsyncSessionLocal() as db:
async for name, data in stream_turn(
req.message, template=documents.TEMPLATE, cfg=cfg, client_id=client_id,
conversation_id=req.conversation_id, db=db,
):
yield f"event: {name}\ndata: {json.dumps(data)}\n\n"
return StreamingResponse(
event_source(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
- Checks run before the response exists. Once the 200 and the first bytes are sent, a rejection can only be an
errorevent. - The turn’s session opens inside
event_source(), not viaDepends(get_db), because aDepends-scoped session closes beforeStreamingResponsestarts writing. X-Accel-Buffering: nostops nginx holding the entire stream and releasing it as one chunk.
How graph nodes stream
Graph nodes cannot yield to the endpoint: LangGraph runs them. They write to LangGraph’s custom stream instead, and stream_turn() forwards what arrives.
# inside a node
get_stream_writer()(("step", entry))
get_stream_writer()(("text", {"delta": event.delta.text}))
# stream_turn()
async for event, data in graph.astream(
initial, thread, context=deps, stream_mode="custom", durability="sync"
):
yield event, data
- The custom mode, not
updates. Anupdateschunk arrives only when a node returns, after all its text deltas. The custom stream carries steps, deltas and proposals in the exact order the nodes wrote them, in one mode. - The tuples are the SSE events. The endpoint serializes each
(event, data)pair unchanged, so it needs no per-event code. run,doneanderrorcome fromstream_turn(), not a node. They bracket the graph: one before it starts, one after the turn is persisted.
Errors
async def stream_turn(user_message, *, template, cfg, client_id, conversation_id, db):
try:
... # prepare, run the graph, persist, commit
yield ("done", {...})
except GraphCrash:
raise # the fault injector must kill the process
except Exception as exc:
await db.rollback()
await recorder.finish("failed")
yield ("error", {"message": "Upstream API error: RateLimitError"
if isinstance(exc, anthropic.APIError)
else "An internal error occurred. Please try again."})
The HTTP status went out with the first byte, so the error event is the only way to tell the client. A generator that simply stops looks like a finished turn from the browser’s side. Detail stays in the server log.
Frontend
ChatPanel.tsx uses fetch POST rather than EventSource (which is GET-only):
const response = await fetch(`/api/c/${clientId}/chat/stream`, {
method: "POST",
body: JSON.stringify({ message, conversation_id: conversationId }),
headers: { "Content-Type": "application/json" },
});
for await (const { event, data } of parseSse(response.body!.getReader())) {
handleEvent(event, data);
}
handleEvent drives React state:
| Event | Effect |
|---|---|
run | Stores the run id |
step | Appends to the message’s step trail |
text | Appends delta to the current message |
citation | Attaches a numbered popover to the preceding text segment |
ticket_proposal | Renders the confirm card |
done | Stores conversation_id; renders cost and latency |
error | Renders the error inside the assistant bubble |
Text and citations arrive interleaved, so the frontend builds { text, citations[] } segments rather than a flat string.
Next.js proxy route
Browser requests go to the Next.js API route at apps/web/app/api/c/[client_id]/chat/stream/route.ts, which proxies to FastAPI:
export async function POST(req: Request, { params }) {
const upstream = await fetch(
`${process.env.API_URL}/api/c/${params.client_id}/chat/stream`,
{ method: "POST", body: req.body, duplex: "half" }
);
return new Response(upstream.body, {
headers: { "Content-Type": "text/event-stream" },
});
}
The proxy keeps the FastAPI origin off the browser and handles CORS in one place.
Note: Streamable HTTP
Streamable HTTP is the MCP spec’s replacement for HTTP+SSE as an MCP server transport. It lets a single endpoint respond with either plain JSON or an SSE stream, and adds session management.
That overhead suits MCP servers serving external clients like Claude Desktop, not a custom chat API with a fixed event contract that always streams. If Configent ever exposes its retrieval as an MCP server, Streamable HTTP would be the right transport for that surface.