Sub topic 5
Framing tokens as Server-Sent Events
This chapter assumes you can write a basic FastAPI route, understand async generators, and know that StreamingResponse sends each yielded chunk as it is produced. Here you will learn how to wrap each token in a format that clients can parse reliably.
Why plain chunks are not enough
The /count example sent raw text like chunk 0\n. That works for a demo. HTTP gives no guarantee that chunk boundaries on the wire match the boundaries of your yield calls. A proxy or network layer can merge two chunks or split one in half. If a token contains a newline, a client that splits on newlines will misread it.
Server-Sent Events (SSE) is a simple text format for sending a stream of messages over one HTTP response. It gives every message a clear end marker, so the client can recover your message boundaries.
The message format
An SSE message is a few lines of text ended by a blank line. The two fields you need are event (the message type) and data (the payload).
event: token
data: {"text": "Hello"}
The blank line, which means the text ends with \n\n, marks the end of the message. Without it, a client keeps waiting.
The response must also use the media type text/event-stream.
A helper that builds messages
Put the framing in one small function so every message is built the same way.
import json
def sse(event: str, data: dict) -> str:
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
print(repr(sse("token", {"text": "Hello"})))
print(repr(sse("token", {"text": "line one\nline two"})))Running this prints:
'event: token\ndata: {"text": "Hello"}\n\n'
'event: token\ndata: {"text": "line one\\nline two"}\n\n'In the second line, the newline inside the token appears as the two characters \n, not as a real line break.
Why JSON-encode the payload
json.dumps escapes newlines inside the token. The data: field must stay on one line, because a real line break would end it. If you wrote the raw token after data:, a token such as "a\n\nb" would end the message early and corrupt the stream.
JSON also lets you add fields later, such as a token index or a finish reason, without changing the format.
Event types
The endpoint in this tutorial uses three event names.
| Event | When it is sent | Payload |
|---|---|---|
| `token` | For each non-empty piece of text | `{"text": "..."}` |
| `done` | After the last token | `{}` |
| `error` | If generation fails | `{"message": "..."}` |
A client uses the event line to decide what to do. It appends text on token, stops on done, and shows a message on error. Sending an explicit done event lets the client tell a finished answer from a dropped connection.
Using the helper in a generator
Here is a self-contained endpoint that streams fixed words with SSE framing. It uses no LLM yet.
import asyncio
import json
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
def sse(event: str, data: dict) -> str:
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
async def words():
for word in ["Streaming", "with", "SSE"]:
yield sse("token", {"text": word + " "})
await asyncio.sleep(0.3)
yield sse("done", {})
@app.get("/words")
async def stream_words():
return StreamingResponse(words(), media_type="text/event-stream")Run it with uvicorn main:app and open curl -N http://localhost:8000/words. The -N flag turns off curl's own buffering. You should see three token messages, one every 0.3 seconds, then a done message.
Common errors
- Missing blank line. If the message ends with a single
\n, the client never sees a complete message. Always end with\n\n. - Raw text in
data:. Tokens with newlines break the framing. Usejson.dumps. - Wrong media type. Without
text/event-stream, browsers and SSE libraries will not treat the response as an event stream. - Yielding dicts.
StreamingResponseexpectsstrorbytes. Build the string first.
Exercise
A token from the model is the text Hi\n\nthere. What goes wrong if you write f"data: {token}\n\n" instead of using json.dumps, and how does json.dumps fix it?
Show answer
The two real newlines inside the token end the data field and the message early, so the client sees a broken message followed by stray text. json.dumps turns each newline into the two characters \n, so the whole payload stays on one line and the message ends only at the final blank line.