Sub topic 8
Putting the Streaming Endpoint Together
This chapter assembles the pieces from earlier chapters into one working endpoint. It takes a validated request, gets a shared LLM client, streams model output, and frames each piece as a Server-Sent Events (SSE) message.
Prerequisites
This chapter assumes you know:
- Basic Python, including
async/awaitand async generators. - How HTTP requests and responses work.
- A basic FastAPI route and Pydantic model.
- What an LLM chat API is.
You also need fastapi, uvicorn, openai and httpx installed, and an OPENAI_API_KEY environment variable set.
The pieces and how they connect
The endpoint combines five parts. Each one has a single job.
| Part | Job |
|---|---|
| `ChatRequest` | Validates the incoming JSON body before any work starts |
| `get_client` | Creates one shared async LLM client |
| `sse` | Turns an event name and a dictionary into one SSE message |
| `token_events` | An async generator that reads model chunks and yields SSE messages |
| `chat` | The route. It wires the parts together and returns a `StreamingResponse` |
The key point is the order of events. FastAPI validates the body and resolves dependencies first. Then the route function returns. The generator only starts running after that, when the server begins sending the response body.
The complete endpoint
Save this as main.py.
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"},
)Run it with uvicorn main:app.
Walking through each part
The request model
ChatRequest rejects an empty prompt and anything over 4000 characters. When validation fails, FastAPI returns a normal 422 JSON response. This works because the response has not started yet. Once streaming begins, the status code is already sent and can no longer change. That is why validation belongs at the top of the endpoint, before the generator exists.
The shared client
get_client is wrapped in lru_cache, so the first call creates an AsyncOpenAI instance and every later call returns the same one. The client holds a connection pool. Creating a new client per request would discard that pool and open fresh connections each time.
AsyncOpenAI() reads OPENAI_API_KEY from the environment. The key never appears in code.
Because the route receives the client through Depends, a test can replace it. A later chapter uses that to avoid calling a real model.
The SSE helper
An SSE message is plain text. It has an event: line, a data: line and a blank line that ends the message. The helper uses json.dumps for the data. This matters because model output often contains newlines. A raw newline inside a data: line would end that line early and corrupt the message. JSON escapes a newline as \n, so each message stays on one line.
A token containing a newline produces this on the wire:
event: token
data: {"text": "line one\nline two"}
The generator
token_events does four things:
- It opens a streaming completion with
stream=True. Theawaitreturns an async iterator of chunks. - It loops over chunks with
async for. - It skips chunks with no text. The check
chunk.choices and ...handles two cases. Some chunks have an emptychoiceslist. Others, such as the first chunk that carries the role or the last one that carries the finish reason, havedelta.contentset toNone. - It yields a
doneevent when the loop ends, so the client knows the stream finished normally.
Each yield hands one string to StreamingResponse, which writes it to the connection. The async for suspends while waiting for the next chunk. During that wait, the event loop can serve other requests.
The route
The route is short. It does not call the model itself. It builds the generator and returns it inside a StreamingResponse. Three details matter:
media_type="text/event-stream"sets theContent-Typeheader. Browsers and SSE libraries rely on it.Cache-Control: no-cachetells caches not to store the stream.X-Accel-Buffering: noasks an nginx proxy not to buffer the output. Without it, tokens can pile up in the proxy and arrive in one burst.
Why errors are yielded, not raised
The try/except sits inside the generator for a reason. By the time the generator runs, the server has usually already sent 200 OK and the headers. If the generator raised an exception, the server could not change the status. The connection would close in the middle of the body, and the client would see a truncated stream with no explanation.
Instead, the generator catches the failure and yields an error event. The client receives a clear signal and can show a message.
Two points about this code:
- The error message is generic on purpose. Sending
str(exc)could leak internal details, such as URLs or parts of a request, to the user. except Exceptiondoes not catchasyncio.CancelledError, which is aBaseExceptionin current Python. That is the right behavior. When a client disconnects, the cancellation should propagate and stop the work. A later chapter covers this in detail.
In production you would also log the exception on the server side before yielding the error event.
Running and checking it
Start the server and call it with curl. The -N flag turns off curl's own output buffering.
curl -N -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-d '{"prompt": "Say hello"}'You should see output like this, appearing gradually:
event: token
data: {"text": "Hello"}
event: token
data: {"text": "!"}
event: done
data: {}
If everything arrives at once at the end, something is buffering the output. The proxy chapter covers the usual causes.
Common mistakes
- Creating the client inside the generator. This opens a new connection pool per request and wastes time on every call.
- Skipping the
Nonecheck. Without it, the first chunk yields an event with"text": null, and the client may crash on it. - Raising instead of yielding errors. The client sees a dropped connection instead of an
errorevent. - Writing raw text into
data:. Newlines in model output break the framing. Always encode with JSON. - Using a blocking client. A synchronous
OpenAI()client inside anasyncgenerator blocks the event loop, and every other request stalls while one model call runs.
Summary of behavior
| Situation | What the client receives |
|---|---|
| Empty or oversized prompt | `422` JSON error, no stream |
| Normal generation | `token` events, then one `done` event |
| Model fails mid-generation | `token` events, then one `error` event |
| Client closes the connection | Nothing further. The server stops the generator |
Exercise
A teammate changes sse to return f"event: {event}\ndata: {data}\n\n", where data is the dictionary and is not passed through json.dumps. Name two problems this causes for the client.
Show answer
First, str() of a dictionary uses Python syntax with single quotes, such as {'text': 'Hi'}, which is not valid JSON, so the client's json.loads fails. Second, a token that contains a newline puts a raw line break inside the data: field, which ends the line early and breaks the SSE message framing. JSON encoding fixes both.
Exercise
The generator catches Exception and yields an error event. Why does the route not wrap StreamingResponse(...) in a try/except to return a 500 instead?
Show answer
The route returns the response object immediately, before the generator has run. The generator executes later, while the server sends the body, after the status code and headers have already gone out. Any failure at that point is outside the route's try/except and cannot change the status, so the error has to be reported as an event inside the stream.
Exercise
Why is get_client decorated with lru_cache, and what would happen to performance if you created AsyncOpenAI() inside token_events instead?
Show answer
lru_cache makes every request reuse one client, and with it one connection pool. Creating a client inside token_events would build a new pool for each request, so each call would pay for new connections and TLS handshakes, and idle pools would pile up until garbage collection.