Custom Reducers
Your own rules.
Sometimes neither replacing nor appending is right. Say two warehouses report stock counts, as dictionaries. We want to add the counts together, book by book. That needs a reducer of our own.

- Not replace, not append
- Merge dictionaries
- Your own reducer
Merging stock counts
Add counts is our reducer. It takes the old dictionary and the new one, and adds the numbers for each title. We attach it with annotated. Two warehouse nodes each report their counts. Run it. The final stock adds both warehouses together, title by title.
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END
def add_counts(old: dict, new: dict) -> dict:
merged = dict(old)
for title, n in new.items():
merged[title] = merged.get(title, 0) + n
return merged
class State(TypedDict):
stock: Annotated[dict, add_counts]
def bath(s): return {"stock": {"Dune": 2, "Emma": 1}}
def bristol(s): return {"stock": {"Dune": 1, "Circe": 4}}
b = StateGraph(State)
b.add_sequence([bath, bristol]); b.add_edge(START, "bath"); b.add_edge("bristol", END)
print(b.compile().invoke({"stock": {}})["stock"]){'Dune': 3, 'Emma': 1, 'Circe': 4}Reducer ideas
Custom reducers can do almost anything. Merge dictionaries. Keep only unique items. Keep the largest value. Or keep only the last ten messages. Keep them small, pure functions, with no side effects.
| key | value |
|---|---|
| Merge | dictionaries |
| Unique | no duplicates |
| Max | keep the largest |
| Window | last N items |
Summary
A custom reducer is any function of the old value and the update. Attach it with annotated. Next, running branches in parallel.
Key takeaways- (old, new) → merged
- Annotated[dict, fn]
- Pure functions