Skip to content

LangGraph State Reducers Detailed interpretation 🎯 ​

📚 Overview ​

This document explains in detail State Reducers in LangGraph. This is the core mechanism of LangGraph state management and is used to control how state is updated. Through Reducers, we can elegantly handle complex scenarios such as status conflicts of parallel nodes, message appending, and custom aggregation.

Core Value:

  • Solve the problem of status conflict of parallel nodes
  • Provide flexible status update strategy
  • Supports adding, modifying and deleting messages
  • Allow custom status aggregation logic

🎯 Core Concept ​

What is a State Reducer? ​

Reducer is a function that defines how new values ​​are merged into existing state.

Analogy understanding:

想象你有一个购物车(状态)
- 默认方式:每次都替换整个购物车(覆盖)
- Reducer 方式:可以选择"追加商品"、"删除商品"、"合并购物车"等策略

Applications in LangGraph:

  • When multiple nodes update the same status field at the same time, the Reducer decides how to handle these updates
  • Avoid state conflicts and data loss
  • Provide consistent status update behavior

⚠️ Problem scenario: Default override behavior ​

Scenario 1: Single node update (no problem) ​

python
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    foo: int

def node_1(state):
    print("---Node 1---")
    return {"foo": state['foo'] + 1}

# 构建图
builder = StateGraph(State)
builder.add_node("node_1", node_1)
builder.add_edge(START, "node_1")
builder.add_edge("node_1", END)

graph = builder.compile()

# 执行
result = graph.invoke({"foo": 1})
# 输出: {'foo': 2}

Description:

  • By default, the status returned by the node will overwrite the original status
  • {"foo": 1} → node_1 → {"foo": 2}
  • No problem when updating single node

Scenario 2: Parallel node conflict (problem!) ❌ ​

python
class State(TypedDict):
    foo: int

def node_1(state):
    print("---Node 1---")
    return {"foo": state['foo'] + 1}

def node_2(state):
    print("---Node 2---")
    return {"foo": state['foo'] + 1}

def node_3(state):
    print("---Node 3---")
    return {"foo": state['foo'] + 1}

# 构建图
builder = StateGraph(State)
builder.add_node("node_1", node_1)
builder.add_node("node_2", node_2)
builder.add_node("node_3", node_3)

# 关键:node_1 分支到 node_2 和 node_3(并行执行)
builder.add_edge(START, "node_1")
builder.add_edge("node_1", "node_2")
builder.add_edge("node_1", "node_3")
builder.add_edge("node_2", END)
builder.add_edge("node_3", END)

graph = builder.compile()

# 执行会报错!
from langgraph.errors import InvalidUpdateError
try:
    graph.invoke({"foo": 1})
except InvalidUpdateError as e:
    print(f"InvalidUpdateError occurred: {e}")

Execution process:

输入: {"foo": 1}
  ↓
node_1: {"foo": 2}
  ↓
┌─────────┴─────────┐
node_2      node_3
{"foo": 3}  {"foo": 3}
  ↓           ↓
  └─────────┬─────────┘
          ❌ 冲突!

Problem Analysis:

  1. After node_1 is executed, foo = 2
  2. node_2 and node_3 Parallel execution (in the same step)
  3. Both nodes try to overwrite foo to 3
  4. LangGraph doesn’t know which value should be retained → InvalidUpdateError

✅ Solution: Use Reducer ​

Option 1: Use operator.add Reducer ​

python
from operator import add
from typing import Annotated

class State(TypedDict):
    foo: Annotated[list[int], add]  # ⭐ 关键:使用 Annotated + add

def node_1(state):
    print("---Node 1---")
    return {"foo": [state['foo'][-1] + 1]}

def node_2(state):
    print("---Node 2---")
    return {"foo": [state['foo'][-1] + 1]}

def node_3(state):
    print("---Node 3---")
    return {"foo": [state['foo'][-1] + 1]}

