Skip to content

LangGraph Map-Reduce detailed interpretation ​

📚 Overview ​

This document explains in detail the Map-Reduce mode in LangGraph. This is a classic distributed computing pattern used in LangGraph for efficient task decomposition and parallel processing. Through Map-Reduce, we can split complex tasks into multiple subtasks for parallel execution, and then aggregate the results.

🎯 Core Concept ​

What is Map-Reduce? ​

Map-Reduce is a programming model that consists of two phases:

  1. Map (mapping) phase

    • Break down large tasks into smaller sub-tasks
    • Process each sub-task in parallel
    • Each subtask is executed independently without affecting each other
  2. Reduce (reduce) phase

    • Collect the results of all subtasks
    • Aggregate, summarize or filter results
    • produce final output

Classic application scenarios ​

  • Document Processing: Process long documents in segments and then summarize them
  • Data Analysis: Analyze multiple data sources in parallel and aggregate statistical results
  • Content Generation: Generate multiple candidate content and choose the best result
  • Multi-source query: Query multiple APIs in parallel and merge the results

🎭 Practical case: Joke generation system ​

We will build an intelligent joke generation system to demonstrate the complete process of Map-Reduce:

Requirements:

  1. Map stage: Based on a theme (such as "animals"), generate jokes with multiple sub-themes
  2. Reduce phase: Select the best one from all generated jokes

System architecture diagram ​

用户输入主题 "animals"
        ↓
   [generate_topics] 生成子主题: [mammals, reptiles, birds]
        ↓
    (Send API 动态分发)
        ↓
   ┌────────┬────────┬────────┐
   ↓        ↓        ↓        ↓
[joke-1] [joke-2] [joke-3]  (Map 阶段:并行生成)
   ↓        ↓        ↓
   └────────┴────────┴────────┘
             ↓
        [best_joke]  (Reduce 阶段:选择最佳)
             ↓
         返回结果

🔧 Detailed explanation of code implementation ​

1. Define prompt words and models ​

python
from langchain_openai import ChatOpenAI

# 三个关键提示词
subjects_prompt = """Generate a list of 3 sub-topics that are all related to this overall topic: {topic}."""
joke_prompt = """Generate a joke about {subject}"""
best_joke_prompt = """Below are a bunch of jokes about {topic}. Select the best one! Return the ID of the best one, starting 0 as the ID for the first joke. Jokes: \n\n  {jokes}"""

# 初始化 LLM
model = ChatOpenAI(model="gpt-4o", temperature=0)

Description:

  • subjects_prompt: Split topic into 3 subtopics
  • joke_prompt: Generate jokes for a single subtopic
  • best_joke_prompt: Choose the best one from multiple jokes

2. Define state (State) ​

This is the key to Map-Reduce! We need two states:

Global State (OverallState) ​

python
import operator
from typing import Annotated
from typing_extensions import TypedDict
from pydantic import BaseModel

class Subjects(BaseModel):
    subjects: list[str]

class BestJoke(BaseModel):
    id: int

class OverallState(TypedDict):
    topic: str                                  # 用户输入的主题
    subjects: list                               # 生成的子主题列表
    jokes: Annotated[list, operator.add]        # 收集的笑话(支持并行追加)
    best_selected_joke: str                     # 最终选出的最佳笑话

Key Points:

  • jokes uses the operator.add reducer, allowing multiple parallel nodes to write simultaneously
  • This is consistent with the parallelization knowledge learned before

Local state (JokeState) ​

python
class JokeState(TypedDict):
    subject: str  # 单个笑话生成节点只需要知道主题

class Joke(BaseModel):
    joke: str

Python knowledge points: Pydantic BaseModel

BaseModel is the core class of the Pydantic library and is used for:

  • Data validation
  • type checking
  • Structured output
python
# 使用示例
class Joke(BaseModel):
    joke: str

# LLM 会返回符合这个结构的数据
response = model.with_structured_output(Joke).invoke(prompt)
# response.joke 就是字符串类型的笑话内容

3. Map stage: Generate subtopics ​

python
def generate_topics(state: OverallState):
    prompt = subjects_prompt.format(topic=state["topic"])
    response = model.with_structured_output(Subjects).invoke(prompt)
    return {"subjects": response.subjects}

Function: Decompose the user-entered topic (such as "animals") into 3 sub-topics (such as ["mammals", "reptiles", "birds"])


4. Dynamic task distribution: Send API ⭐ ​

This is the core magic of Map-Reduce!

