Skip to content

Detailed interpretation of LangGraph sub-graph (Sub-graph) ​

📋 Case Overview ​

This case demonstrates the core concepts and usage of Sub-graph in LangGraph. Although the code is relatively simple, it reveals a very important architectural pattern: how to manage different state spaces in complex systems.

Business scenario ​

Imagine you are running a question and answer system and need to analyze user logs regularly:

  1. Log Cleaning: Original logs need to be preprocessed
  2. Failure Analysis: Find records with poor answer quality and generate improvement reports
  3. Problem Summary: Analyze the topics that users are most concerned about, and send it to the Slack notification team

Core Challenge ​

These two analysis tasks (failure analysis & problem summary) require:

  • Parallel execution for greater efficiency
  • Independent state space (each has different intermediate variables)
  • Share input data (both require access to cleaned logs)
  • Summary output results to the main image

**Sub-picture is the best solution to this problem! **


🗺️ Overall architecture diagram ​

用户输入原始日志(raw_logs)
         ↓
    ┌─────────┐
    │clean_logs│  清洗日志
    └─────────┘
         ↓ cleaned_logs(共享数据)
    ┌────┴────┐
    ↓         ↓
┌──────┐  ┌──────┐
│失败分析│  │问题总结│  (两个独立子图并行运行)
│子图   │  │子图   │
└──────┘  └──────┘
    ↓         ↓
fa_summary  report
    └────┬────┘
         ↓
     最终结果汇总

📚 Detailed explanation of code segments ​

Part 1: Define the data structure ​

Log data model ​

python
from typing_extensions import TypedDict
from typing import List, Optional

class Log(TypedDict):
    id: str              # 日志 ID
    question: str        # 用户问题
    docs: Optional[List] # 检索到的文档(可选)
    answer: str          # 系统回答
    grade: Optional[int] # 质量评分(可选)
    grader: Optional[str]# 评分器名称(可选)
    feedback: Optional[str] # 反馈信息(可选)

Python knowledge points:

  1. TypedDict: This is a type introduced in Python 3.8+, used to define the structure of the dictionary

    python
    # 普通字典 - 不知道有哪些键
    log1 = {"id": "1", "question": "xxx"}
    
    # TypedDict - 明确定义了键和类型
    log2: Log = {"id": "1", "question": "xxx", ...}
  2. Optional[type]: Indicates that this field can be of the specified type or None

    python
    grade: Optional[int]  # 等价于 grade: int | None

**Why is it designed like this? **

  • Not all logs have grades, only those that have been evaluated
  • This flexible data structure adapts to actual business scenarios

Part 2: Failure Analysis Subgraph ​

Status definition ​

python
# 子图内部状态(完整状态)
class FailureAnalysisState(TypedDict):
    cleaned_logs: List[Log]   # 输入:清洗后的日志
    failures: List[Log]       # 中间变量:失败的日志
    fa_summary: str           # 输出:失败分析摘要
    processed_logs: List[str] # 输出:处理过的日志 ID

# 子图输出状态(只包含需要返回给主图的字段)
class FailureAnalysisOutputState(TypedDict):
    fa_summary: str           # 只输出摘要
    processed_logs: List[str] # 只输出处理记录

Key Concept: Why do we need two states?

  1. Internal state (FailureAnalysisState):

    • Contains all intermediate variables (such as failures)
    • Used to transfer data between internal nodes of subgraphs
  2. Output State (FailureAnalysisOutputState):

    • Only include fields that need to be returned to the main image
    • Avoid unnecessary data transfer
    • Reduce the possibility of status conflicts

Analogy:

  • Internal state = all tools and ingredients in the kitchen
  • Output status = finished dishes served to guests

Node function ​

1. get_failures - Filter failure log

python
def get_failures(state):
    """ 获取包含失败记录的日志 """
    cleaned_logs = state["cleaned_logs"]

    # 筛选出有 grade 字段的日志(表示被评分过)
    failures = [log for log in cleaned_logs if "grade" in log]

    return {"failures": failures}

Python knowledge points - list comprehension:

python
# 传统写法
failures = []
for log in cleaned_logs:
    if "grade" in log:
        failures.append(log)

# 列表推导式(更简洁)
failures = [log for log in cleaned_logs if "grade" in log]

Business Logic:

  • Only evaluated logs have the grade field
  • These logs usually require manual review due to quality issues

2. generate_summary - Generate summary

python
def generate_summary(state):
    """ 生成失败分析摘要 """
    failures = state["failures"]

    # 实际应用中,这里会调用 LLM 分析失败原因
    # fa_summary = summarize_with_llm(failures)
    fa_summary = "Poor quality retrieval of Chroma documentation."

    # 记录处理过的日志 ID
    processed_logs = [
        f"failure-analysis-on-log-{failure['id']}"
        for failure in failures
    ]

    return {
        "fa_summary": fa_summary,
        "processed_logs": processed_logs
    }

Technical Details:

  1. f-string format string (Python 3.6+):

    python
    failure_id = "123"
    
    # 传统方式
    msg = "failure-analysis-on-log-" + failure_id
    
    # f-string(更直观)
    msg = f"failure-analysis-on-log-{failure_id}"
  2. The role of processed_logs:

    • Track which logs have been processed
    • for auditing and debugging
    • The main image will collect the processing records of all sub-images