# 构建图(同样的并行结构)
builder = StateGraph(State)
builder.add_node("node_1", node_1)
builder.add_node("node_2", node_2)
builder.add_node("node_3", node_3)

builder.add_edge(START, "node_1")
builder.add_edge("node_1", "node_2")
builder.add_edge("node_1", "node_3")
builder.add_edge("node_2", END)
builder.add_edge("node_3", END)

graph = builder.compile()

# 执行成功!
result = graph.invoke({"foo": [1]})
# 输出: {'foo': [1, 2, 3, 3]}

Execution process:

输入: {"foo": [1]}
  ↓
node_1: {"foo": [1, 2]}  (追加 2)
  ↓
┌──────────┴──────────┐
node_2         node_3
追加 3         追加 3
  ↓              ↓
  └──────────┬──────────┘
         合并
  {"foo": [1, 2, 3, 3]}  ✅ 成功!

Key Points:

  • Annotated[list[int], add] specifies the use of operator.add as Reducer
  • operator.add performs a splice operation on a list: [1, 2] + [3] = [1, 2, 3]
  • The return value of the parallel node will be appended instead of overwritten
  • The final state contains updates for all nodes

🔬 Deep understanding of Annotated and Reducer ​

Python knowledge points: Annotated type ​

python
from typing import Annotated

# 基本用法
Annotated[类型, 元数据1, 元数据2, ...]

# 在 LangGraph 中
Annotated[list[int], add]
#         ^^^^^^^^^  ^^^
#         类型定义   Reducer 函数

The role of Annotated:

  1. Type hint: list[int] tells the IDE and type checker that this is a list of integers
  2. Metadata: add is additional metadata that LangGraph uses to determine the state update strategy
  3. Does not affect runtime type: The Python runtime still thinks it is list[int]

Python knowledge points: operator.add ​

python
import operator

# 对数字:执行加法
operator.add(1, 2)  # → 3

# 对字符串:执行拼接
operator.add("hello", " world")  # → "hello world"

# 对列表:执行列表拼接
operator.add([1, 2], [3, 4])  # → [1, 2, 3, 4]

# 在 LangGraph 中
# 旧状态: [1, 2]
# 新更新: [3]
# 结果: operator.add([1, 2], [3]) → [1, 2, 3]

**Why choose operator.add? **

  • It is a built-in module of Python with good performance
  • Clear semantics: "add" new value to old value
  • Intuitive operations on lists (splicing)

🛠️ Custom Reducer ​

Problem: operator.add cannot handle None ​

python
from operator import add

class State(TypedDict):
    foo: Annotated[list[int], add]

def node_1(state):
    return {"foo": [2]}

graph = ...  # 构建图

# 传入 None 会报错
try:
    graph.invoke({"foo": None})
except TypeError as e:
    print(f"TypeError occurred: {e}")
    # TypeError: unsupported operand type(s) for +: 'NoneType' and 'list'

Reason:

  • operator.add(None, [2]) cannot be executed
  • None + list is an illegal operation

Solution: Custom Reducer function ​

python
def reduce_list(left: list | None, right: list | None) -> list:
    """
    安全地合并两个列表,处理 None 的情况

    Args:
        left: 旧状态(可能是 None)
        right: 新更新(可能是 None)

    Returns:
        合并后的列表
    """
    if not left:
        left = []
    if not right:
        right = []
    return left + right

# 使用自定义 Reducer
class CustomReducerState(TypedDict):
    foo: Annotated[list[int], reduce_list]  # ⭐ 使用自定义函数

def node_1(state):
    print("---Node 1---")
    return {"foo": [2]}

# 构建图
builder = StateGraph(CustomReducerState)
builder.add_node("node_1", node_1)
builder.add_edge(START, "node_1")
builder.add_edge("node_1", END)

graph = builder.compile()

# 现在可以处理 None 了!
result = graph.invoke({"foo": None})
# 输出: {'foo': [2]}

