Sub topic 2
Framing Tokens as Server-Sent Events
Assume you know basic Python async/await, HTTP responses, FastAPI routes, Pydantic models, and the basic request-and-response pattern of an LLM API.
Framing tokens as Server-Sent Events
Server-Sent Events (SSE) is a text format for sending a sequence of events over one long-lived HTTP response. Each event has an event name and a data line. A blank line ends the event.
For JSON payloads, use one event per token or control message:
event: token
data: {"text": "Hello"}
event: done
data: {}The client can render each token immediately instead of waiting for the complete answer.
Streaming chunks from an async LLM client
An async LLM client returns an async iterable when streaming is enabled. Each chunk can contain a small piece of generated text. Some chunks contain metadata or no text, so check the content before sending it.
Providing the LLM client with `Depends`
FastAPI's Depends calls a provider and passes its result into the route. A cached provider creates one shared async client instead of creating a client for every request.
Putting the endpoint together
import asyncio
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:
text = chunk.choices[0].delta.content
if text:
yield sse("token", {"text": text})
yield sse("done", {})
except asyncio.CancelledError:
raise
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 cancellation branch preserves disconnect cancellation. Other failures become an error event because HTTP headers have already been sent.
Exercise
Why does sse() end each event with two newline characters?
Show answer
The first newline ends the data line, and the blank line tells the SSE client that the event is complete.