Streaming LLM API in Production: Configuration and Error Handling
Summary
Configuring streaming responses for LLM API in production: SSE, error handling, timeouts, and monitoring.
1. Why Streaming is Needed
Streaming allows receiving model responses in parts, reducing the time to the first token and improving UX. This is critical for chatbots and interactive applications.
2. Basics of SSE
Server-Sent Events (SSE) is a standard protocol for streaming text.
Example response:
data: {"choices": [{"delta": {"content": "Hello"}}]}
data: {"choices": [{"delta": {"content": " world"}}]}
data: [DONE]
3. Implementation in Python (FastAPI)
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import httpx
app = FastAPI()
async def stream_llm(prompt: str):
async with httpx.AsyncClient() as client:
async with client.stream("POST", "https://api.provider.com/v1/chat/completions",
json={"model": "gpt-4", "messages": [{"role": "user", "content": prompt}], "stream": True}
) as response:
async for line in response.aiter_lines():
if line.startswith("data: "):
yield line[6:] + "\n\n"
@app.post("/chat")
async def chat(prompt: str):
return StreamingResponse(stream_llm(prompt), media_type="text/event-stream")
4. Error Handling During Streaming
4.1. Timeouts
Set a timeout for reading each chunk to avoid hanging.
timeout = httpx.Timeout(connect=10.0, read=30.0, write=10.0, pool=10.0)
4.2. Retries
Upon connection break, retry the request from the beginning, but do not duplicate already sent chunks.
async def stream_with_retry(prompt, max_retries=3):
for attempt in range(max_retries):
try:
async for chunk in stream_llm(prompt):
yield chunk
return
except httpx.ReadTimeout:
if attempt == max_retries - 1:
raise
await asyncio.sleep(2 ** attempt)
4.3. Partial Responses
If the client disconnects, complete the generation.
async def stream_llm(prompt, request):
async with httpx.AsyncClient() as client:
async with client.stream(...) as response:
async for line in response.aiter_lines():
if await request.is_disconnected():
break
yield line
5. Client Side (JavaScript)
const response = await fetch('/chat?prompt=Hello');
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
// Handle chunk
console.log(chunk);
}
6. Monitoring Streaming
- Measure time to first token (TTFT) and inter-token interval.
- Log number of chunks and total response size.
- Use observability tools described in llm-observability-stack.
7. Comparison of Streaming and Regular Request
| Parameter | Regular Request | Streaming |
|---|---|---|
| Time to First Token | High | Low |
| Perceived Speed | Slow | Fast |
| Implementation Complexity | Low | Medium |
| Error Handling | Easier | Harder |
8. Conclusion
Streaming is essential for modern LLM applications. Configure timeouts, retries, and monitoring to ensure stable operation. For managing limits and budget, see llm-api-rate-limit-budgeting.