Lesson 52.5 · 5 of 6 · 6 min read · Reviewed 24 Nov 2026
Streaming intermediate events to the UI
By the end, you can
- Choose which intermediate events a graph run should stream to a user interface.
- Design a small, ordered event format the UI can render and resume.
A single model call streamsStreaming: Receiving a response as a series of server-sent events while it is generated, instead of waiting for the whole reply. tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. (1.6). A graph run is longer and has more going on: nodes start and finish, tests run, a loop goes round. Streaming intermediate events lets the user watch the run instead of a blank screen.
Three levels of events
| Level | Example event | Good for |
|---|---|---|
| Node progress | node_start: test, node_end: test |
A step list with ticks |
| State updates | update: {passed: false, failures: 2} |
Showing results as they land |
| Tokens | token: "def apply_disc" |
Live text inside a writing node |
Most UIs want node progress always, state updates for the few fields people care about, and tokens only for nodes that write text the user reads. Graph frameworks usually let you pick the level; LangGraph, for example, offers several stream modes for whole states, updates and model tokens.
A small event format
Keep each event tiny and self-describing:
{"run": "7f2", "seq": 14, "type": "node_end", "node": "test",
"data": {"passed": false, "failures": 1}}
- run ties the event to one run, so two tabs don’t mix.
- seq is a counter. The UI sorts by it, drops duplicates and, after a dropped connection, asks for “everything after 14”.
- type tells the UI how to render: a step tick, a result line, a token, an approval card.
A paused run (52.4) is just another event: {"type": "interrupt", "node": "merge", "data": {...}}. The UI shows the approval card when it arrives.
Getting events to the browser
Two common transports:
- 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. (SSE): one long HTTP response, server to browser only. Simple, works through most proxies, and browsers reconnect on their own. A good default for progress.
- WebSockets: two-way. Useful when the user sends input mid-run, such as approvals or cancels, over the same channel.
Either way, your graph runner emits events into a queue as nodes run, and the web handler forwards them.
What not to stream
- Secrets and credentials that sit in the state or in tool inputs.
- Raw internals the user can’t act on: full prompts, entire diffs on every update.
- Hidden reasoning you have chosen not to show.
Filter at the server. The browser should only ever receive the events you meant to send.
When to use it
Stream whenever a run takes more than a few seconds or has visible steps. For short, single-node runs, a normal response is simpler.
Common mistakes
- No sequence numbers. Reconnects replay or skip events and the step list goes wrong.
- Streaming everything. Thousands of token events for nodes nobody reads slow the page down.
- UI state that disagrees with the run. Derive the screen from events only, so it always matches what happened.
Key points
- Long graph runs feel broken if the screen stays blank; streaming events shows progress as each node starts and finishes.
- Stream three levels as needed: node progress, state updates, and model tokens inside a node.
- Give every event a run id, a sequence number and a type, so the UI can order, de-duplicate and reconnect.
- Send the UI what it needs to show, not the whole state; leave out secrets and raw internals.
Stream graph events to a UI
Emit small, ordered, filtered events from a graph run so a UI can render progress and recover from a dropped connection.
You will have: An event generator with run ids, sequence numbers and types, and a UI renderer that de-duplicates.
Steps
- Run the starter: events have no sequence numbers, the catch-up replays everything, and the token leaks.
- Add run, seq and type to every event.
- Filter secret fields out of the data before it leaves the server.
- Send the merge node as an interrupt so the UI can show an approval card.
- Run it and check the step list shows each event once, in order.
Done when
- 6 events are shown and the 1 duplicate from the reconnect is dropped.
- The last event has type interrupt.
- secrets leaked: 0.
Open in the Playground No API key needed.
Starter code (Python)
# Stream small, ordered events from a graph run to a UI, and survive a dropped connection.
SECRET_FIELDS = {"api_token"}
def graph_run():
"""Yields (node, update) as each node finishes. The state holds a secret the UI must never see."""
yield "plan", {"plan": "fix rounding", "api_token": "sim-demo-token"}
yield "write", {"code": "v1"}
yield "test", {"passed": False, "failures": 2}
yield "fix", {"code": "v2"}
yield "test", {"passed": True, "failures": 0}
yield "merge", {"waiting_for": "approval"}
def events(run_id):
seq = 0
for node, update in graph_run():
seq += 1
# TODO: give every event run, seq and type, and drop SECRET_FIELDS from data
# TODO: send a node_end event normally, but an "interrupt" event for the merge node
yield {"node": node, "data": update}
LOG = list(events("7f2")) # the server keeps the log so clients can catch up
def ui(received):
seen, lines = set(), []
for e in sorted(received, key=lambda e: e.get("seq", 0)):
key = (e.get("run"), e.get("seq"))
if key in seen:
continue
seen.add(key)
lines.append(f"{e.get('seq', '?')}. {e.get('type', '?')} {e['node']} {e['data']}")
return lines, len(received) - len(seen)
# The connection drops after event 3; the client reconnects and asks for everything after seq 2.
first = LOG[:3]
catch_up = [e for e in LOG if e.get("seq", 0) > 2]
lines, dupes = ui(first + catch_up)
print("\n".join(lines))
print(f"events shown: {len(lines)}, duplicates dropped: {dupes}")
print("secrets leaked:", sum("api_token" in e["data"] for e in LOG))
Show a solution
# Stream small, ordered events from a graph run to a UI, and survive a dropped connection.
SECRET_FIELDS = {"api_token"}
def graph_run():
"""Yields (node, update) as each node finishes. The state holds a secret the UI must never see."""
yield "plan", {"plan": "fix rounding", "api_token": "sim-demo-token"}
yield "write", {"code": "v1"}
yield "test", {"passed": False, "failures": 2}
yield "fix", {"code": "v2"}
yield "test", {"passed": True, "failures": 0}
yield "merge", {"waiting_for": "approval"}
def events(run_id):
seq = 0
for node, update in graph_run():
seq += 1
data = {k: v for k, v in update.items() if k not in SECRET_FIELDS}
kind = "interrupt" if node == "merge" else "node_end"
yield {"run": run_id, "seq": seq, "type": kind, "node": node, "data": data}
LOG = list(events("7f2")) # the server keeps the log so clients can catch up
def ui(received):
seen, lines = set(), []
for e in sorted(received, key=lambda e: e.get("seq", 0)):
key = (e.get("run"), e.get("seq"))
if key in seen:
continue
seen.add(key)
lines.append(f"{e.get('seq', '?')}. {e.get('type', '?')} {e['node']} {e['data']}")
return lines, len(received) - len(seen)
# The connection drops after event 3; the client reconnects and asks for everything after seq 2.
first = LOG[:3]
catch_up = [e for e in LOG if e.get("seq", 0) > 2]
lines, dupes = ui(first + catch_up)
print("\n".join(lines))
print(f"events shown: {len(lines)}, duplicates dropped: {dupes}")
print("secrets leaked:", sum("api_token" in e["data"] for e in LOG))