python
from langgraph.types import Send

def continue_to_jokes(state: OverallState):
    # 为每个子主题创建一个 Send 任务
    return [Send("generate_joke", {"subject": s}) for s in state["subjects"]]

Send API detailed explanation:

python
Send("generate_joke", {"subject": s})
#    ^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^
#    目标节点名称      发送的状态数据

Important Features:

  1. Dynamic Parallelization: Automatically create parallel tasks for each element in the list
  2. Status Flexibility: Any status can be sent, no need to match OverallState exactly
  3. Automatic Expansion: Whether there are 3 or 300 subtopics, they can be automatically processed in parallel

**Why is it powerful? **

The traditional method requires knowing how many parallel tasks there are in advance, but Send can dynamically create tasks based on runtime data:

python
# 如果有 3 个主题,Send 会创建 3 个并行任务
subjects = ["mammals", "reptiles", "birds"]
# 相当于:
# - Send("generate_joke", {"subject": "mammals"})
# - Send("generate_joke", {"subject": "reptiles"})
# - Send("generate_joke", {"subject": "birds"})

# 如果有 10 个主题,自动创建 10 个并行任务!

5. Map phase: parallel generation of jokes ​

python
def generate_joke(state: JokeState):
    prompt = joke_prompt.format(subject=state["subject"])
    response = model.with_structured_output(Joke).invoke(prompt)
    return {"jokes": [response.joke]}

Key details:

  • Input: JokeState (only subject)
  • Output: {"jokes": [response.joke]} (note it is a list!)
  • The returned data will be written back to the jokes field of OverallState
  • Since jokes has operator.add reducer, the output of multiple parallel nodes will be automatically spliced

Execution process diagram:

generate_joke(subject="mammals")  → 返回 {"jokes": ["joke1"]}
generate_joke(subject="reptiles") → 返回 {"jokes": ["joke2"]}
generate_joke(subject="birds")    → 返回 {"jokes": ["joke3"]}

最终 OverallState.jokes = ["joke1", "joke2", "joke3"]

6. Reduce phase: Choose the best joke ​

python
def best_joke(state: OverallState):
    # 将所有笑话合并为一个字符串
    jokes = "\n\n".join(state["jokes"])

    # 让 LLM 选择最好的笑话
    prompt = best_joke_prompt.format(topic=state["topic"], jokes=jokes)
    response = model.with_structured_output(BestJoke).invoke(prompt)

    # 返回被选中的笑话
    return {"best_selected_joke": state["jokes"][response.id]}

Function:

  • Receive all jokes generated in parallel
  • Use LLM to evaluate and select the best jokes
  • BestJoke model returns the index (id) of the best joke
  • Get the best jokes from state["jokes"] based on index

7. Build the diagram ​

python
from langgraph.graph import END, StateGraph, START

# 创建图
graph = StateGraph(OverallState)

# 添加节点
graph.add_node("generate_topics", generate_topics)
graph.add_node("generate_joke", generate_joke)
graph.add_node("best_joke", best_joke)

# 添加边
graph.add_edge(START, "generate_topics")

# 条件边:使用 Send 动态分发任务
graph.add_conditional_edges("generate_topics", continue_to_jokes, ["generate_joke"])

graph.add_edge("generate_joke", "best_joke")
graph.add_edge("best_joke", END)

# 编译
app = graph.compile()

LangGraph knowledge points: conditional edges and Send

python
graph.add_conditional_edges("generate_topics", continue_to_jokes, ["generate_joke"])
#                          ^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^
#                          源节点             条件函数             可能的目标节点
  • continue_to_jokes returns the Send object list
  • LangGraph will automatically create a parallel path to generate_joke for each Send
  • After all parallel tasks are completed, automatically enter the best_joke node

8. Execution diagram ​

python
for s in app.stream({"topic": "animals"}):
    print(s)

Example output:

python
{'generate_topics': {'subjects': ['mammals', 'reptiles', 'birds']}}

{'generate_joke': {'jokes': ["Why don't mammals ever get lost? Because they always follow their 'instincts'!"]}}
{'generate_joke': {'jokes': ["Why don't alligators like fast food? Because they can't catch it!"]}}
{'generate_joke': {'jokes': ["Why do birds fly south for the winter? Because it's too far to walk!"]}}

{'best_joke': {'best_selected_joke': "Why don't alligators like fast food? Because they can't catch it!"}}

Points to observe:

  1. First generate 3 subtopics
  2. Then generate 3 jokes in parallel (note that the output order may be different)
  3. Choose the best joke at the end