Build subgraph ​

python
from langgraph.graph import StateGraph, START, END

fa_builder = StateGraph(
    state_schema=FailureAnalysisState,        # 内部状态
    output_schema=FailureAnalysisOutputState  # 输出状态
)

# 添加节点
fa_builder.add_node("get_failures", get_failures)
fa_builder.add_node("generate_summary", generate_summary)

# 添加边(定义执行顺序)
fa_builder.add_edge(START, "get_failures")
fa_builder.add_edge("get_failures", "generate_summary")
fa_builder.add_edge("generate_summary", END)

Execution process:

START → get_failures → generate_summary → END

LangGraph Concept:

  • START: special node, representing the entrance of the graph
  • END: special node, representing the exit of the graph
  • add_edge(A, B): directed edge from node A to node B

Part 3: Problem summary sub-picture ​

Status definition ​

python
# 内部状态
class QuestionSummarizationState(TypedDict):
    cleaned_logs: List[Log]   # 输入
    qs_summary: str           # 中间变量:问题摘要
    report: str               # 输出:最终报告
    processed_logs: List[str] # 输出:处理记录

# 输出状态
class QuestionSummarizationOutputState(TypedDict):
    report: str               # 只输出报告
    processed_logs: List[str] # 只输出处理记录

Note: qs_summary is an intermediate variable and does not need to be returned to the main image


Node function ​

1. generate_summary - Generate a summary of the issue

python
def generate_summary(state):
    cleaned_logs = state["cleaned_logs"]

    # 实际会调用 LLM 分析用户问题的主题
    summary = "Questions focused on usage of ChatOllama and Chroma vector store."

    # 记录处理的日志
    processed_logs = [
        f"summary-on-log-{log['id']}"
        for log in cleaned_logs
    ]

    return {
        "qs_summary": summary,
        "processed_logs": processed_logs
    }

2. send_to_slack - Send report

python
def send_to_slack(state):
    qs_summary = state["qs_summary"]

    # 实际会基于摘要生成完整报告并发送到 Slack
    # report = generate_report(qs_summary)
    # send_to_slack_api(report)
    report = "foo bar baz"

    return {"report": report}

Business Process:

清洗日志 → 生成摘要 → 格式化报告 → 发送到 Slack

Build subgraph ​

python
qs_builder = StateGraph(
    QuestionSummarizationState,
    output_schema=QuestionSummarizationOutputState
)

qs_builder.add_node("generate_summary", generate_summary)
qs_builder.add_node("send_to_slack", send_to_slack)

qs_builder.add_edge(START, "generate_summary")
qs_builder.add_edge("generate_summary", "send_to_slack")
qs_builder.add_edge("send_to_slack", END)

Part 4: Main picture - integrated sub-picture ​

Main picture status ​

python
from operator import add
from typing import Annotated

class EntryGraphState(TypedDict):
    raw_logs: List[Log]                      # 输入:原始日志
    cleaned_logs: List[Log]                  # 清洗后的日志
    fa_summary: str                          # 来自失败分析子图
    report: str                              # 来自问题总结子图
    processed_logs: Annotated[List[int], add] # 来自两个子图,需要合并

Core technical points - Annotated and Reducer:

python
processed_logs: Annotated[List[int], add]

This line of code contains three important concepts:

  1. Annotated: Type annotation enhancement tool for Python 3.9+

    python
    from typing import Annotated
    
    # 基本类型注解
    name: str
    
    # 带额外元数据的注解
    age: Annotated[int, "must be positive"]
  2. Reducer: add from operator module

    python
    from operator import add
    
    # add 的作用是合并列表
    result = add([1, 2], [3, 4])  # 结果:[1, 2, 3, 4]
  3. **Why do you need Reducer? **

Because both subgraphs run in parallel will return processed_logs:

python
# 失败分析子图返回
{"processed_logs": ["failure-analysis-on-log-2"]}

# 问题总结子图返回
{"processed_logs": ["summary-on-log-1", "summary-on-log-2"]}

# LangGraph 需要知道如何合并这两个结果
# 使用 add 后:
{"processed_logs": [
    "failure-analysis-on-log-2",
    "summary-on-log-1",
    "summary-on-log-2"
]}

Common Reducers:

python
from operator import add

# 列表合并
Annotated[List[str], add]  # [1, 2] + [3] = [1, 2, 3]

# 自定义 Reducer
def merge_dicts(a, b):
    return {**a, **b}

Annotated[dict, merge_dicts]

Why does cleaned_logs not require a Reducer? ​

Question: cleaned_logs will also be accessed by two subgraphs, why is Annotated not needed?

Answer: Because we defined output_schema!

python
# 失败分析子图的输出状态(不包含 cleaned_logs)
class FailureAnalysisOutputState(TypedDict):
    fa_summary: str
    processed_logs: List[str]
    # 注意:没有 cleaned_logs

# 问题总结子图的输出状态(也不包含 cleaned_logs)
class QuestionSummarizationOutputState(TypedDict):
    report: str
    processed_logs: List[str]
    # 注意:也没有 cleaned_logs