Advantages of custom Reducer:

  • Can implement arbitrarily complex merge logic
  • Handle edge cases (such as None, null values)
  • More in line with business needs

Custom Reducer Example ​

Example 1: Keep only unique values ​

python
def unique_reducer(left: list | None, right: list | None) -> list:
    """合并列表并去重"""
    if not left:
        left = []
    if not right:
        right = []
    return list(set(left + right))

class State(TypedDict):
    tags: Annotated[list[str], unique_reducer]

# 使用
# 旧状态: {"tags": ["python", "ai"]}
# 新更新: {"tags": ["python", "langchain"]}
# 结果: {"tags": ["python", "ai", "langchain"]}  # 自动去重

Example 2: Keep the latest N values ​

python
def keep_last_n(n: int):
    """工厂函数:创建一个只保留最新 n 个值的 Reducer"""
    def reducer(left: list | None, right: list | None) -> list:
        if not left:
            left = []
        if not right:
            right = []
        combined = left + right
        return combined[-n:]  # 只保留最后 n 个
    return reducer

class State(TypedDict):
    history: Annotated[list[str], keep_last_n(5)]  # 只保留最新 5 个

# 使用
# 旧状态: {"history": ["a", "b", "c", "d", "e"]}
# 新更新: {"history": ["f", "g"]}
# 结果: {"history": ["c", "d", "e", "f", "g"]}  # 只保留最新 5 个

Example 3: Merging dictionaries ​

python
def merge_dict_reducer(left: dict | None, right: dict | None) -> dict:
    """深度合并两个字典"""
    if not left:
        left = {}
    if not right:
        right = {}
    return {**left, **right}

class State(TypedDict):
    config: Annotated[dict, merge_dict_reducer]

# 使用
# 旧状态: {"config": {"a": 1, "b": 2}}
# 新更新: {"config": {"b": 3, "c": 4}}
# 结果: {"config": {"a": 1, "b": 3, "c": 4}}  # b 被覆盖,c 被添加

💬 Messages Reducer: Process conversation messages ​

Built-in add_messages Reducer ​

LangGraph provides a Reducer specifically used to process messages: add_messages

Two ways to use:

Method 1: Manual definition ​

python
from typing import Annotated
from langchain_core.messages import AnyMessage
from langgraph.graph.message import add_messages

class CustomMessagesState(TypedDict):
    messages: Annotated[list[AnyMessage], add_messages]
    user_name: str
    session_id: str
python
from langgraph.graph import MessagesState

# MessagesState 已经内置了 messages 字段和 add_messages reducer
class ExtendedMessagesState(MessagesState):
    # 只需要添加额外的字段
    user_name: str
    session_id: str

Advantages of MessagesState:

  • Automatically include messages: Annotated[list[AnyMessage], add_messages]
  • Reduce boilerplate code
  • Clearer expression of intent

Basic usage of add_messages ​

python
from langgraph.graph.message import add_messages
from langchain_core.messages import AIMessage, HumanMessage

# 初始状态
initial_messages = [
    AIMessage(content="Hello! How can I assist you?", name="Model"),
    HumanMessage(content="I'm looking for information on marine biology.", name="Lance")
]

# 新消息
new_message = AIMessage(
    content="Sure, I can help with that. What specifically are you interested in?",
    name="Model"
)

# 追加消息
result = add_messages(initial_messages, new_message)

# 结果
# [
#     AIMessage(content="Hello! How can I assist you?", name="Model"),
#     HumanMessage(content="I'm looking for information on marine biology.", name="Lance"),
#     AIMessage(content="Sure, I can help with that...", name="Model")  # ✅ 追加成功
# ]

Advanced function 1: Message rewriting (Re-writing) ​

Core mechanism: If the id of the new message is the same as the existing message, the old message will be overwritten

