Sub topic 4
The Server-Sent Events wire format
This chapter assumes you know basic HTTP requests and responses, can read Python and JavaScript, and know how chunked responses deliver a body in pieces. It covers the text format that most LLM APIs use to send streamed output. Once you know the format, you can write a parser, or debug one that fails.
What SSE is
Server-Sent Events (SSE) is a small text protocol for one-way streaming from server to client over ordinary HTTP. The server answers with Content-Type: text/event-stream and keeps the response open. It writes events into the body as they happen. The body is UTF-8 text, and the client reads it as it arrives.
SSE adds no framing beyond what HTTP gives you. Each event is a few lines of text, and a blank line ends it. That is why you can inspect a stream with curl -N (which turns off curl's output buffering) and read it directly.
Anatomy of an event
An event is a block of lines. Each line has the form field: value. A blank line ends the event.
event: message
id: 42
data: {"delta": "Hel"}
The specification defines four fields.
| Field | Meaning |
|---|---|
| `data` | The payload. Repeated `data` lines in one event are joined with `\n`. |
| `event` | An optional event name. If absent, the type is `message`. |
| `id` | An optional identifier the client can send back to resume a stream. |
| `retry` | A reconnection delay in milliseconds, used by browser `EventSource`. |
Lines that start with : are comments. Servers often send : keep-alive periodically so that idle connections are not closed by proxies. Clients must ignore comments. Unknown field names are also ignored.
Rules that cause bugs
Most parser bugs come from a handful of details.
- Only a blank line dispatches an event. If the connection drops after
data: {...}but before the blank line, the event is incomplete. The specification says to discard it, not to deliver a fragment. - One optional space is stripped. In
data: hello, the value ishello. Indata: hello(two spaces), the value ishello. Strip exactly one leading space, not all whitespace. - Multi-line data is joined with a newline. Two consecutive
data:lines produce one payload containing\n. Because of this, a relay that writes raw text containing newlines into adata:line corrupts the event. Encode the payload as JSON, or split it into onedata:line per line. - Line endings can be
\n,\r\n, or\r. A robust parser handles all three. The parser below strips\r\nfrom each line. It does not handle a bare\ras a line terminator. - Chunks are not events. A network read can end in the middle of a line. Chapter material on chunk boundaries comes later, but the rule starts here: buffer text until you have a complete line, and complete lines until you have a blank one.
How LLM APIs use SSE
Providers use the same format with their own payload conventions. The common pattern is:
- You send a normal HTTP request, usually a
POSTwith a JSON body, with a flag such asstream: true. - The response arrives as
text/event-stream. - Each event's
datais a JSON object describing a small piece of the answer (a delta). - Some APIs end with a sentinel such as
data: [DONE], which is not JSON. Others end with a typed final event.
Some APIs put the event kind in the event: field (for example event: content_block_delta) and also repeat it inside the JSON. Others use only data: lines and put the kind in the JSON. Check which one your provider uses before writing the parser. A parser that ignores event: is fine for the second style and loses information in the first.
data: {"delta": "Hel"}
data: {"delta": "lo"}
: keep-alive
data: [DONE]
A minimal parser
This function takes any iterable of text lines and yields one payload per event. It joins multiple data lines, skips comments, and sends nothing for events with no data.
import json
def iter_sse_data(lines):
"""Yield the data payload of each Server-Sent Event from an iterable of text lines."""
data_lines = []
for line in lines:
line = line.rstrip("\r\n")
if line == "":
# A blank line ends the event.
if data_lines:
yield "\n".join(data_lines)
data_lines = []
elif line.startswith(":"):
# Comment line, often used as a keep-alive.
continue
elif line.startswith("data:"):
value = line[5:]
if value.startswith(" "):
value = value[1:]
data_lines.append(value)
lines = [
'data: {"delta": "Hel"}',
"",
'data: {"delta": "lo"}',
"",
"data: [DONE]",
"",
]
text = ""
for payload in iter_sse_data(lines):
if payload == "[DONE]":
break
text += json.loads(payload)["delta"]
print(text) # HelloThe loop checks for [DONE] before calling json.loads. Parsing the sentinel as JSON raises json.JSONDecodeError, which is a common first error when you write this by hand.
The function ignores event, id, and retry. That is acceptable for the data-only style. If your provider uses event:, track the most recent event name in a variable. Reset it when you dispatch.
Reconnection and the browser EventSource
Browsers include an EventSource class that implements the full protocol, including automatic reconnection. After a drop, it waits for the retry interval and reconnects with a Last-Event-ID header set to the last id it saw. A server can use that to resume.
LLM chat APIs rarely work with EventSource, for two reasons. It only sends GET requests, so it cannot carry a JSON body. It also cannot set custom headers such as Authorization. This is why browser code for LLM streams typically uses fetch and parses the body itself, as a later chapter shows. The cost is that you must write the parsing and reconnection logic yourself.
Resuming a generation after a reconnect is also unusual for LLM APIs. A new request normally starts a new generation, and you pay for it again. Do not assume Last-Event-ID works with a provider unless its documentation says so.
Common errors
- The response is not an event stream. Check the
Content-Type. If an error occurs before streaming starts, many APIs return a normal JSON error with a 4xx or 5xx status. Treat the body as JSON in that case, not as SSE. - Splitting the body on
\n\nonly. This misses\r\n\r\nline endings. Normalize line endings first. - Printing raw lines. Output such as
data: {...}appears in your UI because the prefix was not stripped. - Newlines in a payload. A raw newline inside a
data:value ends that line. The next line is then ignored unless it starts with a field name. Encode payloads as JSON.
Exercise
A server sends these lines: data: first, data: second, then a blank line. What payload does the parser above yield, and how many events does it emit?
Show answer
It emits one event with the payload "first\nsecond". Two data: lines in the same block are joined with a newline, and only the blank line ends the event.
Exercise
A stream ends after the line data: {"delta": "lo"} with no blank line following. According to the SSE rules, and with the parser above, is the event delivered?
Show answer
No. An event is dispatched only when a blank line ends it. The parser above leaves the line in data_lines and never yields it, which matches the specification's rule to discard incomplete events.