Watch It Run: Streaming and Saved State
Calling invoke on a graph runs it to the end and hands back only the final state, and once the call returns that state is gone. This page is about the two things you usually want next: watching a run while it happens, step by step or token by token, and keeping its state after it ends, so that a second run can carry on the same conversation and you can look back at what happened at each step.
A run moves in steps
Both streaming and saving depend on how LangGraph runs a graph. A run does not flow through the nodes continuously. It advances in discrete steps, which the documentation calls super-steps. In each step, every node that is scheduled to run gets the current state, does its work and returns its update. Only when all of them have finished are their updates merged into the state, each key through its reducer, and then the next step begins with the nodes the edges point to.
In a straight chain, each step holds one node. When a node has several outgoing edges, or a routing function returns a list of node names, all those destinations are scheduled together and run in the same step. The run ends when no node is scheduled any more.
- START
- classify
- check_orders
- check_account
- answer
- END
- START to classify
- classify to check_orders
- classify to check_account
- check_orders to answer: merged
- check_account to answer: merged
- answer to END
In this graph, check_orders and check_account run in the same step. Neither sees what the other writes during that step: both read the state as it was when the step began. Their two updates are merged afterwards, so answer, in the next step, sees both. If both nodes write to the same key, that key needs a reducer that combines the values (appending to a list, for example); without one, a plain key can take only one value per step.
The step is also the unit everything on the rest of this page counts in. Streaming reports what happened after each step, a checkpointer saves the state after each step, and the recursion limit counts steps.
True or false?
Two nodes that run in the same step can read each other's updates while they run.
False. Both read the state as it was at the start of the step. Their updates are merged only once the step is over, so the nodes of the next step see both.
In a graph that is a straight chain of three nodes, each node runs in its own step.
True. A node is scheduled only after the node before it has finished and its update is merged, so a chain takes one step per node.
Streaming a run
A compiled graph has a stream method next to invoke (and astream for async code). It takes the same input, but instead of returning once at the end it yields chunks as the run goes, so a program can print progress, show which node is working, or display an answer while it is being written. The stream_mode argument decides what each chunk holds.
With stream_mode="updates", you get one chunk per node after each step: a dictionary keyed by the node's name, holding only the keys that node returned. Here is a two-node graph with plain functions as nodes:
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
question: str
category: str
answer: str
def classify(state: State) -> dict:
return {"category": "billing"}
def answer(state: State) -> dict:
return {"answer": f"Sending this to the {state['category']} team."}
builder = StateGraph(State)
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()
for chunk in graph.stream({"question": "Why was I charged twice?"}, stream_mode="updates"):
print(chunk){'classify': {'category': 'billing'}}
{'answer': {'answer': 'Sending this to the billing team.'}}Each line names the node and shows only what it changed, which makes updates the mode for tracing which node ran and what it did. If two nodes run in the same step, their updates arrive as two separate chunks. A graph built with StateGraph also streams updates when you pass no mode at all.
With stream_mode="values", each chunk is instead the full state after a step, every key included. That is the mode to use when you want to render the whole current state each time, for example the latest message of the conversation.
Both of these report once per step, so a node that calls a model shows nothing until the model has finished. The third common mode fills that gap: stream_mode="messages" reports a model's message while it is being written.
In this mode each chunk is a pair. The first part is a piece of the message. The second is metadata about where that piece came from, including the name of the node under langgraph_node, so you can keep only the pieces of one node. It works for a LangChain chat model called anywhere in the graph, even when the node calls it with invoke rather than stream.
for chunk, metadata in graph.stream(inputs, stream_mode="messages"):
if metadata["langgraph_node"] == "agent":
print(chunk.content, end="", flush=True)The tokens come from the model, so what you see depends on it. A model that streams sends many small pieces. A model that does not stream, such as a fake model that returns prepared messages, still appears in this mode, but each message arrives once, whole.
You can pass a list of modes, such as stream_mode=["updates", "messages"]. Each chunk then comes as a pair of the mode's name and its data, so one loop can handle both. The table sums up the modes you will use most; the documentation lists a few more, for custom data a node writes and for debugging.
| stream_mode | Each chunk | Reported | Good for |
|---|---|---|---|
| updates (default) | node name and the keys it returned | after each step, per node | tracing which node ran |
| values | the full state | after each step | showing the current state |
| messages | (message piece, metadata) | while a model writes | showing an answer as it is written |
On top of these modes, LangGraph also has a higher-level event stream, stream_events. It runs the stream modes it needs underneath, and instead of raw chunks it gives typed views of a run, such as its messages, its state snapshots and its final output. Several parts of a program can read these views at the same time.
Its newest form, version="v3", is marked experimental in the reference, so the plain stream modes are the stable base to learn first.
True or false?
With stream_mode="updates", every chunk holds the whole state of the graph.
False. An update chunk holds only the keys one node returned, keyed by the node name. The full state after each step is what stream_mode="values" gives.
messages mode can show a model's tokens even when the node calls the model with invoke.
True. LangGraph collects the tokens of LangChain chat models from anywhere in the graph, whichever method the node used to call them.
A checkpointer saves every step
Streaming lets you watch a run, but when it ends its state still disappears. A checkpointer is the component that keeps it. You give one to the graph when you compile it, and from then on the graph saves a snapshot of its state, a checkpoint, after every step, not just at the end.
from langgraph.checkpoint.memory import InMemorySaver
graph = builder.compile(checkpointer=InMemorySaver())InMemorySaver keeps checkpoints in a Python dictionary inside the running process. It needs no setup, which makes it right for development and tests, and everything it holds is lost when the program exits. Saving to a file or a database is done by other checkpointers that ship as separate packages. You may still see the older name MemorySaver; it is the same class, kept for backwards compatibility.
Saving at every step means one run leaves several checkpoints, not one. A graph START → node_a → node_b → END run once leaves four: one for the input, then one after each step. Each records the state at that point and which node was due to run next.
- step -1 input received, next __start__
- step 0 input written, next node_a
- step 1 node_a done, next node_b
- step 2 node_b done, next: nothing
- step -1 to step 0
- step 0 to step 1
- step 1 to step 2
The step counter starts at -1 for the input, which is why the numbers look shifted. What matters is that between any two steps there is a complete, saved state. Several features that LangGraph builds on checkpoints depend on exactly that: pausing a run to wait for a person and resuming it later, restarting after a failure from the last step that succeeded, and going back to an earlier checkpoint to replay from there. They all start from the same saved state you are learning to use here.
True or false?
A checkpointer saves the state once, when the run reaches END.
False. It saves a checkpoint after every step. A run through two nodes leaves four checkpoints: the input and one after each step.
State kept by InMemorySaver is gone once the Python process exits.
True. It stores checkpoints in memory only. Keeping them across restarts takes a checkpointer that writes to a file or a database.
A thread id names one conversation
One checkpointer can hold many separate conversations, so each run has to say which one it belongs to. It does that with a thread id, a string you choose and pass in the run's config under configurable. Every checkpoint is saved under its thread id, and a later run with the same id starts from the latest checkpoint of that thread.
The node below returns an AI message saying how many messages it can see. The state is MessagesState, whose messages key has a reducer that appends new messages.
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, MessagesState, StateGraph
def reply(state: MessagesState) -> dict:
count = len(state["messages"])
return {"messages": [("ai", f"I can see {count} messages.")]}
builder = StateGraph(MessagesState)
builder.add_node("reply", reply)
builder.add_edge(START, "reply")
builder.add_edge("reply", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "ticket-42"}}
graph.invoke({"messages": [("user", "Hi")]}, config)
result = graph.invoke({"messages": [("user", "Still there?")]}, config)
print(len(result["messages"])) # 4
other = graph.invoke({"messages": [("user", "Hi")]}, {"configurable": {"thread_id": "ticket-7"}})
print(len(other["messages"])) # 2The first run leaves two messages in thread ticket-42: the question and the reply. The second run does not replace them. LangGraph loads the saved state, applies the new input through the reducers, so the new human message is appended after the two saved ones, and runs the graph again from its start. The reply now counts three messages, and the thread ends with four. Thread ticket-7 shares nothing with it and starts empty.
- run 1 2 messages saved
- run 2 starts from 2, ends with 4
- run 1 starts empty, ends with 2
- run 1 to run 2: same thread id
Two consequences follow. A graph compiled with a checkpointer needs the thread id on every call; leaving out configurable entirely raises an error instead of running without memory. And the only way to start a conversation from empty state on such a graph is a new thread id. Note also where things go in the config: thread_id sits under configurable, while a per-run setting such as recursion_limit sits at the top level of the same dictionary.
True or false?
Running again with the same thread id replaces the saved messages with the new input.
False. The new input is applied to the saved state through the reducers, so with an appending reducer the new message is added after the saved ones.
Two runs with different thread ids on the same compiled graph do not see each other's state.
True. Checkpoints are stored and loaded by thread id, so each id is its own conversation.
Reading the saved state
Because every checkpoint is kept, you can look at a thread without running it. graph.get_state(config) returns the latest checkpoint of the thread named in the config as a StateSnapshot. Its fields answer the questions you usually have when something went wrong:
| Field | What it holds |
|---|---|
| values | the state at this checkpoint, every key |
| next | the names of the nodes due to run next; () means the run was complete |
| metadata | the step number, the source (input or loop) and the writes of that step |
| config | the thread id and the id of this checkpoint |
| parent_config | the config of the checkpoint before it; None for the first |
| created_at | when it was saved |
graph.get_state_history(config) goes further and returns every checkpoint of the thread, each one a StateSnapshot, ordered with the most recent first. For the thread ticket-42 above, after its two runs:
snapshot = graph.get_state(config)
print(snapshot.values["messages"][-1].content)
print(snapshot.next)
for state in graph.get_state_history(config):
print(state.metadata["step"], state.next, len(state.values.get("messages", [])))I can see 3 messages.
()
4 () 4
3 ('reply',) 3
2 ('__start__',) 2
1 () 2
0 ('reply',) 1
-1 ('__start__',) 0Read from the bottom up, this is the whole story of the thread. The first run took steps -1 to 1; the second continued the count from 2 to 4 rather than starting again. At step 3 you can see the appended question already in the state with reply due next, and at step 4 the run is complete, with nothing left in next.
This is what makes the history useful when something goes wrong. When a run stops halfway, next of the latest snapshot tells you which node it was waiting on, and the history shows the values at each step that led there. Because it is a plain iterator, you filter it in Python, for example to find the checkpoint whose next is ("reply",).
True or false?
The first item get_state_history yields is the newest checkpoint of the thread.
True. The history is ordered most recent first, so the first item matches what get_state returns.
An empty tuple in next means the run stopped with an error.
False. An empty next means no node is due to run, which is what a run that reached its end leaves behind.