Skip to content
AgenticAIWiki
  1. Learn
  2. Part 0
  3. 1. Engineering prerequisites for AI apps
  4. 1.6

Lesson 1.6 · 6 of 7 · 7 min read · Reviewed 24 Nov 2026

Streaming with server-sent events

By the end, you can

  • Read a server-sent events stream: event lines, data lines and blank-line separators.
  • Assemble streamed deltas into a final reply and handle a stream that ends early.

A model generates its reply one token at a time (chapter 2). Without streamingStreaming: Receiving a response as a series of server-sent events while it is generated, instead of waiting for the whole reply. you wait for every tokenToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. before you see any. With streaming, each piece arrives as soon as it exists. Most model APIs stream with server-sent eventsServer-sent events (SSE): A simple protocol for a server to push a stream of events to a client over one HTTP connection..

What SSE looks like on the wire

The client sends an ordinary HTTP request with "stream": true. The server answers with Content-Type: text/event-stream and keeps the connection open, writing plain text like this:

event: message_start
data: {"type": "message_start", "message": {"id": "msg_01", "usage": {"input_tokens": 12}}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": " there"}}

event: message_delta
data: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 2}}

event: message_stop
data: {"type": "message_stop"}

The rules are small:

Line Meaning
event: name The type of this event (optional; the default is message)
data: ... The payload. Several data: lines in one event are joined with newlines
: comment Ignored. Servers send these, or ping events, to keep the connection alive
blank line The event is complete: dispatch it

The event names above follow one provider’s API. Others use different names (some end with a data: [DONE] line), but the framing is the same SSE everywhere.

A worked example: assembling the reply

import json

text, stop_reason = [], None
for event in parse_sse(response_lines):        # yields (name, data) pairs
    payload = json.loads(event.data)
    if payload["type"] == "content_block_delta":
        text.append(payload["delta"].get("text", ""))
    elif payload["type"] == "message_delta":
        stop_reason = payload["delta"]["stop_reason"]
    elif payload["type"] == "error":
        raise RuntimeError(payload["error"]["message"])

reply = "".join(text)

In practice the SDK’s stream helper does this for you (client.messages.stream(...) with text_stream and get_final_message()). Knowing the wire format helps when you proxy a stream through your own backend, debug a gateway, or use a language with no SDK.

Why it matters

  • Perceived speed. A 6-second answer that starts showing at 0.5 seconds feels fast. The total time is the same.
  • Long outputs. Some APIs require streaming for very long generations, so the connection does not sit silent past a timeout.
  • Early stop. You can show progress, or cancel when the user navigates away, which stops paying for tokens nobody will read.

On other providers

Most model APIs stream over server-sent events, but the event names differ: OpenAI’s Responses API sends typed events such as response.output_text.delta, and Gemini streams generateContent chunksChunking: Splitting documents into smaller passages before embedding and indexing them.. Parse events into one internal shape (text delta, tool call, usage, done) so the rest of your app doesn’t care which provider is behind it.

Common mistakes

  • Treating each chunk as one event. Network chunks do not line up with events. Buffer until the blank line.
  • Ignoring the stop reasonStop reason: The field in a response that says why generation stopped: end_turn, max_tokens, stop_sequence, tool_use and others.. A stream can end with max_tokens. Check it exactly as you would for a normal reply.
  • No handling for mid-stream errors. An overload error can arrive after some text. Decide whether to retry the whole request or show what you have.
  • Buffering proxies. Some proxies and serverless platforms hold the whole response before sending it on, which silently turns streaming off. Test through the real path.

Key points

  • Server-sent events (SSE) is a simple one-way stream over a normal HTTP response. The server keeps the connection open and writes text events as they happen.
  • Each event is a few lines such as event: and data:, ended by a blank line. Model APIs put a small JSON object in each data line.
  • Streaming does not make generation faster. It shows the first words sooner, which is what users notice.
  • Your code must join the deltas, watch for the final stop event and handle errors that arrive mid-stream.
