Skip to content

Reducers and Messages

Sudhanshu edited this page Nov 11, 2026 · 1 revision

Reducers and Message Channels

The four numerical/list examples compare the default overwrite behavior with additive and custom reducer semantics.

flowchart TD
 IN["Incoming TypedDict / Pydantic state"] --> NODE["Node returns partial dict"]
 NODE --> CHOICE{"Reducer configured for field?"}
 CHOICE -->|No| OVER["Overwrite previous field value"]
 CHOICE -->|operator.add: int| NUM["Numeric accumulation"]
 CHOICE -->|operator.add: list| LIST["List concatenation"]
 CHOICE -->|merge_unique| UNIQ["Ordered unique list merge"]
 CHOICE -->|add_messages| MSG["Append / replace message by ID"]
 OVER --> NEXT["Updated graph state"]
 NUM --> NEXT
 LIST --> NEXT
 UNIQ --> NEXT
 MSG --> NEXT
Loading

Examples

State declaration Node updates Result
counter: int 1, then 2 2
Annotated[int, operator.add] Start 0, add 1 then 2 3
Annotated[list[int], operator.add] Start [], append [1], [2] [1,2]
Annotated[list[int], merge_unique] [1,2], [2,3] [1,2,3]
add_messages Append ai-2, replace ai-2 by ID Last message Absolutely!

MessagesState uses LangGraph's built-in messages reducer. The offline assistant returns a canned answer, while the optional LLM example calls a hosted model.

Design concern: reducers must suit the update semantics; naive concatenation or unordered writes can duplicate information when introducing parallel branches.

Clone this wiki locally