🎓 Summary of core knowledge points ​

LangGraph-specific concepts ​

1. Send API ​

Function: Dynamically create parallel tasks

python
Send(node_name, state_dict)

Features:

  • The amount of parallelism is dynamically determined at runtime
  • Custom status can be sent (does not have to be full graph status)
  • Automatically handles parallel execution and result aggregation

2. Map-Reduce mode ​

StageFunctionNumber of nodesExecution method
MapDecompose tasks and generate resultsDynamic (according to data)Parallel
ReduceAggregation results1Serial (wait for all Maps to complete)

3. Multi-state design ​

  • OverallState: global state, throughout the entire graph
  • JokeState: local state, only used for specific nodes
  • Data can be transferred between different states through Send

4. Conditional edge + Send ​

python
graph.add_conditional_edges(
    "source_node",           # 源节点
    condition_function,      # 返回 Send 列表的函数
    ["target_node"]         # 目标节点(Send 指向的节点)
)

Python-specific knowledge points ​

1. Pydantic BaseModel ​

python
from pydantic import BaseModel

class Joke(BaseModel):
    joke: str

# 用于 LLM 结构化输出
response = model.with_structured_output(Joke).invoke(prompt)

Advantages:

  • Automatic type verification
  • Clear data structure
  • Seamless integration with LangChain

2. TypedDict vs BaseModel ​

PropertiesTypedDictBaseModel
Type checkingStatic (IDE prompt)Runtime verification
VerifyNoneYes
PurposeState DefinitionData Model, API Output
PerformanceFaster (without verification)Slightly slower (with verification)
python
# TypedDict - 用于 State
class OverallState(TypedDict):
    topic: str

# BaseModel - 用于结构化输出
class Joke(BaseModel):
    joke: str

3. List comprehension + Send ​

python
# 创建多个 Send 任务的优雅方式
[Send("generate_joke", {"subject": s}) for s in subjects]

# 等价于:
result = []
for s in subjects:
    result.append(Send("generate_joke", {"subject": s}))

💡 Best Practices ​

1. When to use Map-Reduce? ​

✅ Applicable scenarios:

  • Need to perform the same operation on multiple data items (such as batch translation, batch summary)
  • Tasks can be naturally decomposed into independent subtasks (such as processing documents in sections)
  • Need to filter from multiple candidate results (such as generating multiple answers and choosing the best one)
  • The amount of data is large and requires parallel acceleration (such as analyzing multiple data sources)

❌ Not applicable scenarios:

  • There are dependencies between subtasks
  • Tasks that cannot be broken down naturally
  • Simple queries from a single data source

2. Send API usage tips ​

Tip 1: Dynamically control the amount of parallelism ​

python
def continue_to_jokes(state: OverallState):
    # 可以根据条件过滤
    subjects = [s for s in state["subjects"] if len(s) > 3]
    return [Send("generate_joke", {"subject": s}) for s in subjects]

Tip 2: Send additional context ​

python
def continue_to_jokes(state: OverallState):
    return [
        Send("generate_joke", {
            "subject": s,
            "original_topic": state["topic"],  # 传递额外信息
            "style": "family-friendly"
        })
        for s in state["subjects"]
    ]

Tip 3: Conditional sending ​

python
def continue_to_jokes(state: OverallState):
    sends = []
    for i, s in enumerate(state["subjects"]):
        if i < 5:  # 最多只处理前 5 个
            sends.append(Send("generate_joke", {"subject": s}))
    return sends

3. State design principles ​

Principle 1: Minimize local state ​

python
# ✅ 好的设计 - 只包含必需字段
class JokeState(TypedDict):
    subject: str

# ❌ 不好的设计 - 包含不需要的字段
class JokeState(TypedDict):
    subject: str
    topic: str  # generate_joke 不需要这个
    jokes: list  # 也不需要这个

Principle 2: Use Reducer to aggregate results ​

python
# Map 节点的输出字段必须有 reducer
class OverallState(TypedDict):
    jokes: Annotated[list, operator.add]  # ✅ 正确
    # jokes: list  # ❌ 错误!并行更新会冲突

Principle 3: Clear status flow ​

python
OverallState (完整状态)
    ↓
Send → JokeState (子集)
    ↓
返回 → OverallState.jokes (部分更新)

🚀 Advanced skills ​

1. Multi-layer Map-Reduce ​

Multiple Map-Reduce levels can be nested:

python
主题
 ↓ Map