Mechanism explanation:

  1. When there is no output_schema:

    python
    StateGraph(MyState)  # 所有状态字段都会输出
    • The subgraph will return all status fields
    • cleaned_logs will be returned by both subgraphs
    • Requires Reducer to merge
  2. With output_schema:

    python
    StateGraph(MyState, output_schema=MyOutputState)
    • The subgraph only returns fields defined in MyOutputState
    • cleaned_logs is not in the output state and will not return
    • No Reducer required

Analogy:

  • no output_schema = function returns all local variables
  • With output_schema = function only returns the value you specify

Main graph nodes and construction ​

clean_logs node:

python
def clean_logs(state):
    """ 清洗日志 """
    raw_logs = state["raw_logs"]

    # 实际应用中会进行数据清洗:
    # - 去重
    # - 格式标准化
    # - 过滤无效数据
    cleaned_logs = raw_logs  # 简化示例

    return {"cleaned_logs": cleaned_logs}

Build the main image:

python
entry_builder = StateGraph(EntryGraphState)

# 添加常规节点
entry_builder.add_node("clean_logs", clean_logs)

# 关键:将编译后的子图作为节点添加
entry_builder.add_node(
    "question_summarization",
    qs_builder.compile()  # 编译子图
)

entry_builder.add_node(
    "failure_analysis",
    fa_builder.compile()  # 编译子图
)

# 定义执行流程
entry_builder.add_edge(START, "clean_logs")
entry_builder.add_edge("clean_logs", "failure_analysis")
entry_builder.add_edge("clean_logs", "question_summarization")
entry_builder.add_edge("failure_analysis", END)
entry_builder.add_edge("question_summarization", END)

# 编译主图
graph = entry_builder.compile()

Key Points:

  1. Subgraphs are also nodes:

    python
    entry_builder.add_node("子图名称", 子图实例.compile())
  2. Parallel execution:

    python
    entry_builder.add_edge("clean_logs", "failure_analysis")
    entry_builder.add_edge("clean_logs", "question_summarization")

    There are two edges starting from clean_logs, and the two subgraphs will run in parallel.

  3. xray parameters:

    python
    graph.get_graph(xray=1).draw_mermaid_png()

    xray=1 will expand the internal structure of the subgraph to facilitate debugging.


Part 5: Running the Example ​

Prepare test data ​

python
# 正常的问答日志
question_answer = Log(
    id="1",
    question="How can I import ChatOllama?",
    answer="To import ChatOllama, use: 'from langchain_community.chat_models import ChatOllama.'",
    # 没有 grade 字段,表示质量正常
)

# 有质量问题的日志
question_answer_feedback = Log(
    id="2",
    question="How can I use Chroma vector store?",
    answer="To use Chroma, define: rag_chain = create_retrieval_chain(retriever, question_answer_chain).",
    grade=0,  # 评分为 0,表示质量差
    grader="Document Relevance Recall",
    feedback="The retrieved documents discuss vector stores in general, but not Chroma specifically",
)

raw_logs = [question_answer, question_answer_feedback]

Execution diagram ​

python
result = graph.invoke({"raw_logs": raw_logs})

Output results:

python
{
    'raw_logs': [...],  # 原始输入

    'cleaned_logs': [...],  # clean_logs 节点的输出

    'fa_summary': 'Poor quality retrieval of Chroma documentation.',
    # ↑ 来自失败分析子图

    'report': 'foo bar baz',
    # ↑ 来自问题总结子图

    'processed_logs': [
        'failure-analysis-on-log-2',   # 失败分析处理了 log-2
        'summary-on-log-1',            # 问题总结处理了 log-1
        'summary-on-log-2'             # 问题总结处理了 log-2
    ]
    # ↑ 两个子图的 processed_logs 通过 add 合并
}

🔑 Core technology analysis ​

1. The nature of subgraphs ​

**What is a sub-picture? **

  • The subgraph itself is a complete StateGraph
  • Can be run and tested independently
  • After compiling through compile(), it can be embedded as a node in other graphs

Analogy:

  • Main image = a company
  • Subgraph = Department within the company
  • Each department has its own workflow (internal state)
  • The department only reports key results (output status) to the company

2. Status communication mechanism ​

Main image → Subimage (input):

python
class EntryGraphState(TypedDict):
    cleaned_logs: List[Log]  # 主图有这个字段

class FailureAnalysisState(TypedDict):
    cleaned_logs: List[Log]  # 子图也有这个字段

When the main graph calls a subgraph, LangGraph will automatically pass fields with the same name:

python
# 主图状态
{"cleaned_logs": [...]}

# 自动传递给子图
# 子图可以访问 state["cleaned_logs"]

Sub-image → Main image (output):

python
class FailureAnalysisOutputState(TypedDict):
    fa_summary: str  # 子图输出这个字段

class EntryGraphState(TypedDict):
    fa_summary: str  # 主图有同名字段接收

The fields returned by the subgraph will update the fields of the same name in the main graph state.


Key Principles:

✅ Field with the same name = communication channel

  • The main picture and sub-picture pass data through fields with the same name
  • Fields with different names do not interfere with each other

