Skip to content

Chapter 7 · Streaming and frontend event contracts ​

Deliver intermediate progress to the UI rather than waiting for the whole graph. Distinguish values, updates, and custom with a deterministic example before adding token streaming.

Mechanics and design choices ​

This example explicitly selects version="v2", requiring LangGraph 1.1+. Every event has type, ns, and data. updates contains node changes, values contains snapshots, and custom carries application progress. messages contains model chunks and metadata, not arbitrary strings returned by nodes. Current docs recommend considering event streaming introduced in 1.2 for new applications; its versioning is distinct from stream v2.

Example ​

python
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.config import get_stream_writer

class State(TypedDict):
    topic: str
    report: str

def report(state: State):
    writer = get_stream_writer()
    writer({"stage": "collect", "completed": 1, "total": 2})
    writer({"stage": "format", "completed": 2, "total": 2})
    return {"report": f"Report: {state['topic']}"}

builder = StateGraph(State)
builder.add_node("report", report)
builder.add_edge(START, "report")
builder.add_edge("report", END)
graph = builder.compile()
parts = list(graph.stream(
    {"topic": "local fixtures", "report": ""},
    stream_mode=["updates", "custom"], version="v2",
))
assert len([p for p in parts if p["type"] == "custom"]) == 2
for part in parts:
    print(part["type"], part["ns"], part["data"])

Run and verify ​

Run and expect two custom progress events plus a report update. Assert the application contract rather than internal scheduler log counts. Wrap these events in SSE or WebSocket messages at the transport layer.

Pitfalls ​

State may contain user input, retrieved text, and internal fields. Do not expose every value to clients. A browser disconnect does not necessarily cancel server work; define cancellation and recovery separately.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. What does updates contain?

2. What distinguishes v2 events?

3. Is any returned string a messages event?

4. Should all state be exposed?

Hands-on exercises ​

  1. Display only stage and progress, filtering all other fields.
  2. Add a subgraph and inspect how ns identifies event origin.
  3. Design reconnection without duplicate application events.

Official references ​

Verified on: 2026-09-17.