python
# 初始状态
initial_messages = [
    AIMessage(content="Hello! How can I assist you?", name="Model", id="1"),
    HumanMessage(content="I'm looking for information on marine biology.", name="Lance", id="2")
]

# 新消息(注意 id="2" 与第二条消息相同)
new_message = HumanMessage(
    content="I'm looking for information on whales, specifically",
    name="Lance",
    id="2"  # ⭐ 相同的 ID
)

# 重写消息
result = add_messages(initial_messages, new_message)

# 结果
# [
#     AIMessage(content="Hello! How can I assist you?", name="Model", id="1"),
#     HumanMessage(content="I'm looking for information on whales, specifically", name="Lance", id="2")
#     # ✅ 第二条消息被重写
# ]

Application scenario:

  • Fix user input
  • Updated AI responses
  • Implement message editing function

Advanced function 2: Message deletion (Removal) ​

Use RemoveMessage:

python
from langchain_core.messages import RemoveMessage, AIMessage, HumanMessage

# 消息列表
messages = [
    AIMessage("Hi.", name="Bot", id="1"),
    HumanMessage("Hi.", name="Lance", id="2"),
    AIMessage("So you said you were researching ocean mammals?", name="Bot", id="3"),
    HumanMessage("Yes, I know about whales. But what others should I learn about?", name="Lance", id="4")
]

# 创建删除指令(删除前两条消息)
delete_messages = [RemoveMessage(id=m.id) for m in messages[:-2]]
# [RemoveMessage(id="1"), RemoveMessage(id="2")]

# 执行删除
result = add_messages(messages, delete_messages)

# 结果
# [
#     AIMessage("So you said you were researching ocean mammals?", name="Bot", id="3"),
#     HumanMessage("Yes, I know about whales...", name="Lance", id="4")
# ]
# ✅ id="1" 和 id="2" 的消息被删除

Application scenario:

  • Implement sliding window (only keep the latest N messages)
  • Delete sensitive information
  • Clear irrelevant conversation history
  • Optimize context length (reduce Token consumption)

Practical case: Sliding window dialogue ​

python
from langgraph.graph import MessagesState, StateGraph, START, END
from langchain_core.messages import RemoveMessage, HumanMessage, AIMessage

class ConversationState(MessagesState):
    max_messages: int = 10  # 最多保留 10 条消息

def chat_node(state: ConversationState):
    # 模拟 AI 响应
    response = AIMessage(content="I understand your question.", name="Bot")
    return {"messages": [response]}

def cleanup_node(state: ConversationState):
    """清理旧消息,只保留最新的 max_messages 条"""
    messages = state["messages"]
    max_msgs = state.get("max_messages", 10)

    if len(messages) > max_msgs:
        # 计算需要删除的消息数量
        num_to_delete = len(messages) - max_msgs
        # 创建删除指令
        delete_messages = [RemoveMessage(id=m.id) for m in messages[:num_to_delete]]
        return {"messages": delete_messages}

    return {}

# 构建图
builder = StateGraph(ConversationState)
builder.add_node("chat", chat_node)
builder.add_node("cleanup", cleanup_node)

builder.add_edge(START, "chat")
builder.add_edge("chat", "cleanup")
builder.add_edge("cleanup", END)

graph = builder.compile()

# 使用
initial_state = {
    "messages": [HumanMessage(content="Hello", id=str(i)) for i in range(12)],
    "max_messages": 10
}

result = graph.invoke(initial_state)
# 结果只保留最新 10 条消息

🎓 Summary of core knowledge points ​

LangGraph-specific concepts ​

1. Reducer mechanism ​

FeaturesDescription
FunctionDefine status update strategy
Trigger timingWhen multiple nodes update the same field
Default BehaviorOverride (can cause parallel conflicts)
Reducer behaviorCustom merge logic (such as appending, deduplication)

2. Built-in Reducer ​

ReducerPurposeExample
operator.addSplicing list/string[1, 2] + [3] = [1, 2, 3]
add_messagesAdd/modify/delete messagesConversation history management

