AI Hints
LangGraph · Lesson 19 of 120

Reducers

Combining updates.

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

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.

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

reducers.pypython
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": []}))
Output
{'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.

keyvalue
Reducer(old, new) → value
Annotatedattaches it
operator.addjoin or sum
No reducerreplace

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
Next up: Appending Lists — operator.add