Lesson 2 of 11 · Graphs
State, Nodes and Edges
Define LangGraph state with TypedDict, write nodes that return partial updates, run steps in parallel, and merge updates with reducers like add_messages.
- 7 min read
- Advanced
- Reviewed
- Define a graph's state schema with TypedDict
- Write nodes that return only the keys they change
- Connect nodes with edges, including parallel branches that join
- Use reducers to combine updates to the same key
- Use MessagesState for conversations
The state schema
Every graph starts with a description of its state: which keys exist and what type each holds. The simplest way is a TypedDict:
Nodes return partial updates: only the keys they change. LangGraph merges the update into the state before the next node runs. By default, a new value replaces the old one.
Parallel branches and reducers
Sometimes replacing is wrong. Here two searches run at the same time, and both add notes:
import operator
from typing import Annotated, TypedDict
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
topic: str
notes: Annotated[list[str], operator.add] # a reducer: updates are added to the list
def search_web(state: State) -> dict:
return {"notes": [f"web: 3 articles on {state['topic']}"]}
def search_docs(state: State) -> dict:
return {"notes": [f"docs: 2 internal pages on {state['topic']}"]}
def summarise(state: State) -> dict:
return {"notes": [f"summary: combined {len(state['notes'])} notes"]}
builder = StateGraph(State)
builder.add_node("search_web", search_web)
builder.add_node("search_docs", search_docs)
builder.add_node("summarise", summarise)
builder.add_edge(START, "search_web") # two edges from START:
builder.add_edge(START, "search_docs") # both searches run in parallel
builder.add_edge(["search_web", "search_docs"], "summarise") # wait for both, then summarise
builder.add_edge("summarise", END)
graph = builder.compile()
result = graph.invoke({"topic": "e-bike batteries", "notes": []})
for note in result["notes"]:
print(note)docs: 2 internal pages on e-bike batteries web: 3 articles on e-bike batteries summary: combined 2 notes
Three things to notice:
- Two edges from
STARTmake both searches run in the same step, in parallel. add_edge(["search_web", "search_docs"], "summarise")makessummarisewait until both have finished.Annotated[list[str], operator.add]givesnotesa reducer: each update is added to the list instead of replacing it. Both searches' notes survive, and the summary's note is added after them.
Without a reducer
If two nodes in the same step write to a key that has no reducer, LangGraph can't know which value to keep, so it refuses:
from typing import TypedDict
from langgraph.errors import InvalidUpdateError
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
notes: list[str] # no reducer this time
builder = StateGraph(State)
builder.add_node("a", lambda s: {"notes": ["from a"]})
builder.add_node("b", lambda s: {"notes": ["from b"]})
builder.add_edge(START, "a")
builder.add_edge(START, "b")
builder.add_edge(["a", "b"], END)
try:
builder.compile().invoke({"notes": []})
except InvalidUpdateError as e:
print("InvalidUpdateError:", str(e).splitlines()[0])InvalidUpdateError: At key 'notes': Can receive only one value per step. Use an Annotated key to handle multiple values.
That error is a feature: silently keeping one of two parallel results would lose data. Here's the rule in plain Python:
import operator
# How a graph applies the updates of nodes that ran in the same step:
# keys with a reducer combine the values; keys without one may only get one value per step.
REDUCERS = {"notes": operator.add} # like Annotated[list[str], operator.add]
def apply_step(state, updates):
new = dict(state)
written = {}
for node, update in updates: # updates from every node that ran in this step
for key, value in update.items():
if key in REDUCERS:
new[key] = REDUCERS[key](new[key], value)
elif key in written:
raise ValueError(f"'{key}' got values from {written[key]} and {node} in one step")
else:
new[key] = value
written[key] = node
return new
state = {"topic": "e-bike batteries", "notes": [], "status": "new"}
state = apply_step(state, [("search_web", {"notes": ["web: 3 articles"]}),
("search_docs", {"notes": ["docs: 2 pages"], "status": "searched"})])
print(state)
try:
apply_step(state, [("a", {"status": "done"}), ("b", {"status": "failed"})])
except ValueError as e:
print("Error:", e)Conversations: MessagesState
Chat-based graphs keep a list of messages. LangGraph's ready-made MessagesState has one key, messages, with the add_messages reducer: new messages are appended, ("user", "...") tuples are converted to message objects, and a message with the same ID as an existing one replaces it.
from langgraph.graph import END, START, MessagesState, StateGraph
def greet(state: MessagesState) -> dict:
name = state["messages"][-1].content.split()[-1]
return {"messages": [("ai", f"Hello {name}! How can I help with your bike?")]}
builder = StateGraph(MessagesState) # a ready-made state: {"messages": [...]} with add_messages
builder.add_node("greet", greet)
builder.add_edge(START, "greet")
builder.add_edge("greet", END)
graph = builder.compile()
result = graph.invoke({"messages": [("user", "Hi, I'm Mei")]})
for m in result["messages"]:
print(f"{type(m).__name__}: {m.content}")HumanMessage: Hi, I'm Mei AIMessage: Hello Mei! How can I help with your bike?
You can extend it with your own keys: class State(MessagesState): user_id: str; attempts: int.
Common mistakes
Apply node updates to graph state with reducers, the rule LangGraph uses for keys declared with Annotated.
state = {"messages": ["hi"], "count": 1, "status": "new"}
updates = [{"messages": ["hello!"], "count": 1}, {"messages": ["how can I help?"], "status": "open"}]
reducers = {"messages": lambda old, new: old + new, "count": lambda old, new: old + new}
# Apply each update in order: for a key with a reducer, combine the old and new values with it;
# otherwise just replace the value. Then print the final state.
Two nodes run in the same step and both return a value for notes. When does this work?
Summary
- A state schema (often a
TypedDict) defines the shared state's keys and types. - Nodes return partial updates; by default updates replace values.
- Several edges from one node run branches in parallel;
add_edge([a, b], c)joins them. - Reducers (
Annotated[..., operator.add]) combine updates; without one, parallel writes raise InvalidUpdateError. MessagesStateandadd_messageshandle conversations.
Next: conditional edges.
Finished reading? Tick it off to track your progress.