Sub topic 5
Framing tokens as Server-Sent Events
This chapter covers how to wrap each streamed token in a Server-Sent Events (SSE) message. It assumes you know basic Python with async/await, can read an HTTP response, and have written a FastAPI route that returns a StreamingResponse. The previous chapter showed that an async generator can yield strings and that FastAPI sends each one as it appears. Here we decide what those strings should look like.
Why raw chunks are not enough
A StreamingResponse sends bytes. It does not know where one token ends and the next begins. TCP, proxies, and HTTP chunked encoding may split or merge your writes, so two yield calls can arrive as one read, and one yield can arrive as two.
If you yield bare tokens like "Hel" and "lo", the client sees Hello and cannot tell how many tokens there were. It also has no way to tell a normal token from an error message or the end of the answer. Streaming needs a framing format: a rule that marks message boundaries and labels each message.
Server-Sent Events is a small text format designed for this. Its media type is text/event-stream. It is plain text, easy to read in curl, and supported by browsers, httpx, and many other clients.
Anatomy of an SSE message
An SSE stream is a sequence of messages. Each message is one or more lines of the form field: value. A blank line ends the message.
event: token
data: {"text": "Hel"}
event: token
data: {"text": "lo"}
event: done
data: {}
The blank line is the delimiter. A message without it is incomplete, and a conforming client will not act on it. Every message you send must therefore end in \n\n.
| Field | Meaning | Used in this tutorial |
|---|---|---|
| `event` | Names the message type. If absent, the type is `message`. | Yes: `token`, `done`, `error` |
| `data` | The payload. Several `data` lines in one message are joined with `\n`. | Yes: one JSON object per message |
| `id` | A message id the client can send back after a reconnect. | No |
| `retry` | Milliseconds the browser should wait before reconnecting. | No |
| a line starting with `:` | A comment. Clients ignore it. | Possibly, for keep-alives |
The `sse` helper
The endpoint in this tutorial builds every message with one small function:
import json
def sse(event: str, data: dict) -> str:
return f"event: {event}\ndata: {json.dumps(data)}\n\n"
if __name__ == "__main__":
print(repr(sse("token", {"text": "Hel"})))
print(repr(sse("done", {})))Running it prints:
'event: token\ndata: {"text": "Hel"}\n\n'
'event: done\ndata: {}\n\n'The function does three things worth understanding.
- It writes an
event:line, so the client can branch on the message type instead of guessing from the content. - It puts the payload in a single
data:line. - It ends with
\n\n, which is the message delimiter.
Why the payload is JSON
An LLM token is arbitrary text. It can contain newlines, quotes, non-ASCII characters, or text that looks like SSE syntax, such as \n\nevent: done. If you wrote the token directly after data: , a newline inside it would end the data line. The text after the newline would be parsed as a new field, or as the blank line that closes the message.
json.dumps solves this. It escapes a newline in a string as the two characters \ and n, so the encoded payload is always one physical line:
import json
token = "line one\n\nevent: done"
print(json.dumps({"text": token}))The output is {"text": "line one\n\nevent: done"}, with the \n shown literally and no real line breaks. The client decodes it with json.loads and recovers the exact original text.
JSON also gives you room to grow. Later you can send {"text": "Hel", "index": 0} without changing the framing, and clients that read only text keep working.
A side effect matters for testing: json.dumps uses ", " and ": " as separators by default. The output is {"text": "Hel"} with a space after the colon. The fake-client test later in this tutorial asserts on exactly that string. If you change the separators, for example with separators=(",", ":") to save bytes, update the test too.
By default json.dumps also escapes non-ASCII characters as \uXXXX. That is valid and safe, and json.loads restores them. Passing ensure_ascii=False gives smaller output for languages such as Chinese or Arabic, but then the response must be encoded as UTF-8. StreamingResponse encodes str chunks as UTF-8 already, so both options work.
Three event types
The endpoint uses a small vocabulary. Each type has a fixed meaning that the client can rely on.
token: one piece of generated text, with payload{"text": "..."}. There are many per stream.done: generation finished normally, with payload{}. There is at most one, and it is the last message.error: generation failed after the response had started, with payload{"message": "generation failed"}. It replacesdone.
A client can then end its loop on either done or error. It no longer needs to infer completion from a closed connection. This matters because a closed connection is ambiguous: it could mean success, a crash, or a proxy that timed out.
What a client does with these messages
A client reads the response as text, splits on blank lines, and processes the fields of each message. The function below does this for a complete string. It is not a streaming parser, but it shows the rules that real clients follow:
import json
def parse_sse(text: str) -> list[tuple[str, dict]]:
events = []
for block in text.split("\n\n"):
event = "message"
data_lines = []
for line in block.split("\n"):
if line.startswith(":"):
continue # comment line
field, _, value = line.partition(":")
value = value.removeprefix(" ") # one leading space is dropped
if field == "event":
event = value
elif field == "data":
data_lines.append(value)
if data_lines:
events.append((event, json.loads("\n".join(data_lines))))
return events
stream = (
'event: token\ndata: {"text": "Hel"}\n\n'
': keep-alive\n\n'
'event: token\ndata: {"text": "lo"}\n\n'
'event: done\ndata: {}\n\n'
)
for event, data in parse_sse(stream):
print(event, data)The output is:
token {'text': 'Hel'}
token {'text': 'lo'}
done {}Three details of the format show up here:
- One space after the colon is part of the syntax and is removed. Any further spaces belong to the value.
- A block with no
datalines is not dispatched. That is why the: keep-alivecomment produces no event. - Multiple
datalines are joined with\n. Our server never sends more than one, but a client should still handle it.
The Python client later in this tutorial does the same work line by line, which is what you need for a live stream.
Choices that follow from the format
Keep each message small and complete
Yield one sse(...) string per message. Do not build a message across two yield statements. A message is only valid once its terminating blank line has been sent, and a half-sent message is a protocol error if the stream breaks.
Keep the media type consistent with the body
Return media_type="text/event-stream". Clients and proxies use this header to decide how to treat the response. A body that is SSE-framed but labeled text/plain will often be buffered or displayed raw.
The browser `EventSource` has limits
Browsers parse SSE natively through EventSource, which also reconnects automatically. It can only send GET requests, with no body and no custom headers. Our /chat endpoint takes a JSON body, so it is a POST route. From a browser, you would call it with fetch and read response.body yourself, or switch to GET with a short prompt in the query string. Long prompts belong in a POST body, so this tutorial keeps POST.
Comments are useful as keep-alives
A line starting with : is ignored by clients, but it still counts as traffic on the connection. If a model can pause for many seconds before its first token, you can send ": keep-alive\n\n" periodically so idle-timeout rules in proxies do not close the connection. This tutorial does not add one, but the format supports it.
Do not add `id` and `retry` without a plan
id and retry support resuming a stream after a reconnect. Resuming requires the server to remember what it already sent, which an LLM call does not do by default. Without that state, a reconnect would restart the generation. Leave these fields out unless you build resume support.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Ending a message with a single `\n` | The client never sees the message boundary and waits | End with `\n\n` |
| Writing raw token text in `data:` | A token with a newline breaks the message | Encode the payload with `json.dumps` |
| Yielding a `dict` instead of a `str` or `bytes` | `StreamingResponse` raises an error, since it expects `str` or `bytes` chunks | Build the string with `sse(...)` |
| Using `media_type="application/json"` | Clients and proxies treat the body as one JSON document | Use `text/event-stream` |
| Forgetting the terminal event | The client cannot tell success from a dropped connection | Always send `done` or `error` |
Exercise
Exercise
The model produces the token "Hi\n\nthere". Show the exact string that sse("token", {"text": "Hi\n\nthere"}) returns, written as a Python string literal. Then explain why putting the raw token directly after data: would corrupt the stream.
Show answer
The result is 'event: token\ndata: {"text": "Hi\\n\\nthere"}\n\n'. In the source string, json.dumps turns each real newline into the two characters backslash and n, so the payload stays on one line, and only the final \n\n is a real blank line. If the raw token were written after data: , the two real newlines would end the data line and then create a blank line. The client would treat the message as finished after Hi, and it would parse there as an unknown field or the start of a new message.