3. MessagesState ​

python
# 手动方式
class State(TypedDict):
    messages: Annotated[list[AnyMessage], add_messages]

# 快捷方式(推荐)
class State(MessagesState):
    pass  # 自动包含 messages 字段

Python-specific knowledge points ​

1. Annotated type ​

python
from typing import Annotated

Annotated[基础类型, 元数据1, 元数据2, ...]

# 在 LangGraph 中
Annotated[list[int], add]
#         ^^^^^^^^^  ^^^
#         类型       Reducer

Function:

  • Provide type hints (IDE support)
  • Additional metadata (LangGraph used to determine Reducer)
  • Does not affect runtime behavior

2. TypedDict vs Pydantic BaseModel ​

PropertiesTypedDictBaseModel
Runtime Verification❌✅
Type Tips✅✅
PerformanceFasterSlightly slower
PurposeState DefinitionData Model, API Output

3. operator module ​

python
import operator

operator.add(a, b)      # a + b
operator.sub(a, b)      # a - b
operator.mul(a, b)      # a * b
operator.truediv(a, b)  # a / b

Application in LangGraph:

  • operator.add for list splicing
  • is a built-in Python module, no installation required

4. Union in type hints ​

python
from typing import Union

# Python 3.10+ 可以使用 | 语法
def reduce_list(left: list | None, right: list | None) -> list:
    ...

# 等价于(旧语法)
def reduce_list(left: Union[list, None], right: Union[list, None]) -> list:
    ...

💡 Best Practices ​

1. When to use Reducer? ​

✅ Required scenarios:

  • There are parallel nodes in the graph
  • Multiple nodes may update the same status field
  • Need to append rather than overwrite (such as message history)
  • Requires custom aggregation logic (such as deduplication, summation)

❌ Unnecessary scenarios:

  • Fully serial graph (no parallel nodes)
  • Each field is updated by only one node
  • Overrides behave as expected

2. Reducer design principles ​

Principle 1: Clear semantics ​

python
# ✅ 好的设计 - 语义清晰
class State(TypedDict):
    message_history: Annotated[list, add_messages]  # 消息历史:追加
    calculation_results: Annotated[list, operator.add]  # 计算结果:拼接
    user_count: Annotated[int, max]  # 用户数:取最大值

# ❌ 不好的设计 - 语义不明
class State(TypedDict):
    data: Annotated[list, add]  # data 是什么?为什么追加?

Principle 2: Handle edge cases ​

python
# ✅ 好的设计 - 处理 None
def safe_reducer(left: list | None, right: list | None) -> list:
    if not left:
        left = []
    if not right:
        right = []
    return left + right

# ❌ 不好的设计 - 可能崩溃
def unsafe_reducer(left: list, right: list) -> list:
    return left + right  # 如果传入 None 会报错

Principle 3: Maintain idempotence (if possible) ​

python
# ✅ 幂等的 Reducer
def unique_add(left: list, right: list) -> list:
    """多次添加相同元素只保留一个"""
    return list(set(left + right))

# 应用:即使重复执行,结果一致
state = ["a", "b"]
state = unique_add(state, ["b", "c"])  # ["a", "b", "c"]
state = unique_add(state, ["b", "c"])  # ["a", "b", "c"] - 相同结果

3. Message management best practices ​

Practice 1: Clean up messages regularly ​

python
def should_cleanup(state: MessagesState) -> bool:
    """每 10 条消息清理一次"""
    return len(state["messages"]) % 10 == 0

builder.add_conditional_edges(
    "chat",
    should_cleanup,
    {True: "cleanup", False: END}
)

Practice 2: Keep system messages ​

python
from langchain_core.messages import SystemMessage

