Module 1 · Thinking in graphs
Typed state schema and reducers
6 min read
State is the heart of a LangGraph graph. It flows between nodes, it is saved at every step, it is what you inspect to debug and modify to correct an execution. A well-designed state makes the graph simple; a badly designed one makes every node complicated. This lesson covers schema declaration, the reducers that define how updates are combined, and the design rules we apply in Relay.
Declaring the schema
The state schema is most often declared with a TypedDict:
from typing import Literal, TypedDict
class SupportState(TypedDict, total=False):
intent: Literal["question", "order_status", "refund", "other"]
order_id: str | None
language: Literal["fr", "en"]
agent_turns: int
total=False makes every key optional: a node doesn't have to provide all keys, and the initial state can be partial. It is the most practical choice for a state that fills up during execution; in return, use state.get("key", default) for keys that may be missing.
Two alternatives exist:
| Schema | Runtime validation | When to use it |
|---|---|---|
TypedDict | None | The default: light, fast, serializable |
dataclass | None | If you want default values and attribute access |
Pydantic BaseModel | Yes, at node input | If the state comes from untrusted sources and must be validated |
In Relay we use TypedDicts and reserve Pydantic for model outputs (lesson 2.1), which are the system's real untrusted boundary.
Reducers: how updates are combined
By default, a state key follows the "last write wins" rule: if a node returns {"intent": "refund"}, the previous value is replaced. For many keys, that is not the desired behavior. A message history must grow, an audit log must accumulate its lines.
A reducer is a function (old_value, update) -> new_value attached to a key with Annotated:
import operator
from typing import Annotated
class State(TypedDict, total=False):
audit: Annotated[list[str], operator.add] # lists are concatenated
A node returning {"audit": ["triage → refund"]} appends that line to the log instead of replacing it. That is why Relay's nodes always return a one-element list for audit.
Reducers have a second, essential role: they make parallel writes possible. If two nodes in the same step write the same key without a reducer, LangGraph refuses to choose:
InvalidUpdateError: At key 'x': Can receive only one value per step.
Use an Annotated key to handle multiple values.
With a reducer, both writes are combined deterministically. We will need this for the map-reduce in lesson 2.3.
You can write your own reducers. For example, to keep a maximum:
def keep_max(current: int | None, update: int) -> int:
return update if current is None else max(current, update)
class State(TypedDict, total=False):
max_score: Annotated[int, keep_max]
To exceptionally replace a value managed by a reducer (clearing a log, for instance), return it wrapped in Overwrite: {"audit": Overwrite([])} bypasses the reducer for that update.
add_messages: the conversation reducer
Conversation history is so common that LangGraph provides a dedicated reducer, add_messages:
from langchain_core.messages import AnyMessage
from langgraph.graph.message import add_messages
class State(TypedDict, total=False):
messages: Annotated[list[AnyMessage], add_messages]
It does more than plain concatenation:
- it appends new messages at the end;
- it replaces an existing message when it receives a message with the same id — handy to correct a message already emitted;
- it removes a message when sent a
RemoveMessage(id=...)— the basis of any context-pruning strategy; - it converts short formats:
("user", "Hello")or{"role": "user", "content": "Hello"}becomeHumanMessages.
LangGraph also provides MessagesState, a ready-made schema containing only that messages key. You can inherit from it to add your own fields.
Relay's state
Here is the running project's main schema:
class SupportState(TypedDict, total=False):
messages: Annotated[list[AnyMessage], add_messages]
intent: Intent
order_id: str | None
language: Literal["fr", "en"]
status: Status
agent_turns: int
refund: dict | None
audit: Annotated[list[str], operator.add]
Each key has a precise reason to exist:
| Key | Written by | Read by | Reducer |
|---|---|---|---|
messages | agent, tools, handoff, subgraph | agent, triage | add_messages |
intent | triage | the route_intent router | last write |
order_id | triage | refund | last write |
agent_turns | load_profile (reset to 0), agent (+1) | route_after_agent | last write |
audit | almost every node | humans, tests | operator.add |
The run context: what doesn't belong in the state
Not everything nodes need belongs in the state. The customer id, the channel (chat or email), a database connection: this information is fixed for the whole run and shouldn't be saved in every checkpoint. LangGraph passes it through a typed context:
from dataclasses import dataclass
from langgraph.runtime import Runtime
@dataclass
class Context:
customer_id: str
channel: Literal["chat", "email"] = "chat"
async def load_profile(state: SupportState, runtime: Runtime[Context]) -> dict:
customer_id = runtime.context.customer_id
...
builder = StateGraph(SupportState, context_schema=Context)
graph.invoke(inputs, config, context=Context(customer_id="cus_lea"))
The context has a decisive security advantage: the model cannot change it. The customer id comes from your authentication system, not from a field the LLM could fill in. That is what lets Relay's lookup_order tool refuse access to another customer's orders.
Design rules
- Persist data, not objects. The state is serialized at every checkpoint: no connections, API clients or functions in it.
- One key, one owner. Ideally, only one family of nodes writes each key. If everyone writes everywhere, nobody knows where a value comes from.
- No derived values. If a value can be computed from others (a total, a message count), compute it when needed rather than storing it.
- A reducer for any key written in parallel or meant to accumulate.
- Keep the state small. It is saved at every step: whole documents in the state mean a checkpoint database that grows very fast. Store large content elsewhere and keep a reference.
Key takeaways
TypedDictwithtotal=Falseis the default schema; Pydantic is for untrusted data.- Without a reducer, the last write wins; with
Annotated[type, reducer], updates are combined.- Parallel writes to the same key require a reducer, otherwise
InvalidUpdateError.add_messagesappends, replaces by id, removes withRemoveMessageand converts short formats.- What is fixed for the run (customer id, channel) goes through the context, which the model cannot change.
Practice
- In
examples/01_first_graph.py, removeoperator.addfrom thelogkey and run it: what doeslogcontain at the end? - Write a
merge_dictsreducer that merges two dictionaries, and use it for ametricskey. - Send a
RemoveMessagefor the first message of a conversation state and check that it disappears.