langgraph
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLangGraph Workflow Patterns
LangGraph工作流模式
Comprehensive patterns for building production LangGraph workflows. Each category has individual rule files in loaded on-demand.
rules/用于构建生产级LangGraph工作流的全面模式集合。每个分类都有独立的规则文件存储在目录中,可按需加载。
rules/Quick Reference
快速参考
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| State Management | 4 | CRITICAL | Designing workflow state schemas, accumulators, reducers |
| Routing & Branching | 3 | HIGH | Dynamic routing, retry loops, semantic routing |
| Parallel Execution | 3 | HIGH | Fan-out/fan-in, map-reduce, concurrent agents |
| Supervisor Patterns | 3 | HIGH | Central coordinators, round-robin, priority dispatch |
| Tool Calling | 4 | CRITICAL | Binding tools, ToolNode, dynamic selection, approvals |
| Checkpointing | 3 | HIGH | Persistence, recovery, cross-thread Store memory |
| Human-in-Loop | 3 | MEDIUM | Approval gates, feedback loops, interrupt/resume |
| Streaming | 3 | MEDIUM | Real-time updates, token streaming, custom events |
| Subgraphs | 3 | MEDIUM | Modular composition, nested graphs, state mapping |
| Functional API | 3 | MEDIUM | @entrypoint/@task decorators, migration from StateGraph |
Total: 32 rules across 10 categories
State Management
状态管理
State schemas determine how data flows between nodes. Wrong schemas cause silent data loss.
| Rule | File | Key Pattern |
|---|---|---|
| TypedDict State | | |
| Pydantic Validation | | |
| MessagesState | | |
| Custom Reducers | | |
状态 schema 决定了数据在节点间的流动方式。错误的 schema 会导致无提示的数据丢失。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| TypedDict 状态 | | |
| Pydantic 验证 | | 边界使用 |
| MessagesState | | |
| 自定义归约器 | | |
Routing & Branching
路由与分支
Control flow between nodes. Always include END fallback to prevent hangs.
| Rule | File | Key Pattern |
|---|---|---|
| Conditional Edges | | |
| Retry Loops | | Loop-back edges with max retry counter |
| Semantic Routing | | Embedding similarity or |
控制节点间的数据流。务必包含END分支回退,避免工作流挂起。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 条件边 | | 使用 |
| 重试循环 | | 带最大重试计数器的循环边 |
| 语义路由 | | 基于嵌入相似度或 |
Parallel Execution
并行执行
Run independent nodes concurrently. Use to accumulate results.
Annotated[list, add]| Rule | File | Key Pattern |
|---|---|---|
| Fan-Out/Fan-In | | |
| Map-Reduce | | |
| Error Isolation | | |
并发运行独立节点。使用累加结果。
Annotated[list, add]| 规则 | 文件 | 核心模式 |
|---|---|---|
| 扇出/扇入 | | 使用 |
| Map-Reduce | | |
| 错误隔离 | | |
Supervisor Patterns
监督者模式
Central coordinator routes to specialized workers. Workers return to supervisor.
| Rule | File | Key Pattern |
|---|---|---|
| Basic Supervisor | | |
| Priority Routing | | Priority dict ordering agent execution |
| Round-Robin | | Completion tracking with |
中央协调器将任务路由至专用工作者节点,工作者执行后返回至协调器。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 基础监督者 | | 使用 |
| 优先级路由 | | 基于优先级字典排序Agent执行顺序 |
| 轮询调度 | | 用 |
Tool Calling
工具调用
Integrate function calling into LangGraph agents. Keep tools under 10 per agent.
| Rule | File | Key Pattern |
|---|---|---|
| Tool Binding | | |
| ToolNode Execution | | |
| Dynamic Selection | | Embedding-based tool relevance filtering |
| Tool Interrupts | | |
将函数调用集成到LangGraph Agent中。每个Agent关联的工具数量建议不超过10个。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 工具绑定 | | |
| ToolNode 执行 | | |
| 动态选择 | | 基于嵌入的工具相关性过滤 |
| 工具中断 | | 使用 |
Checkpointing
检查点
Persist workflow state for recovery and debugging.
| Rule | File | Key Pattern |
|---|---|---|
| Checkpointer Setup | | |
| State Recovery | | |
| Cross-Thread Store | | |
持久化工作流状态以支持恢复与调试。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 检查点设置 | | 开发环境用 |
| 状态恢复 | | |
| 跨线程存储 | | 使用 |
Human-in-Loop
人机协同
Pause workflows for human intervention. Requires checkpointer for state persistence.
| Rule | File | Key Pattern |
|---|---|---|
| Interrupt/Resume | | |
| Approval Gate | | |
| Feedback Loop | | Iterative interrupt until approved |
暂停工作流以等待人工干预。需要检查点来实现状态持久化。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 中断/恢复 | | |
| 审批网关 | | |
| 反馈循环 | | 迭代中断直至获得批准 |
Streaming
流式传输
Real-time updates and progress tracking for workflows.
| Rule | File | Key Pattern |
|---|---|---|
| Stream Modes | | 5 modes: values, updates, messages, custom, debug |
| Token Streaming | | |
| Custom Events | | |
为工作流提供实时更新与进度跟踪。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 流式模式 | | 5种模式:values、updates、messages、custom、debug |
| Token 流式传输 | | 带节点/标签过滤的 |
| 自定义事件 | | 使用 |
Subgraphs
子图
Compose modular, reusable workflow components with nested graphs.
| Rule | File | Key Pattern |
|---|---|---|
| Invoke from Node | | Different schemas, explicit state mapping |
| Add as Node | | Shared state, |
| State Mapping | | Boundary transforms between parent/child |
通过嵌套图组合模块化、可复用的工作流组件。
| 规则 | 文件 | 核心模式 |
|---|---|---|
| 从节点调用 | | 独立schema,显式状态映射 |
| 作为节点添加 | | 共享状态, |
| 状态映射 | | 父图/子图间的边界转换 |
Functional API
函数式API
Build workflows using and decorators instead of explicit graph construction.
@entrypoint@task| Rule | File | Key Pattern |
|---|---|---|
| @entrypoint | | Workflow entry point with optional checkpointer |
| @task | | Returns futures, |
| Migration | | |
使用和装饰器构建工作流,替代显式的图构造方式。
@entrypoint@task| 规则 | 文件 | 核心模式 |
|---|---|---|
| @entrypoint | | 带可选检查点的工作流入口 |
| @task | | 返回futures,使用 |
| 迁移指南 | | 从 |
Quick Start Example
快速开始示例
python
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command
from typing import TypedDict, Annotated, Literal
from operator import add
class State(TypedDict):
input: str
results: Annotated[list[str], add]
def supervisor(state) -> Command[Literal["worker", END]]:
if not state.get("results"):
return Command(update={"input": state["input"]}, goto="worker")
return Command(goto=END)
def worker(state) -> dict:
return {"results": [f"Processed: {state['input']}"]}
graph = StateGraph(State)
graph.add_node("supervisor", supervisor)
graph.add_node("worker", worker)
graph.add_edge(START, "supervisor")
graph.add_edge("worker", "supervisor")
app = graph.compile()python
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command
from typing import TypedDict, Annotated, Literal
from operator import add
class State(TypedDict):
input: str
results: Annotated[list[str], add]
def supervisor(state) -> Command[Literal["worker", END]]:
if not state.get("results"):
return Command(update={"input": state["input"]}, goto="worker")
return Command(goto=END)
def worker(state) -> dict:
return {"results": [f"Processed: {state['input']}"]}
graph = StateGraph(State)
graph.add_node("supervisor", supervisor)
graph.add_node("worker", worker)
graph.add_edge(START, "supervisor")
graph.add_edge("worker", "supervisor")
app = graph.compile()2026 Key Patterns
2026核心模式
- Command API: Use when updating state AND routing together
Command(update=..., goto=...) - context_schema: Pass runtime config (temperature, provider) without polluting state
- CachePolicy: Cache expensive node results with TTL via
InMemoryCache - RemainingSteps: Proactively handle recursion limits
- Store: Cross-thread memory separate from Checkpointer (thread-scoped)
- interrupt(): Dynamic interrupts inside node logic (replaces for conditional cases)
interrupt_before - add_edge(START, node): Not (deprecated)
set_entry_point()
- Command API: 同时更新状态和路由时使用
Command(update=..., goto=...) - context_schema: 传递运行时配置(温度、提供商),避免污染状态
- CachePolicy: 通过为耗时节点结果添加TTL缓存
InMemoryCache - RemainingSteps: 主动处理递归限制
- Store: 与检查点分离的跨线程内存(线程作用域)
- interrupt(): 在节点逻辑内实现动态中断(替代条件场景下的)
interrupt_before - add_edge(START, node): 替代已弃用的
set_entry_point()
Key Decisions
关键决策指南
| Decision | Recommendation |
|---|---|
| State type | TypedDict internally, Pydantic at boundaries |
| Entry point | |
| Routing + state update | Command API |
| Routing only | Conditional edges |
| Accumulators | |
| Dev checkpointer | MemorySaver |
| Prod checkpointer | PostgresSaver |
| Short-term memory | Checkpointer (thread-scoped) |
| Long-term memory | Store (cross-thread, namespaced) |
| Max parallel branches | 5-10 concurrent |
| Tools per agent | 5-10 max (dynamic selection for more) |
| Approval gates | |
| Stream modes | |
| Subgraph pattern | Invoke for isolation, Add-as-Node for shared state |
| Functional vs Graph | Functional for simple flows, Graph for complex topology |
| 决策项 | 推荐方案 |
|---|---|
| 状态类型 | 内部使用TypedDict,边界使用Pydantic |
| 入口配置 | 使用 |
| 路由+状态更新 | 使用Command API |
| 仅路由 | 使用条件边 |
| 累加器 | 始终使用 |
| 开发环境检查点 | MemorySaver |
| 生产环境检查点 | PostgresSaver |
| 短期内存 | 检查点(线程作用域) |
| 长期内存 | Store(跨线程、命名空间隔离) |
| 最大并行分支数 | 5-10个并发 |
| 单Agent工具数量 | 最多5-10个(更多工具使用动态选择) |
| 审批网关 | 高风险操作使用 |
| 流式模式 | 多数UI场景使用 |
| 子图模式 | 隔离场景用调用模式,共享状态场景用添加为节点模式 |
| 函数式vs图API | 简单流用函数式,复杂拓扑用图API |
Common Mistakes
常见错误
- Forgetting reducer (overwrites instead of accumulates)
add - Mutating state in place (breaks checkpointing)
- No END fallback in routing (workflow hangs)
- Infinite retry loops (no max counter)
- Side effects in router functions
- Too many tools per agent (context overflow)
- Raising exceptions in tools (crashes agent loop)
- No checkpointer in production (lose progress on crash)
- Wrapping in try/except (breaks the mechanism)
interrupt() - Not transforming state at subgraph boundaries
- Forgetting on Functional API tasks
.result() - Using (deprecated, use
set_entry_point())add_edge(START, ...)
- 遗漏归约器(覆盖而非累加结果)
add - 原地修改状态(破坏检查点机制)
- 路由未设置END回退(工作流挂起)
- 无限重试循环(未设置最大计数器)
- 路由函数中包含副作用
- 单Agent绑定过多工具(上下文溢出)
- 工具中抛出异常(导致Agent循环崩溃)
- 生产环境未配置检查点(崩溃时丢失进度)
- 用try/except包裹(破坏中断机制)
interrupt() - 子图边界未做状态转换
- 函数式API任务遗漏
.result() - 使用已弃用的(应使用
set_entry_point())add_edge(START, ...)
Evaluations
测试验证
See for consolidated test cases across all categories.
test-cases.json所有分类的综合测试用例请参考。
test-cases.jsonRelated Skills
相关技能
- - Higher-level multi-agent coordination, ReAct loop patterns, and framework comparisons
agent-orchestration - - Durable execution alternative
temporal-io - - General LLM function calling
llm-integration - - Pydantic model patterns
type-safety-validation
- - 更高阶的多Agent协调、ReAct循环模式及框架对比
agent-orchestration - - 持久化执行替代方案
temporal-io - - 通用LLM函数调用
llm-integration - - Pydantic模型模式
type-safety-validation