✅ Input = State Intersection

  • Sub-pictures can only access input fields with the same name as the main picture.

✅ output = output_schema

  • Subgraph only returns fields defined in output_schema
  • Reduce unnecessary data transfer

3. Merge results of parallel subgraphs ​

Scenario: Two subgraphs run in parallel, both returning fields with the same name

python
# 子图 A 返回
{"processed_logs": ["a", "b"]}

# 子图 B 返回
{"processed_logs": ["c", "d"]}

# 如何合并?

Solution 1: Use Reducer

python
from operator import add

class State(TypedDict):
    processed_logs: Annotated[List[str], add]  # 指定合并方式

Result: {"processed_logs": ["a", "b", "c", "d"]}


Solution 2: Use different field names

python
class EntryState(TypedDict):
    fa_processed_logs: List[str]  # 失败分析的记录
    qs_processed_logs: List[str]  # 问题总结的记录

class FAOutputState(TypedDict):
    fa_processed_logs: List[str]  # 不同名

class QSOutputState(TypedDict):
    qs_processed_logs: List[str]  # 不同名

In this way, the two subgraphs return different fields and do not need to be merged.


4. When to use subplots? ​

Scenarios suitable for using sub-pictures:

✅ Independent business logic

  • Each subplot is responsible for a complete subtask
  • Have clear input and output boundaries

✅ Status isolation required

  • Intermediate variables of subgraphs should not pollute the main graph state
  • For example: failures is only used within the failure analysis subgraph

✅ Reusable process

  • The same sub-picture can be reused in different main pictures
  • For example: Log cleaning subgraph can be used in multiple scenarios

✅ Parallel execution

  • Multiple independent tasks need to be run simultaneously
  • Combine results via Reducer

Scenarios not suitable for using sub-pictures:

❌ Simple linear process

  • If there are just a few sequentially executed nodes, no subgraph is needed

❌ State is highly coupled

  • If nodes need to frequently share intermediate states

❌ Over-design

  • Don’t use subgraphs for the sake of using subgraphs

💡 Summary of Python knowledge points ​

1. TypedDict ​

python
from typing_extensions import TypedDict

# 定义字典结构
class Person(TypedDict):
    name: str
    age: int

# 使用
person: Person = {"name": "Alice", "age": 30}

Advantages:

  • Provide type checking
  • IDE auto-completion
  • Clear data structure documentation

2. Optional type ​

python
from typing import Optional

# 表示可选字段
grade: Optional[int]  # 可以是 int 或 None

# 等价于
grade: int | None  # Python 3.10+

3. Annotated metadata ​

python
from typing import Annotated

# 基本用法
Age = Annotated[int, "must be positive"]

# LangGraph 用法
from operator import add
Logs = Annotated[List[str], add]  # 指定合并方式

4. List comprehension ​

python
# 基本形式
result = [expression for item in iterable if condition]

# 示例
numbers = [1, 2, 3, 4, 5]
even = [n for n in numbers if n % 2 == 0]  # [2, 4]
squared = [n**2 for n in numbers]  # [1, 4, 9, 16, 25]

5. f-string formatting ​

python
name = "Alice"
age = 30

# 基本用法
msg = f"Name: {name}, Age: {age}"

# 表达式
msg = f"Next year: {age + 1}"

# 格式控制
pi = 3.14159
msg = f"Pi: {pi:.2f}"  # "Pi: 3.14"

6. operator module ​

python
from operator import add

# 列表合并
add([1, 2], [3, 4])  # [1, 2, 3, 4]

# 数字相加
add(10, 20)  # 30

# 其他常用操作符
from operator import mul, sub
mul(3, 4)  # 12
sub(10, 3)  # 7

🎯 Practical suggestions ​

For beginners ​

  1. Understand status communication first

    • Draw the state structure of the main picture and sub-pictures
    • Mark which fields are shared
  2. Start Simple

    • Build a subgraph first
    • Add the second one after the test passes
    • Finally handle parallelization and merging
  3. Use Visualization

    python
    # 查看子图结构
    fa_graph.get_graph().draw_mermaid_png()
    
    # 查看主图结构(展开子图)
    main_graph.get_graph(xray=1).draw_mermaid_png()
  4. Debugging Tips

    • Test each subplot individually first
    • Ensure subgraphs can run independently
    • Then integrated into the main image

For advanced use ​

  1. Optimized state design

    • Include only necessary fields in output_schema
    • Use meaningful field names to avoid conflicts
    • Proper use of Reducers
  2. Error handling

    python
    def safe_node(state):
        try:
            return process(state)
        except Exception as e:
            return {"error": str(e)}
  3. Performance Optimization

    • Leverage parallel execution to improve efficiency
    • Avoid passing large amounts of unnecessary data
    • Use xray parameters to analyze execution paths
  4. Testability

    python
    # 单独测试子图
    fa_graph = fa_builder.compile()
    result = fa_graph.invoke({"cleaned_logs": test_logs})
    
    # 测试主图
    main_graph = entry_builder.compile()
    result = main_graph.invoke({"raw_logs": test_logs})

📌 Summary ​

