Sub topic 2
Reading Delta Events
Assume basic HTTP, JSON, Python, JavaScript, asynchronous programming, and LLM tokens. A streamed LLM response usually contains small updates called deltas. Each delta describes what changed instead of repeating the entire message.
Reading delta events
An API commonly sends Server-Sent Events (SSE). Each event has one or more data: lines and ends with a blank line. The data is often JSON:
data: {"choices":[{"delta":{"content":"Hel"}}]}
data: {"choices":[{"delta":{"content":"lo"}}]}
data: [DONE]The content value is the text fragment. Append fragments in arrival order.
Parsing events that split across chunks
Network reads do not respect event boundaries. One read may end halfway through a JSON value. Keep an incomplete tail in a buffer and parse only complete events.
import json
def read_deltas(lines):
data_lines = []
for line in lines:
line = line.rstrip("\r\n")
if line == "":
if data_lines:
yield "\n".join(data_lines)
data_lines = []
elif line.startswith("data:"):
value = line[5:]
if value.startswith(" "):
value = value[1:]
data_lines.append(value)
lines = [
'data: {"choices":[{"delta":{"content":"Hel"}}]}', "",
'data: {"choices":[{"delta":{"content":"lo"}}]}', "",
"data: [DONE]", "",
]
message = ""
for payload in read_deltas(lines):
if payload == "[DONE]":
break
event = json.loads(payload)
delta = event["choices"][0].get("delta", {})
message += delta.get("content", "")
print(message) # HelloA production parser should also handle comments, multiple data lines, carriage returns, malformed JSON, and a final event without a blank line.
Building the message and reading metadata
Keep text separate from metadata. A delta can contain a role, text, tool-call fragments, or no content at all.
| Field | Meaning |
|---|---|
| `delta.content` | Text fragment |
| `finish_reason` | Why generation ended |
| `usage` | Input and output token counts |
The final event often contains a finish_reason such as stop, length, or tool_calls. Usage may arrive in that event, a separate event, or not at all unless enabled by the provider.
Reading the stream with `fetch` in the browser
The browser can read the response body incrementally and cancel it with AbortController.
async function streamText(url, body, onText, signal) {
const response = await fetch(url, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body),
signal
});
if (!response.ok || !response.body) throw new Error("Stream failed");
const reader = response.body
.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
while (true) {
const {done, value} = await reader.read();
if (done) break;
buffer += value;
const events = buffer.split(/\r?\n\r?\n/);
buffer = events.pop();
for (const event of events) {
for (const line of event.split(/\r?\n/)) {
if (line.startsWith("data: ")) onText(line.slice(6));
}
}
}
}
const controller = new AbortController();
streamText("/api/chat", {prompt: "Hello"}, console.log, controller.signal);
// Call controller.abort() to stop reading.Exercise
Why must a browser parser retain the buffer after splitting on blank lines?
Show answer
The remaining text may be an incomplete event whose JSON continues in the next network chunk.