Reducers
Combining updates.
When a node returns a key, the new value replaces the old one. That's fine for a total. But for a log, or a list of messages, we want to add to it, not replace it. A reducer decides how updates combine.

- Default: replace
- Logs need adding
- A reducer decides
Replace vs append
Notes is a plain list, so each update replaces it. Log is annotated with operator add, a reducer, so each update is appended. Both nodes write to both keys. Run it. Notes only has the last value. Log has both entries.
import operator
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
notes: list[str]
log: Annotated[list[str], operator.add]
def first(s): return {"notes": ["from first"], "log": ["first ran"]}
def second(s): return {"notes": ["from second"], "log": ["second ran"]}
b = StateGraph(State)
b.add_sequence([first, second])
b.add_edge(START, "first"); b.add_edge("second", END)
print(b.compile().invoke({"notes": [], "log": []})){'notes': ['from second'], 'log': ['first ran', 'second ran']}How reducers work
A reducer is a function that takes the old value and the update, and returns the new value. Annotated attaches it to a key. Operator add joins lists, and adds numbers. Keys without a reducer simply replace.
| key | value |
|---|---|
| Reducer | (old, new) → value |
| Annotated | attaches it |
| operator.add | join or sum |
| No reducer | replace |
Summary
Reducers control how updates combine with the state. Annotated with operator add appends instead of replacing. Next, more ways to use operator add.
Key takeaways- Annotated[...]
- operator.add
- Default replaces