Core concepts ​

  1. Subgraphs are independent graphs

    • Has its own state space
    • Can be run and tested independently
    • Other images can be embedded through compile()
  2. Status communication through fields with the same name

    • Main Image → Subimage: Automatically pass input fields with the same name
    • subgraph → maingraph: return fields in output_schema
  3. Parallel subgraphs require merging of processing results

    • Use Annotated + Reducer
    • or use different field names

Design principles ​

✅ Single Responsibility: Each subgraph is responsible for an independent task ✅ State Isolation: Intermediate variables are not exposed to the main image ✅ Clear Interface: clearly defined input and output states ✅ Reusability: Sub-pictures can be used in multiple scenarios

Applicable scenarios ​

  • Multi-agent system (each agent is a subgraph)
  • Modularization of complex business processes
  • Independent tasks that need to be executed in parallel
  • Scenarios that require state isolation

🚀 Extended exercises ​

  1. Add third subgraph

    • Create a "Performance Monitoring" subgraph
    • Analyze log response times
    • Run three subplots in parallel
  2. Implement error handling

    • Add error catching in subplots
    • Return error message to main image
    • The main picture decides whether to continue based on the error
  3. Nested subgraph

    • Nest subgraphs inside subgraphs
    • Understand the multi-layer state transfer mechanism
  4. Dynamic sub-picture selection

    • Decide which subgraphs to call based on input data
    • Implement conditional parallelism

Final words: Subgraphs are the key mechanism by which LangGraph achieves modularity and scalability. Although this case is simple, the ideas of "state isolation" and "parallel merging" it demonstrates are crucial when building complex multi-agent systems. Master subgraphs, and you’ll have the foundation for building large-scale AI systems!


🧠 In-depth interpretation of core concepts ​

Scene analogy: Corporate office

Imagine a company with three offices:

  1. Front Office (main picture)

    • Responsible for receiving customers and assigning tasks
    • There is a public whiteboard to record: customer information, task progress, and final results
  2. Technical Department Office (Subpicture A)

    • Have your own small whiteboard: record code bugs, repair plans, and technical documents
    • The front desk doesn't see or care about these intermediate processes
    • After completion, just tell the front desk: "It's fixed, here is the repair report"
  3. Marketing Department Office (Subpicture B)

    • Have your own small whiteboard: record research data, analysis drafts, and competitive product information
    • The front desk doesn't see or care about these intermediate processes
    • When finished, just tell the front desk: "Done, here's the market report"

Independent state space = each office has its own small whiteboard

python
# 主图状态(前台的公共白板)
class MainState:
    客户需求: str           # 前台记录
    技术修复报告: str       # 技术部提交的
    市场分析报告: str       # 市场部提交的

# 技术部子图状态(技术部的小白板)
class TechSubGraphState:
    客户需求: str           # 从前台复制过来的
    bug列表: List[str]     # 只在技术部用,前台不知道
    修复代码: str          # 只在技术部用,前台不知道
    技术修复报告: str       # 要提交给前台的

# 市场部子图状态(市场部的小白板)
class MarketSubGraphState:
    客户需求: str           # 从前台复制过来的
    调研数据: List[dict]   # 只在市场部用,前台不知道
    竞品分析: str          # 只在市场部用,前台不知道
    市场分析报告: str       # 要提交给前台的

**Why do you need a separate space? **

❌ Problem of no independent space:

python
# 如果都用同一个白板(共享状态)
全公司共享状态 = {
    "客户需求": "...",
    "bug列表": [...],        # 技术部的
    "修复代码": "...",       # 技术部的
    "调研数据": [...],       # 市场部的
    "竞品分析": "...",       # 市场部的
    # 全混在一起,乱套了!
}

Question:

  • The customer-facing team does not need technical details, but does need a bug list and proposed fixes.
  • The engineering team does not need market data, but does need research findings and competitor analysis.
  • Field names can conflict if both teams use the same name for their notes.
  • The state is bloated and difficult to manage

✅ Benefits of having an independent space:

python
# 技术部只关心自己的事
tech_state = {
    "客户需求": "...",      # 输入
    "bug列表": [...],       # 内部工作
    "修复代码": "...",      # 内部工作
    "技术修复报告": "..."   # 输出
}

# 市场部只关心自己的事
market_state = {
    "客户需求": "...",      # 输入
    "调研数据": [...],      # 内部工作
    "竞品分析": "...",      # 内部工作
    "市场分析报告": "..."   # 输出
}

# 前台只看最终结果
main_state = {
    "客户需求": "...",
    "技术修复报告": "...",  # 来自技术部
    "市场分析报告": "..."   # 来自市场部
}

Benefits:

  • ✅ Clear responsibilities: Each department manages its own affairs
  • ✅ Avoid contamination: intermediate variables will not be leaked to other places
  • ✅ Parallel available: The technical department and the marketing department can work at the same time without interfering with each other
  • ✅ Easy to maintain: Modifying the technical department process will not affect the marketing department

LangGraph’s State Core Concept (Vernacular Version) ​

**What is State? **

State is a data logbook that records the data generated by all nodes from the beginning to the present.

Core metaphor: State = Information Square

