Sub topic 8
Putting the streaming endpoint together
This chapter combines the earlier pieces into one working endpoint. It assumes you can write async Python, define a FastAPI route with a Pydantic model, and know what a chat completion API is. It also assumes you have seen async generators, StreamingResponse, and the Server-Sent Events (SSE) format.
The complete endpoint
import json
import os
from functools import lru_cache
from fastapi import Depends, FastAPI
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
from pydantic import BaseModel, Field
app = FastAPI()
class ChatRequest(BaseModel):
prompt: str = Field(min_length=1, max_length=4000)
@lru_cache
def get_client() -> AsyncOpenAI:
return AsyncOpenAI()
def sse(event: str, data: dict) -> str:
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
async def token_events(client: AsyncOpenAI, prompt: str):
try:
stream = await client.chat.completions.create(
model=os.environ.get("LLM_MODEL", "gpt-4o-mini"),
messages=[{"role": "user", "content": prompt}],
stream=True,
)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
yield sse("token", {"text": chunk.choices[0].delta.content})
yield sse("done", {})
except Exception:
yield sse("error", {"message": "generation failed"})
@app.post("/chat")
async def chat(body: ChatRequest, client: AsyncOpenAI = Depends(get_client)):
return StreamingResponse(
token_events(client, body.prompt),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)The OpenAI client reads its key from the OPENAI_API_KEY environment variable. Run the app with uvicorn main:app.
How the pieces connect
Each part of the code has one job:
ChatRequestrejects empty or oversized prompts. FastAPI does this before your function runs, so a bad request gets a normal 422 response.get_clientis wrapped inlru_cache, so every request shares oneAsyncOpenAIclient and its connection pool.Dependshands it to the route, which lets tests swap it out.ssebuilds one SSE message. The blank line (\n\n) ends the message, and the client will not see the event without it.token_eventsis the async generator thatStreamingResponseconsumes. It yields one SSE message per piece of generated text.
Details that cause bugs
- Await the call, then iterate. With
stream=True,createis a coroutine that returns an async iterator. Writeawait client.chat.completions.create(...)first, thenasync for. - Guard each chunk. Some chunks have an empty
choiceslist. Others havedelta.contentset toNone, for example the chunk that carries the role or the finish reason. Theifin the loop skips both. - Send JSON in
data:.json.dumpsescapes newlines inside the text. A raw newline indata:would split the message and corrupt the framing. - Catch errors inside the generator. The 200 status and headers are sent with the first chunk. After that, raising an exception cannot change the status. The
exceptblock reports the failure as anerrorevent instead. A later chapter covers this in more detail. - Do not leak details. The error event carries a fixed message, not
str(exc). Log the real exception on the server.
Try it
Start the server, then run curl -N -X POST localhost:8000/chat -H "content-type: application/json" -d '{"prompt":"Say hello"}'. The -N flag turns off curl's own buffering. You should see event: token lines appear one at a time, followed by event: done.
Exercise
A request to /chat with an empty prompt returns a 422 response, but a request where the LLM provider is down returns 200 with an error event. Why do the two cases behave differently?
Show answer
Pydantic validation runs before the route function and before any response bytes are sent, so FastAPI can still return a 422 status. The provider call happens inside the generator after StreamingResponse has already started with status 200. At that point the status cannot change, so the failure is reported as an error event in the stream.