def cleanup_node(state):
    messages = state["messages"]
    # 保留系统消息和最新 5 条对话
    system_messages = [m for m in messages if isinstance(m, SystemMessage)]
    recent_messages = [m for m in messages if not isinstance(m, SystemMessage)][-5:]

    # 删除其他消息
    to_delete = [m for m in messages if m not in system_messages + recent_messages]
    delete_ops = [RemoveMessage(id=m.id) for m in to_delete]

    return {"messages": delete_ops}

Practice 3: Implement message editing ​

python
def edit_message_node(state):
    """允许用户编辑最后一条消息"""
    last_message = state["messages"][-1]

    # 创建新消息,使用相同的 ID
    edited_message = HumanMessage(
        content=state["edited_content"],
        id=last_message.id,  # ⭐ 相同 ID = 覆盖
        name=last_message.name
    )

    return {"messages": [edited_message]}

4. Performance optimization techniques ​

Tip 1: Avoid overly large lists ​

python
# ❌ 不好 - 列表无限增长
class State(TypedDict):
    all_results: Annotated[list, operator.add]

# ✅ 好 - 限制大小
def limited_add(max_size: int):
    def reducer(left: list | None, right: list | None) -> list:
        if not left:
            left = []
        if not right:
            right = []
        combined = left + right
        return combined[-max_size:]  # 只保留最新的
    return reducer

class State(TypedDict):
    recent_results: Annotated[list, limited_add(100)]

Tip 2: Use efficient data structures ​

python
# 如果需要频繁查找
def set_reducer(left: set | None, right: set | None) -> set:
    """使用集合实现 O(1) 查找"""
    if not left:
        left = set()
    if not right:
        right = set()
    return left | right  # 集合并集

class State(TypedDict):
    unique_ids: Annotated[set, set_reducer]

🚀 Advanced skills ​

1. Conditional Reducer ​

Dynamically select reducers based on status:

python
def smart_reducer(left: list, right: list, state: dict) -> list:
    """根据状态选择合并策略"""
    if state.get("mode") == "append":
        return left + right
    elif state.get("mode") == "unique":
        return list(set(left + right))
    elif state.get("mode") == "override":
        return right
    else:
        return left + right

2. Combine multiple Reducers ​

python
def compose_reducers(*reducers):
    """组合多个 Reducer"""
    def combined(left, right):
        result = left
        for reducer in reducers:
            result = reducer(result, right)
        return result
    return combined

# 使用
validate_and_add = compose_reducers(
    validate_list,    # 先验证
    deduplicate,      # 再去重
    operator.add      # 最后追加
)

3. Reducer with log ​

python
def logged_reducer(reducer_func, name: str):
    """为 Reducer 添加日志"""
    def wrapper(left, right):
        print(f"[{name}] Merging: {left} + {right}")
        result = reducer_func(left, right)
        print(f"[{name}] Result: {result}")
        return result
    return wrapper

# 使用
class State(TypedDict):
    data: Annotated[list, logged_reducer(operator.add, "DataReducer")]

📊 Reducer mode comparison ​

PatternImplementationApplicable scenariosExamples
OverridesDefault BehaviorSingle Node UpdatesConfiguration Overrides
Addoperator.addCollection resultsLog collection
Remove duplicates and appendCustomizationUniqueness constraintsTag collection
Message Managementadd_messagesConversation HistoryChatbot
Numerical aggregationmax/min/sumStatistical calculationsPerformance indicators

🎯 Practical application cases ​

Case 1: Parallel API call result collection ​

python
from typing import Annotated
from operator import add

class State(TypedDict):
    query: str
    api_results: Annotated[list[dict], add]

def call_api_1(state):
    result = {"source": "API1", "data": "..."}
    return {"api_results": [result]}

def call_api_2(state):
    result = {"source": "API2", "data": "..."}
    return {"api_results": [result]}

# 两个 API 并行调用,结果自动合并
# 最终: {"api_results": [{"source": "API1", ...}, {"source": "API2", ...}]}

Case 2: Chatbot status management ​