Imagine a central square in a city where everyone (nodes) comes:

  • 📢 Publish Message: Post the results of your processing to the bulletin board of the square
  • 👀 View messages: See what information others have posted as input for your own work
  • 🔄 Information Summary: Everyone’s work results are gathered in this square
         信息广场(State)
    ┌────────────────────────┐
    │  用户输入: "..."        │  ← 初始信息
    │  节点A的结果: "..."     │  ← 节点A 贴上去的
    │  节点B的结果: "..."     │  ← 节点B 贴上去的
    │  节点C的结果: "..."     │  ← 节点C 贴上去的
    │  最终答案: "..."        │  ← 最后一个节点总结的
    └────────────────────────┘
           ↑    ↑    ↑    ↑
           │    │    │    │
        节点A 节点B 节点C 节点D
      (来贴)(来看)(来贴)(来看)

Key Features:

  1. Centralized Aggregation -The information generated by all nodes is summarized in the State square

    • It is not a point-to-point transmission, but "I post the announcement → you come to see the announcement"
  2. Information persistence

    • Messages posted on the square will not disappear (unless overwritten)
    • Later nodes can see the information of all previous nodes
  3. Asynchronous collaboration

    • Node A does not need to wait for node B to finish reading before continuing.
    • Just post the information individually, and nodes with dependencies will naturally view it.
  4. Globally visible

    • Any node can see all the information on the square
    • But in fact, nodes only care about the part they need

Operation mechanism of information square

Scenario: Multiple people collaborate to write a report ​

python
# 广场上的公告板(State)
class 报告State(TypedDict):
    老板需求: str          # 老板发布的
    市场数据: dict         # 市场部贴的
    技术方案: str          # 技术部贴的
    财务预算: float        # 财务部贴的
    最终报告: str          # 汇总人员生成的

Execution process:

1. 老板来广场,贴了个需求:
   State = {"老板需求": "做个新产品分析"}

2. 市场部来广场看需求,做完调研后贴结果:
   State = {
       "老板需求": "做个新产品分析",
       "市场数据": {"用户量": 1000, "竞品": ["A", "B"]}  ← 新增
   }

3. 技术部来广场看需求和市场数据,贴技术方案:
   State = {
       "老板需求": "做个新产品分析",
       "市场数据": {...},
       "技术方案": "使用 Python + React"  ← 新增
   }

4. 财务部来广场看技术方案,贴预算:
   State = {
       "老板需求": "做个新产品分析",
       "市场数据": {...},
       "技术方案": "使用 Python + React",
       "财务预算": 100000.0  ← 新增
   }

5. 汇总人员来广场看所有信息,生成最终报告:
   State = {
       "老板需求": "做个新产品分析",
       "市场数据": {...},
       "技术方案": "使用 Python + React",
       "财务预算": 100000.0,
       "最终报告": "综合市场、技术、财务的完整方案"  ← 新增
   }

Note:

  • Each department (node) works independently
  • They collaborate through Square (State) and do not need to communicate directly
  • The information on the square is getting richer and richer, and is finally aggregated into a complete result

Information Plaza vs Traditional Function Call

❌ Traditional method (point-to-point delivery):

python
# 像接力赛,信息一个人传一个人
需求 = 老板.发布需求()
市场数据 = 市场部.调研(需求)           # 只能看到需求
技术方案 = 技术部.设计(需求, 市场数据)  # 只能看到需求和市场数据
预算 = 财务部.计算(技术方案)           # 只能看到技术方案
报告 = 汇总.生成(需求, 市场数据, 技术方案, 预算)  # 要手动传所有参数!

Question:

  • The subsequent function needs to know the parameters of all previous functions -Change one place, all function calls must be changed
  • Information can only flow in one direction and cannot be looked back

✅ State method (Information Plaza):

python
# 每个节点只负责:1. 看广场  2. 贴公告
def 市场部(state):
    需求 = state["老板需求"]  # 从广场看
    市场数据 = 做调研(需求)
    return {"市场数据": 市场数据}  # 贴到广场

def 技术部(state):
    需求 = state["老板需求"]      # 从广场看
    市场 = state["市场数据"]      # 从广场看
    方案 = 设计方案(需求, 市场)
    return {"技术方案": 方案}  # 贴到广场

def 财务部(state):
    方案 = state["技术方案"]  # 从广场看
    预算 = 计算预算(方案)
    return {"财务预算": 预算}  # 贴到广场

def 汇总(state):
    # 从广场一次性看到所有信息!
    所有信息 = state
    报告 = 生成报告(所有信息)
    return {"最终报告": 报告}  # 贴到广场

Advantages:

  • ✅ Each node only cares about the square (state) and does not need to know other nodes
  • ✅ Adding new nodes will not affect existing nodes
  • ✅ Information is globally visible, and any node can look back at previous data
  • ✅ Decoupled and easy to expand

"Partition Management" of Information Plaza (State Isolation of Subgraphs)

