Sub topic 3
Reading and Hardening a Streaming LLM Client
Assume you know async/await, HTTP responses, FastAPI routes, and basic LLM chat APIs. This chapter focuses on consuming and operating a stream after the server has started responding.
Read Server-Sent Events in Python
An SSE event contains an event name and a data line, followed by a blank line. The client must read lines incrementally instead of waiting for the complete response.
import asyncio
import json
import httpx
async def main():
async with httpx.AsyncClient(timeout=None) as client:
async with client.stream(
"POST",
"http://localhost:8000/chat",
json={"prompt": "Say hello"},
) as response:
response.raise_for_status()
event = None
async for line in response.aiter_lines():
if line.startswith("event:"):
event = line[6:].strip()
elif line.startswith("data:"):
data = json.loads(line[5:].strip())
if event == "token":
print(data["text"], end="", flush=True)
elif event == "error":
print(f"\nError: {data['message']}")
return
elif event == "done":
print()
asyncio.run(main())Handle Errors After the Response Starts
The server can set an HTTP status only before sending the first bytes. A later failure must use an SSE event such as event: error. Do not send exception details to the client. Log the internal error and return a safe message.
Stop Work on Disconnect
When a client disconnects, FastAPI cancels the streaming task. An async generator should allow asyncio.CancelledError to propagate and close the upstream LLM stream in finally. Do not catch cancellation and continue generating tokens. This prevents wasted model work.
Prevent Proxy Buffering
Use Content-Type: text/event-stream, Cache-Control: no-cache, and, for Nginx, X-Accel-Buffering: no. Configure the proxy to avoid response buffering and idle timeouts. Otherwise, the application may produce tokens immediately while the client receives them in large delayed batches.
Test with a Fake LLM Client
Override the dependency with a fake client whose create method yields known chunks. Then assert that the response contains token events and a terminal event. This test checks framing without making a network call or spending on model usage. Always clear app.dependency_overrides in a finally block so tests remain isolated.
Set Limits and Observe Failures
Set a request model limit, such as max_length=4000, before starting generation. Apply an upstream timeout and an overall request or idle timeout. Log a request identifier, model name, prompt length, time to first token, completion duration, cancellation, and failure reason. Never log the prompt or generated text by default because they may contain sensitive data.
Exercise
Why can a streaming endpoint send an SSE error event but not change its HTTP status after the first token?
Show answer
HTTP headers, including the status, are sent before the response body. After streaming starts, the server can report failure only inside the response format, such as an SSE error event.