AI Hints
LangGraph · Lesson 21 of 120

Custom Reducers

Your own rules.

⏱ 2 min read▶ Video at 21:49🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

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.

Custom Reducers
From the video: Custom Reducers
  • 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.

custom_reducer.pypython
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"])
Output
{'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.

keyvalue
Mergedictionaries
Uniqueno duplicates
Maxkeep the largest
Windowlast 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
Next up: Parallel Branches — fan out, fan in