Sub topic 4
The Server-Sent Events wire format
This chapter assumes you know basic HTTP requests and responses, can read Python, and know what JSON is. It covers the text format that most LLM APIs use to send streamed output.
What SSE is
Server-Sent Events (SSE) is a simple text protocol for one-way streaming from server to client over a normal HTTP response. The server sends the header Content-Type: text/event-stream and keeps the connection open. It then writes events as plain UTF-8 text whenever it has something to say.
LLM APIs use SSE because each token batch can be sent as soon as it exists, and any HTTP client can read it.
The format
A stream is a series of lines. Events are separated by a blank line.
: keep-alive
data: {"delta": "Hel"}
data: {"delta": "lo"}
data: [DONE]
Each line has the form field: value. The common fields are:
| Field | Meaning |
|---|---|
| `data` | A piece of the event payload. Several `data` lines in one event are joined with `\n`. |
| `event` | An optional event name, such as `message_start`. Some APIs use it to label event types. |
| `id` | An optional event ID, used for resuming with the `Last-Event-ID` header. |
| `retry` | A reconnect delay in milliseconds, used by browser `EventSource`. |
| `:` (comment) | A line starting with a colon is ignored. Servers use these as keep-alives. |
If a value starts with one space after the colon, that single space is removed. The blank line is what completes an event. Until it arrives, the parser must keep collecting lines.
A minimal parser
This function follows those rules. It handles only data lines, which is enough for most LLM streams.
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) # HelloHow LLM APIs use it
Most providers put one JSON object in each data line. Some, such as OpenAI's chat API, end the stream with the literal text [DONE], which is not JSON. Check for it before calling json.loads. Others, such as Anthropic's, add event: lines and signal the end with a specific event type.
Common errors
- Parsing JSON from
[DONE]. This raises a decode error at the very end of an otherwise good stream. - Dropping the last event. If the connection closes without a final blank line, an unfinished event is discarded under the SSE rules. Decide deliberately whether your client should do the same.
- Splitting on every newline. A newline ends a line, not an event. Only a blank line ends an event.
- Sending raw newlines in a server's data. A token containing
\nwritten asdata: {token}would break the framing. Encode payloads as JSON, which escapes newlines.
Exercise
A server sends the text "data: first\ndata: second\n\n". How many events does a parser emit, and what is the payload?
Show answer
One event. Both lines belong to the same event because no blank line separates them, so the payload is "first\nsecond".