Lesson 8 of 11 · Agents
Streaming
Stream a LangGraph run live: node updates, full state values, custom progress with get_stream_writer, model tokens filtered by node, and several modes at once.
- 7 min read
- Advanced
- Reviewed
- Explain why streaming matters for multi-step graphs
- Choose between the updates, values, custom and messages stream modes
- Send progress events from inside a node with get_stream_writer
- Stream model tokens and filter them by node
- Combine several stream modes
Don't make users stare at a spinner
A graph might call a model three times, run two tools and loop once before it answers, which can take 20 seconds or more. If nothing appears until the end, users assume it's broken. Streaming shows progress as it happens: which step is running, what it found, and the final answer word by word.
| Mode | What you get | Good for |
|---|---|---|
"updates" | Each node's returned update, as it finishes | Showing which step ran and what it changed |
"values" | The whole state after each step | UIs that redraw from the full state |
"custom" | Anything a node sends with the stream writer | Progress bars, status messages |
"messages" | Model tokens as they're generated, with metadata | Typing out the answer live |
Progress from inside a node
import time
from typing import TypedDict
from langgraph.config import get_stream_writer
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
files: list[str]
report: str
def scan(state: State) -> dict:
writer = get_stream_writer() # send progress messages while the node works
for i, name in enumerate(state["files"], start=1):
time.sleep(0.1) # pretend each file takes a moment
writer({"progress": f"scanned {i}/{len(state['files'])}: {name}"})
return {"report": f"{len(state['files'])} files scanned, no problems found"}
builder = StateGraph(State)
builder.add_node("scan", scan)
builder.add_edge(START, "scan")
builder.add_edge("scan", END)
graph = builder.compile()
inputs = {"files": ["invoice.pdf", "contract.docx", "photo.jpg"], "report": ""}
for mode, chunk in graph.stream(inputs, stream_mode=["custom", "updates"]):
print(f"{mode:<7} {chunk}")custom {'progress': 'scanned 1/3: invoice.pdf'}
custom {'progress': 'scanned 2/3: contract.docx'}
custom {'progress': 'scanned 3/3: photo.jpg'}
updates {'scan': {'report': '3 files scanned, no problems found'}}get_stream_writer() returns a function that sends custom events out of a node while it is still running, so a slow node can report its progress. Passing a list of modes streams all of them, as (mode, chunk) pairs.
The whole state
# "values" streams the WHOLE state after each step (useful for UIs that redraw everything)
for state in graph.stream({"files": ["a.pdf", "b.pdf"], "report": ""}, stream_mode="values"):
print(state){'files': ['a.pdf', 'b.pdf'], 'report': ''}
{'files': ['a.pdf', 'b.pdf'], 'report': '2 files scanned, no problems found'}"values" yields the full state: first the input, then the state after each step.
Tokens from a model inside the graph
from langchain.chat_models import init_chat_model
from langgraph.graph import END, START, MessagesState, StateGraph
model = init_chat_model("anthropic:MODEL_NAME")
def classify(state: MessagesState) -> dict:
return {"messages": [model.invoke("Classify this request in one word: " + state["messages"][-1].content)]}
def answer(state: MessagesState) -> dict:
return {"messages": [model.invoke(state["messages"])]}
builder = StateGraph(MessagesState)
builder.add_node("classify", classify)
builder.add_node("answer", answer)
builder.add_edge(START, "classify")
builder.add_edge("classify", "answer")
builder.add_edge("answer", END)
graph = builder.compile()
# "messages" mode streams model tokens from inside nodes, tagged with the node they came from
for token, metadata in graph.stream({"messages": [("user", "How do I fix a squeaky brake?")]},
stream_mode="messages"):
if metadata["langgraph_node"] == "answer": # show the user only the answer node's words
print(token.content, end="", flush=True)
print()Clean the rim and pads with alcohol, then check the pads for wear.
"messages" mode streams every token from every model call in the graph, as (token, metadata) pairs. The metadata says which node the call came from (langgraph_node), so you can show the user only the final answer's tokens and hide internal steps such as classification. On screen, the answer appears word by word as the model writes it.
How streaming works
Under the hood, streaming is a generator: it yields events while the graph is still running, instead of returning everything at the end. Here's a tiny version with three modes:
# Streaming in plain Python: a generator yields events WHILE the graph runs,
# so the caller can show progress instead of waiting for the end.
def scan_node(state, emit):
for i, f in enumerate(state["files"], start=1):
emit(("custom", f"scanned {i}/{len(state['files'])}"))
return {"report": "all clean"}
def summarise_node(state, emit):
for word in "No problems in any file".split():
emit(("messages", word)) # like model tokens arriving one by one
return {"summary": "No problems in any file"}
def stream(state, modes):
events = []
for name, node in [("scan", scan_node), ("summarise", summarise_node)]:
update = node(state, events.append)
state = {**state, **update}
events.append(("updates", {name: update}))
events.append(("values", dict(state)))
for mode, data in events: # hand events to the caller as they happen
if mode in modes:
yield mode, data
events.clear()
for mode, data in stream({"files": ["a.pdf", "b.pdf"]}, modes={"custom", "updates", "messages"}):
print(f"{mode:<8} {data}")Common mistakes
Filter a token stream by node, so users see the final answer as it's written but not the internal steps.
# Token events from stream_mode="messages": (text, node the token came from)
events = [("billing", "classify"), ("Your", "answer"), (" refund", "answer"),
(" is", "answer"), ("ok", "check"), (" on its way.", "answer")]
# Build the text the user should see: join only the tokens from the "answer" node, then print it.
Which stream mode lets a slow node report its progress while it is still running?
Summary
- Streaming shows a graph's progress instead of a long silence.
updates: each node's update;values: the full state;custom: events fromget_stream_writer;messages: model tokens.- Pass a list of modes to get
(mode, chunk)pairs. - Filter tokens by
langgraph_nodeso users only see the final answer. - Use
astreamin web apps.
Next: subgraphs.
Finished reading? Tick it off to track your progress.