Hands-on labRuns in the Playground

Parse a server-sent events stream

Turn raw SSE text, split into awkward network chunks, into a finished reply and its stop reason.

You will have: An SSE parser that buffers chunks, skips comments, yields events and assembles the reply text.

Steps

  1. Keep a buffer and add each chunk to it.
  2. Each time the buffer holds a blank line, split off one event and read its event: and data: lines.
  3. Skip lines that start with a colon (keep-alive comments).
  4. Join the text of content_block_delta events and read stop_reason from message_delta.

Done when

  • The parser yields 6 events even though the chunks split one event in two.
  • The reply prints as "Hello there, how can I help?".
  • stop_reason prints end_turn.

Open in the Playground No API key needed.

Starter code (Python)
import json

# The stream as it arrived from the network. Chunks do not line up with events.
CHUNKS = [
    'event: message_start\ndata: {"type": "message_start", "message": {"usage": {"input_tokens": 12}}}\n\nev',
    'ent: content_block_delta\ndata: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello"}}\n\n',
    ': keep-alive comment\n\nevent: content_block_delta\ndata: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": " there,"}}\n',
    '\nevent: content_block_delta\ndata: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": " how can I help?"}}\n\n',
    'event: message_delta\ndata: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 7}}\n\n',
    'event: message_stop\ndata: {"type": "message_stop"}\n\n',
]

def parse_sse(chunks):
    # TODO: keep a text buffer; each time it contains a blank line ("\n\n"), split off one event,
    #       read its "event:" and "data:" lines, skip lines starting with ":", and yield (name, data)
    return []

text, stop_reason, count = [], None, 0
for name, data in parse_sse(CHUNKS):
    count += 1
    payload = json.loads(data)
    # TODO: append delta text from content_block_delta; read stop_reason from message_delta

print("events:", count)
print("reply:", "".join(text))
print("stop_reason:", stop_reason)
Show a solution
import json

# The stream as it arrived from the network. Chunks do not line up with events.
CHUNKS = [
    'event: message_start\ndata: {"type": "message_start", "message": {"usage": {"input_tokens": 12}}}\n\nev',
    'ent: content_block_delta\ndata: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello"}}\n\n',
    ': keep-alive comment\n\nevent: content_block_delta\ndata: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": " there,"}}\n',
    '\nevent: content_block_delta\ndata: {"type": "content_block_delta", "delta": {"type": "text_delta", "text": " how can I help?"}}\n\n',
    'event: message_delta\ndata: {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 7}}\n\n',
    'event: message_stop\ndata: {"type": "message_stop"}\n\n',
]

def parse_sse(chunks):
    """Buffer the text and yield (event, data) each time a blank line ends an event."""
    buffer = ""
    for chunk in chunks:
        buffer += chunk
        while "\n\n" in buffer:
            raw, buffer = buffer.split("\n\n", 1)
            name, data = "message", []
            for line in raw.split("\n"):
                if line.startswith(":"):
                    continue  # comment or keep-alive
                if line.startswith("event:"):
                    name = line[6:].strip()
                elif line.startswith("data:"):
                    data.append(line[5:].strip())
            if data:
                yield name, "\n".join(data)

text, stop_reason, count = [], None, 0
for name, data in parse_sse(CHUNKS):
    count += 1
    payload = json.loads(data)
    if payload["type"] == "content_block_delta":
        text.append(payload["delta"].get("text", ""))
    elif payload["type"] == "message_delta":
        stop_reason = payload["delta"]["stop_reason"]
    elif payload["type"] == "error":
        raise RuntimeError(payload["error"]["message"])

print("events:", count)
print("reply:", "".join(text))
print("stop_reason:", stop_reason)
Quick checkA streamed reply shows its first words after 0.5 s and finishes at 6 s. Without streaming, the same reply finishes at about 6 s. What did streaming change?
How sure are you?
Pick an answer and how sure you are