When the square is too large and the information is too complicated, you can set up Partition Square (sub-picture).

         总广场(主图 State)
    ┌────────────────────────┐
    │ 用户需求: "..."         │
    │ 市场报告: "..."  ←──────┼─── 来自市场分区
    │ 技术报告: "..."  ←──────┼─── 来自技术分区
    │ 最终方案: "..."         │
    └────────────────────────┘
              ↓          ↓
     ┌───────────┐  ┌───────────┐
     │市场分区广场│  │技术分区广场│
     │───────────│  │───────────│
     │调研数据: ..│  │代码设计: ..│  ← 这些细节
     │竞品分析: ..│  │架构图: ...│  ← 总广场看不到
     │用户访谈: ..│  │技术选型: ..│  ← 只在分区内
     │市场报告: ..│  │技术报告: ..│  ← 最终结果贴到总广场
     └───────────┘  └───────────┘

Metaphor:

  • General Square (Main Picture State): The main square of the city government, only see the final reports of each department
  • District Square (sub-map State): a small square within each department to handle detailed work

Benefits:

  1. Information layering: The general square will not be overwhelmed by details
  2. Parallel work: Each partition can work at the same time without interfering with each other.
  3. Privacy Protection: The details of the work within the partition will not be exposed to the general square

Life Analogy: Cooking Recipe Book

Imagine you are making a complex dish:

python
# 菜谱状态(State)
class 做菜State:
    食材: List[str]        # 初始输入
    切好的菜: List[str]    # 第一步产生
    调好的酱料: str        # 第二步产生
    炒好的半成品: str      # 第三步产生
    最终成品: str          # 最后一步产生

Execution process:

开始 → 洗菜切菜 → 调酱料 → 炒菜 → 装盘 → 结束
      ↓        ↓       ↓      ↓
    更新State 更新State 更新State 更新State

Each node (step) does two things:

  1. Read the data in State (see the recipe book to know what was done in the previous step)
  2. Update the data in State (record the results of this step in the recipe book)

Three major characteristics of State

1. Accumulative ​

State is like a snowball, getting bigger and bigger, and something is added to each node.

python
# 初始状态
state = {"食材": ["鸡蛋", "番茄"]}

# 节点1:洗菜切菜
def 切菜(state):
    return {"切好的菜": ["番茄块", "鸡蛋液"]}
# 现在 state = {
#     "食材": ["鸡蛋", "番茄"],
#     "切好的菜": ["番茄块", "鸡蛋液"]  ← 新增
# }

# 节点2:调酱料
def 调酱料(state):
    return {"调好的酱料": "盐+糖+酱油"}
# 现在 state = {
#     "食材": ["鸡蛋", "番茄"],
#     "切好的菜": ["番茄块", "鸡蛋液"],
#     "调好的酱料": "盐+糖+酱油"  ← 又新增
# }

# 节点3:炒菜
def 炒菜(state):
    菜 = state["切好的菜"]      # 读取之前的数据
    酱料 = state["调好的酱料"]  # 读取之前的数据
    return {"最终成品": f"炒{菜} with {酱料}"}
# 现在 state = {
#     "食材": ["鸡蛋", "番茄"],
#     "切好的菜": ["番茄块", "鸡蛋液"],
#     "调好的酱料": "盐+糖+酱油",
#     "最终成品": "炒番茄鸡蛋 with 调料"  ← 继续新增
# }

Key point: Each node will not delete previous data, but only add new data.


2. Overwritable ​

If the node returns a field with the same name, the old value will be overwritten.

python
# 初始状态
state = {"温度": "常温"}

# 节点1:加热
def 加热(state):
    return {"温度": "100度"}
# state = {"温度": "100度"}  ← 覆盖了"常温"

# 节点2:冷却
def 冷却(state):
    return {"温度": "50度"}
# state = {"温度": "50度"}  ← 又覆盖了"100度"

Default behavior: Later nodes will overwrite the same-named fields of previous nodes.

Custom Behavior: Use Reducer to change the merging method

python
from operator import add
from typing import Annotated

class State(TypedDict):
    # 默认行为:覆盖
    温度: str

    # 自定义行为:累加
    日志: Annotated[List[str], add]

# 使用
state = {"日志": ["步骤1"]}

# 节点1
def 节点1(state):
    return {"日志": ["步骤2"]}
# state = {"日志": ["步骤1", "步骤2"]}  ← 合并,不是覆盖!

# 节点2
def 节点2(state):
    return {"日志": ["步骤3"]}
# state = {"日志": ["步骤1", "步骤2", "步骤3"]}  ← 继续合并

3. The only way to communicate between nodes ​

In LangGraph, nodes cannot communicate directly with each other and can only communicate through State.

❌ Wrong way (node wants to call directly):

python
def 节点A(state):
    result = 节点B(state)  # 错误!不能这样
    return {"data": result}

✅ Correct way (communication via State):

python
# 节点A 写入 State
def 节点A(state):
    return {"中间结果": "A的数据"}

# 节点B 从 State 读取
def 节点B(state):
    a_data = state["中间结果"]  # 读取A写入的数据
    return {"最终结果": f"处理了{a_data}"}

# 在图中连接
graph.add_edge("节点A", "节点B")

Analogy:

  • State = Pass note
  • Node A writes "Intermediate result = XXX" on the note
  • Node B reads the note and knows the result of A

State’s design principles

Principle 1: Include only necessary fields ​

❌ Bad Design (Too many useless fields):