python
from langgraph.graph import MessagesState

class ChatState(MessagesState):
    user_id: str
    session_id: str
    context: dict

def chat_node(state: ChatState):
    # 生成响应
    response = generate_response(state["messages"][-1])
    return {"messages": [response]}

def memory_cleanup_node(state: ChatState):
    # 只保留最近 20 条消息
    messages = state["messages"]
    if len(messages) > 20:
        to_delete = messages[:-20]
        return {"messages": [RemoveMessage(id=m.id) for m in to_delete]}
    return {}

Case 3: Aggregation of document analysis results ​

python
class AnalysisState(TypedDict):
    document: str
    insights: Annotated[list[str], operator.add]
    metrics: Annotated[dict, merge_dict]

def technical_analysis(state):
    insight = "Technical complexity: High"
    metrics = {"lines_of_code": 1000}
    return {"insights": [insight], "metrics": metrics}

def business_analysis(state):
    insight = "Business value: Medium"
    metrics = {"estimated_revenue": 50000}
    return {"insights": [insight], "metrics": metrics}

# 并行分析,结果自动合并
# insights: ["Technical complexity: High", "Business value: Medium"]
# metrics: {"lines_of_code": 1000, "estimated_revenue": 50000}

🔍 Frequently Asked Questions ​

Q1: What is the difference between Reducer and ordinary functions? ​

Reducer:

  • Specifically used for state merging
  • Accepts two parameters: old state and new update
  • Return to the merged state
  • Automatically called by LangGraph

Normal functions:

  • can do anything
  • Parameters and return values are arbitrary
  • Needs to be called manually

Q2: Why must parallel nodes use Reducer? ​

Because parallel nodes execute in the same step, their updates happen simultaneously. Without Reducer:

node_2 更新: {"foo": 3}
node_3 更新: {"foo": 3}

问题:应该保留哪个?

Reducer provides a clear merge strategy to avoid conflicts.

Q3: How does add_messages know which messages should be overwritten? ​

Via the id field of the message:

python
# 如果新消息的 id 与现有消息相同,就覆盖
new_msg = HumanMessage(content="Updated", id="123")
old_msgs = [HumanMessage(content="Original", id="123")]

result = add_messages(old_msgs, new_msg)
# 结果: [HumanMessage(content="Updated", id="123")]

Q4: Can I use different Reducers for different fields? ​

Can! Each field can have its own Reducer:

python
class State(TypedDict):
    messages: Annotated[list, add_messages]      # 消息:追加
    scores: Annotated[list, operator.add]        # 分数:拼接
    max_score: Annotated[int, max]               # 最高分:取最大值
    flags: Annotated[set, set_union]             # 标志:集合并集

Q5: Will Reducer affect performance? ​

There will be a slight effect, but it can usually be ignored:

  • operator.add: very fast (built in Python)
  • add_messages: Need to check ID, slightly slower but still efficient
  • Custom Reducer: depends on implementation complexity

Optimization suggestions:

  • Avoid complex calculations in Reducer
  • Use efficient data structures (such as sets instead of lists)
  • Limit state size (e.g. keep only the latest N items)

📖 Further reading ​


🎉 Summary ​

State Reducers are the core mechanism of LangGraph state management, which solves the following key issues:

  1. Parallel Node Conflict - Avoid state conflicts by defining merge strategies
  2. Flexible status update - supports multiple modes such as append, overwrite, and deduplication.
  3. Message Management - The built-in add_messages provides append, modify, and delete functions
  4. Custom Logic - can implement any complex state aggregation logic

Key Takeaways:

  • Define a reducer with Annotated[type, reducer_function]
  • operator.add for list/string concatenation
  • add_messages for message history management
  • Customize Reducer to handle special needs
  • Must handle edge cases such as None

Mastering State Reducers is the foundation for building complex LangGraph applications, making state management elegant and powerful!

English translation of community learning materials. MIT licensed.