Stream LLM tokens over SSE with disconnect detection
Implement a FastAPI StreamingResponse endpoint emitting Server-Sent Events and stopping upstream LLM generation if the client disconnects.
Model Answer & Explanation
@app.post("/chat/stream")
async def chat_stream(request: Request):
async def events():
try:
async for chunk in stream_llm():
if await request.is_disconnected():
break
yield f"data: {chunk}\n\n"
yield "data: [DONE]\n\n"
except asyncio.CancelledError:
pass
return StreamingResponse(events(), media_type="text/event-stream") Return StreamingResponse(event_stream(), media_type='text/event-stream') with Cache-Control: no-cache and X-Accel-Buffering: no. Inside the async generator, poll await request.is_disconnected() or cancel on asyncio.CancelledError inside a try/finally block so the upstream LLM stream is closed immediately when the user stops generation.