子主题 (Level 1)
 ↓ Map
详细主题 (Level 2)
 ↓ Reduce
汇总子主题
 ↓ Reduce
最终结果

2. Map-Reduce with error handling ​

python
def generate_joke(state: JokeState):
    try:
        prompt = joke_prompt.format(subject=state["subject"])
        response = model.with_structured_output(Joke).invoke(prompt)
        return {"jokes": [response.joke]}
    except Exception as e:
        # 返回错误标记或默认值
        return {"jokes": [f"Error generating joke for {state['subject']}"]}

3. Limit parallelism ​

Although Send automatically parallelizes, sometimes it is necessary to limit the number of tasks executed simultaneously (such as API rate limiting):

python
# 方法 1:在条件函数中限制
def continue_to_jokes(state: OverallState):
    # 只发送前 N 个
    max_parallel = 5
    subjects = state["subjects"][:max_parallel]
    return [Send("generate_joke", {"subject": s}) for s in subjects]

# 方法 2:分批处理(需要更复杂的图设计)

📊 Map-Reduce vs simple parallelism ​

FeaturesMap-Reduce (Send)Simple Parallelism (Fan-out)
Amount of parallelismDynamic (determined at runtime)Static (fixed at design time)
State transferFlexible (customizable)Fixed (use graph state)
Applicable scenariosList processing, batch tasksFixed number of parallel paths
ComplexityMediumLow
ScalabilityHighLow

Example comparison:

python
# 简单并行 - 固定 3 个路径
builder.add_edge("start", "task1")
builder.add_edge("start", "task2")
builder.add_edge("start", "task3")

# Map-Reduce - 动态 N 个任务
def send_tasks(state):
    return [Send("task", {"data": d}) for d in state["data_list"]]
builder.add_conditional_edges("start", send_tasks, ["task"])

🎯 Practical application cases ​

Case 1: Document Summary ​

python
# Map: 为每个段落生成摘要
def summarize_chunk(state: ChunkState):
    summary = llm.invoke(f"Summarize: {state['chunk']}")
    return {"summaries": [summary]}

# Reduce: 合并所有段落摘要
def combine_summaries(state: OverallState):
    all_summaries = "\n".join(state["summaries"])
    final = llm.invoke(f"Create final summary: {all_summaries}")
    return {"final_summary": final}

Case 2: Multi-language translation ​

python
# Map: 翻译到多种语言
def send_to_translate(state):
    languages = ["es", "fr", "de", "zh"]
    return [Send("translate", {"lang": lang, "text": state["text"]})
            for lang in languages]

# Reduce: 收集所有翻译
def collect_translations(state):
    return {"all_translations": state["translations"]}

Case 3: Multi-angle analysis ​

python
# Map: 从不同角度分析文本
def send_to_analyze(state):
    perspectives = ["technical", "business", "user", "security"]
    return [Send("analyze", {"perspective": p, "text": state["text"]})
            for p in perspectives]

# Reduce: 综合所有分析
def synthesize(state):
    combined = llm.invoke(f"Synthesize these analyses: {state['analyses']}")
    return {"final_analysis": combined}

📖 Further reading ​


🔍 Frequently Asked Questions ​

Q1: What is the difference between Send and ordinary edges? ​

Common edge: Static routing, determined during design

python
graph.add_edge("A", "B")  # A 总是流向 B

Send: Dynamic routing, determined at runtime

python
# 根据数据动态创建多个并行任务
return [Send("B", data) for data in dynamic_data]

Q2: Why does generate_joke return {"jokes": [joke]} instead of {"jokes": joke}? ​

Because OverallState.jokes uses the operator.add reducer, it expects a list of operations:

python
# 正确 ✅
operator.add(["joke1"], ["joke2"])  # → ["joke1", "joke2"]

# 错误 ❌
operator.add("joke1", "joke2")  # → "joke1joke2" (字符串拼接)

Q3: Can I send completely different status in Send? ​

Can! The status sent by Send does not need to match OverallState:

python
# OverallState 有 topic, subjects, jokes
# 但 Send 可以发送任意结构
Send("generate_joke", {"subject": "cats", "style": "silly"})

As long as the target node (generate_joke) can handle this state.


Summary: Map-Reduce is a powerful mode for processing batch and parallel tasks in LangGraph. With the Send API, we can dynamically create any number of parallel tasks and then use reducers to elegantly aggregate the results. This is a key technology for building scalable, high-performance AI applications!

English translation of community learning materials. MIT licensed.