python
class State(TypedDict):
    用户输入: str
    临时变量1: str     # 只有一个节点用
    临时变量2: int     # 只有一个节点用
    临时变量3: list    # 只有一个节点用
    调试信息: str      # 开发时用,生产不需要
    最终结果: str

✅ GOOD DESIGN (Keep only what’s necessary):

python
class State(TypedDict):
    用户输入: str      # 输入
    最终结果: str      # 输出
    # 临时变量在函数内部定义,不放 State

Tip: If a certain data is only used inside a node, use local variables instead of State.


Principle 2: Use subgraphs to isolate complex states ​

When the state becomes complex, split it with subgraphs.

❌ Bad Design (bloated state):

python
class 巨型State(TypedDict):
    # 主流程字段
    用户输入: str
    最终结果: str

    # 子任务A的字段
    A_中间数据1: str
    A_中间数据2: List
    A_结果: str

    # 子任务B的字段
    B_中间数据1: dict
    B_中间数据2: str
    B_结果: str

    # 全混在一起!

✅ Good design (separated with sub-images):

python
# 主图状态(只关心最终结果)
class 主State(TypedDict):
    用户输入: str
    A_结果: str        # 来自子图A
    B_结果: str        # 来自子图B
    最终结果: str

# 子图A状态(有自己的中间变量)
class 子图AState(TypedDict):
    用户输入: str      # 输入
    中间数据1: str     # 内部使用
    中间数据2: List    # 内部使用
    A_结果: str        # 输出

# 子图B状态(有自己的中间变量)
class 子图BState(TypedDict):
    用户输入: str      # 输入
    中间数据1: dict    # 内部使用
    中间数据2: str     # 内部使用
    B_结果: str        # 输出

Principle 3: Clear inputs and outputs ​

Use output_schema to specify the output of the subgraph.

python
# 子图内部状态(完整的工作空间)
class 内部State(TypedDict):
    输入数据: str
    临时数据1: str
    临时数据2: int
    最终结果: str

# 子图输出状态(只输出必要的)
class 输出State(TypedDict):
    最终结果: str      # 只输出这一个

# 构建子图
sub_graph = StateGraph(
    state_schema=内部State,      # 内部用完整状态
    output_schema=输出State       # 输出时只返回最终结果
)

Benefits:

  • The main picture will not be polluted by temporary data of sub-pictures
  • Clear interface conventions
  • Easy to test and maintain

State practical example: multi-step reasoning

python
from typing import TypedDict, List
from langgraph.graph import StateGraph, START, END

# 定义状态
class ReasoningState(TypedDict):
    问题: str                  # 输入
    思考步骤: List[str]        # 累积的推理过程
    最终答案: str              # 输出

# 节点1:分析问题
def 分析问题(state):
    问题 = state["问题"]
    分析 = f"分析:{问题}涉及数学计算"
    return {"思考步骤": [分析]}  # 第一个思考步骤

# 节点2:制定方案
def 制定方案(state):
    方案 = "方案:先计算子问题,再汇总"
    return {"思考步骤": [方案]}  # 会和之前的合并(如果用 Reducer)

# 节点3:执行计算
def 执行计算(state):
    步骤 = state["思考步骤"]  # 读取之前的推理
    计算 = "执行:2 + 2 = 4"
    return {
        "思考步骤": [计算],
        "最终答案": "4"
    }

# 构建图
graph = StateGraph(ReasoningState)
graph.add_node("分析", 分析问题)
graph.add_node("方案", 制定方案)
graph.add_node("计算", 执行计算)
graph.add_edge(START, "分析")
graph.add_edge("分析", "方案")
graph.add_edge("方案", "计算")
graph.add_edge("计算", END)

# 运行
result = graph.compile().invoke({"问题": "2 + 2 = ?"})

# 结果
{
    "问题": "2 + 2 = ?",
    "思考步骤": [
        "分析:2 + 2 = ?涉及数学计算",
        "方案:先计算子问题,再汇总",
        "执行:2 + 2 = 4"
    ],
    "最终答案": "4"
}

State Debugging Tips

  1. Print status change
python
def 调试节点(state):
    print(f"当前状态:{state}")
    # 你的逻辑
    result = {"新字段": "值"}
    print(f"返回数据:{result}")
    return result
  1. Tracking using LangSmith
python
# 在 LangSmith 中可以看到每个节点后的 State 快照
# 帮助理解数据流动
  1. Unit Test Node
python
# 单独测试节点函数
def test_节点():
    mock_state = {"输入": "测试数据"}
    result = 节点函数(mock_state)
    assert result == {"期望输出": "..."}

Summary: The essence of State

  1. State is the running account of data

    • Record all data from start to present -Add new data to each node
  2. State is the note transfer between nodes

    • Nodes communicate through State
    • The previous node writes and the next node reads
  3. State needs to be carefully designed

    • Include only necessary fields
    • Complex states are isolated with subgraphs
    • Use output_schema to control output
  4. State supports flexible merge strategies

    • Default coverage
    • Customize with Reducer (such as list merging)

Remember this formula:

LangGraph = 节点(处理逻辑) + 边(执行顺序) + State(数据流动)

State is the most core of the three. If you understand State, you will understand the operating principle of LangGraph!

English translation of community learning materials. MIT licensed.