State, nodes & edges
LangGraph describes an application as a graph: a shared state, nodes that update it, and edges that decide what runs next.
Three ideas
The state is a typed dictionary shared by the whole run, defined with TypedDict. A node is a function that reads the state and returns the keys it wants to change. An edge says which node runs next; START and END mark where a run begins and stops. You add nodes and edges to a StateGraph builder, then compile() it into a runnable graph.
Reducers decide how updates merge
By default a returned value overwrites the old one. A reducer, attached with Annotated, merges instead: add_messages appends to the chat history (and updates a message with the same ID), and operator.add concatenates lists. Reducers matter most when several nodes write to the same key, as in parallel branches.
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
class State(TypedDict):
messages: Annotated[list, add_messages] # reducer: append
topic: str # no reducer: overwrite
def classify(state: State) -> dict:
return {"topic": "billing"} # return only what changes
def answer(state: State) -> dict:
return {"messages": [("assistant", "Refunds take 5-7 days.")]}
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()
graph.invoke({"messages": [("user", "How long do refunds take?")]})A worked example
The run starts with one user message. classify returns {"topic": "billing"}: the topic key changes, the messages stay. answer returns one assistant message: because of add_messages, the list now holds both messages instead of only the new one. Had messages no reducer, the user’s question would have been overwritten.
Easy to confuse
- Nodes do not call each other; edges decide the order. That is what makes the flow visible, testable and resumable.
- A node is any Python function. It can call an LLM, a whole agent, a database or nothing at all.
A node returns {"topic": "billing"}. What happens to the state?
A node returns only the updates. LangGraph merges them into the shared state, key by key, using each key’s reducer.
What does the add_messages reducer do?
Without a reducer, a new value overwrites the old one. add_messages appends to the message list (and updates a message that has the same ID).
Why must you call compile() before invoke()?
StateGraph is only a builder. compile() validates nodes and edges and returns the graph you can invoke or stream.
Read more in the books
- LangChain and LangGraph documentation, LangChain: LangGraph: Overview and Graph API.
- Learning LangChain, Mayo Oshin, Nuno Campos: the chapters on LangGraph.