Skip to content
Gains Summary
Main Navigation 首页 / Home
C++ 编程 / C++ Programming
系统与高性能 / Systems & Performance
Web 开发 / Web Development
人工智能 / Artificial Intelligence
工业软件 / Industrial Software
其他内容 / Other Topics
C++ 编程 / C++系统与性能 / SystemsWeb 开发 / Web人工智能 / AI工业软件 / Industrial

外观

Sidebar Navigation

← 人工智能 / Artificial Intelligence

智能体工程 / Agent Engineering

1. Agent 工程体系全景 / Agent Engineering System Overview

2. Function Calling - 让 LLM 具备行动能力 / Function Calling for Giving LLMs the Ability to Act

3. Agent 框架演进 - 从裸 SDK 到 LangGraph / The Evolution of Agent Frameworks from Raw SDKs to LangGraph

4. RAG 基础 - 让 Agent 拥有"知识" / Retrieval-Augmented Generation Fundamentals for Agent Knowledge

5. 记忆管理 - Agent 的大脑 / Memory Management as the Brain of an Agent

6. Agent 工作流 - 从单步到复杂的执行编排 / Agent Workflows from Single Steps to Complex Orchestration

7. 多 Agent 系统 - 多个 Agent 协作 / Multi-Agent Systems and Agent Collaboration

8. RAG 进阶 - 企业级知识库实战 / Advanced RAG for Enterprise Knowledge Bases

9. 真实 Agent 应用场景 / Real-World AI Agent Applications

10. Structured Output - 让 LLM 输出可控的结构化数据 / Structured Output for Controllable, Machine-Readable LLM Responses

11. Tools Design Best Practices - AI Agent 工具设计最佳实践 / Tools Design Best Practices for AI Agents

12. Agent 架构模式 - 从单 Agent 到多 Agent 的工程范式 / Agent Architecture Patterns

13. Agent Modes — 编程 Agent 的交互模式设计 / Designing Interaction Modes for Coding Agents

14. Agent Workflow 编排:从循环到持久化执行的演进

15. Context Engineering - 从 Prompt 设计到上下文编排 / Context Engineering: From Prompt Design to Context Orchestration

16. Agent 缓存工程:从 KV Cache、Prompt Cache 到语义缓存 / Agent Caching Engineering

17. Harness Engineering, Skills, and Loop Engineering — 从信任模型到验证系统 / From Trusting Models to Verifying Systems

18. MCP 协议 - AI 工具的"USB 接口" / Model Context Protocol for AI Tool Integration

19. Agent 评估与测试 — 如何衡量一个"不可预测"的系统 / Agent Evaluation and Testing — How to Measure an "Unpredictable" System

20. 安全沙箱 - Agent 的安全边界 / Secure Sandboxes as Agent Safety Boundaries

21. 权限与门卫 - Agent 的安全控制中枢 / Permissions and Policy Gates for Agent Control

22. API Key 管理与安全 - Agent 的密钥生命周期的管理 / API Key Lifecycle Management and Security for Agents

23. 提示词注入防护 - Agent 的防御前沿 / Prompt Injection Defense for AI Agents

24. 可观测性与调试 - Agent 运行的透明度保障 / Observability and Debugging for Transparent Agent Operations

25. 模型路由 - 让正确的模型做正确的事 / Model Routing for Matching Models to Tasks

26. OpenClaw 设计深度分析 - 为什么它让人觉得"活"了 / OpenClaw Design Analysis and the Illusion of Liveliness

27. Claude Code 泄露源码深度分析 - 512,000 行代码揭示的生产级 Agent 架构 / Claude Code Source Analysis and Production Agent Architecture

28. LobeChat 设计深度分析 - 全栈 Agent Chat 应用工程实践 / LobeChat Design Analysis and Full-Stack Agent Chat Engineering

29. 编程 Agent 全面对比:从 Claude Code 到 Pi 的设计哲学 / Coding Agents Comparison: Design Philosophies from Claude Code to Pi

30. 领域 Agent 的确定性工具编译与延迟执行——从自然语言规格到单次 CAE 提交

31. Agent 工程学习指南 / An AI Agent Engineering Learning Guide

本页目录

Agent Workflow 编排:从循环到持久化执行的演进 ​

📅 创建时间:2026-07-29 🏷️ 标签:#Workflow #Orchestration #DurableExecution #StateMachine #LangGraph 📚 前置知识:[[05-agent-workflow]] [[11-agent-architecture-patterns]]


📋 本章目标 ​

  • 理解 Agent Workflow 从简单循环到持久化编排的四代演进
  • 掌握 State Machine(LangGraph)的 Typed State + Checkpointing + Human-in-the-Loop
  • 理解 Durable Execution 的核心:Checkpointing ≠ 真正的持久化执行
  • 了解 Claude Code 动态 Workflow 的 6 种编排模式
  • 能够根据任务复杂度选择合适的 Workflow 层级

第0部分:你已有的认知——Agent Loop 就是最简单的 Workflow ​

回顾 [[01-function-calling]] 和 [[05-agent-workflow]]:

python
while finish_reason != "stop":
    response = llm.chat(messages, tools)
    if response.tool_calls:
        execute_tools(response.tool_calls)
        messages.append(tool_results)
    else:
        return response.content
1
2
3
4
5
6
7

这就是一个 Workflow——最简版。所有 Workflow 工程都在回答:这个循环崩溃了怎么办?要跑三天怎么办?需要人类审批怎么办?要协调几十个 Agent 怎么办?


第1部分:四代 Workflow 演进 ​

┌─────────────────────────────────────────────────────────────┐
│              Workflow 四代演进                                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Gen 1: Agent Loop (while 循环)                              │
│  → for batch in data: llm.call() → tool.execute()           │
│  → 单进程,崩溃就没了,无状态持久化                           │
│                                                             │
│  Gen 2: State Machine / Graph (LangGraph 式)                 │
│  → 显式 StateGraph,Typed State,checkpointing               │
│  → 暂停/恢复,人类审批,条件分支                             │
│                                                             │
│  Gen 3: Durable Execution (Temporal 式)                      │
│  → Workflow = 纯编排(确定性),Activity = 副作用(可重试)  │
│  → 崩溃自动恢复,精确一次语义,跑数天不丢任务                 │
│                                                             │
│  Gen 4: Dynamic Workflows (Claude Code /workflows)           │
│  → Agent 自己写编排脚本                                      │
│  → 16 并发 × 1000 agent 上限,可恢复                         │
│                                                             │
└─────────────────────────────────────────────────────────────┘
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

第2部分:Gen 2 — State Machine 工作流 ​

LangGraph 把 Workflow 建模为 带类型状态的有向图:

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

class ReviewState(TypedDict):
    code: str
    comments: list[str]
    approved: bool
    iteration: int

def review(state: ReviewState) -> ReviewState:
    result = llm.review(state["code"])
    return {"comments": result.comments, "approved": result.approved}

def fix(state: ReviewState) -> ReviewState:
    fixed = llm.fix(state["code"], state["comments"])
    return {"code": fixed, "iteration": state["iteration"] + 1}

def should_continue(state: ReviewState):
    if state["approved"] or state["iteration"] >= 3:
        return END
    return "fix"

graph = StateGraph(ReviewState)
graph.add_node("review", review)
graph.add_node("fix", fix)
graph.add_conditional_edges("review", should_continue, {"fix": "fix", END: END})
graph.set_entry_point("review")
app = graph.compile(checkpointer=SqliteSaver.from_conn_string("checkpoints.db"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

三个核心概念:

┌─────────────────────────────────────────────────────────────┐
│          State Machine Workflow 三要素                       │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. Typed State:不是松散 dict,是 schema 约束的对象          │
│     → 防止 LLM 产生不符合预期的状态                           │
│                                                             │
│  2. Checkpointing:每执行一个 node,状态序列化到磁盘          │
│     → 崩溃后可以从最后一个 checkpoint 恢复                    │
│                                                             │
│  3. Human-in-the-Loop:interrupt() 暂停等待人类审批           │
│     → Command(resume=...) 继续                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘
1
2
3
4
5
6
7
8
9
10
11
12
13
14

第3部分:Gen 3 — Durable Execution ​

Checkpointing ≠ 真正的持久化执行。区别:

┌─────────────────────────────────────────────────────────────┐
│    Checkpointing (LangGraph)  vs  Durable Execution (Temporal)│
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  保存状态快照               │  运行时自动检测故障             │
│  开发者手动 resume          │  自动恢复,无需人工             │
│  无内置去重                 │  精确一次执行语义               │
│  单进程                     │  分布式集群                     │
│                                                             │
│  "我帮你存了状态,你来恢复。"│  "你的工作流一定跑到完。        │
│                              │   所有事情我来处理。"           │
└─────────────────────────────────────────────────────────────┘
1
2
3
4
5
6
7
8
9
10
11
12

核心设计:Workflow vs Activity 严格分离:

python
# Workflow: 100% 确定性——只做编排,不碰外部世界
@workflow.defn
class ResearchWorkflow:
    @workflow.run
    async def run(self, topic: str):
        papers = await workflow.execute_activity(search_papers, topic)
        findings = await workflow.execute_activity(extract, papers)
        if len(findings) < 5:
            papers = await workflow.execute_activity(search_papers, topic + " expanded")
        report = await workflow.execute_activity(write_report, findings)
        approved = await workflow.wait_for_signal("human_approval")
        if not approved:
            return await self.run(topic)  # 带着反馈重来
        return report

# Activity: 唯一允许碰外部世界的地方,独立重试 + 缓存
@activity.defn
async def search_papers(topic: str) -> list[Paper]:
    return await semantic_scholar.search(topic)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

如果服务器在 write_report 时崩溃:重启后 Temporal 重放历史事件,发现 search_papers 和 extract 已经完成(返回缓存结果),直接从 write_report 继续。


第4部分:Gen 4 — Claude Code Dynamic Workflows ​

2026 年 5 月 GA。Agent 自己写 JavaScript 编排脚本。六个模式:

┌─────────────────────────────────────────────────────────────┐
│         Claude Code 六种编排模式                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. Classify-and-Act    → 分类器 → 路由到专业 Agent          │
│  2. Fan-Out-Synthesize  → 拆分 → 并行 → 汇总                │
│  3. Adversarial Verify  → 每次输出配一个反驳者               │
│  4. Generate-and-Filter → 生成多个 → 按标准筛选 → 保留最佳   │
│  5. Tournament          → 多方案竞争 → 两两评判 → 选出最优   │
│  6. Loop-Until-Done     → 循环生成直到条件满足               │
│                                                             │
│  关键差异:编排逻辑在 script 变量里,不在 LLM context 里      │
│  → 不会 context drift,不会目标漂移                          │
│                                                             │
└─────────────────────────────────────────────────────────────┘
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

第5部分:怎么选 ​

┌─────────────────────────────────────────────────────────────┐
│              Workflow 选型决策                                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  任务几分钟完成,不需要暂停      → Gen 1: while 循环          │
│  需要暂停/恢复/人类审批          → Gen 2: State Machine       │
│  跑数小时到数天,绝对不能丢      → Gen 3: Durable Execution   │
│  大规模并行,Agent 编排 Agent    → Gen 4: Dynamic Workflows   │
│                                                             │
│  关键原则:不要跳过 Gen 2/3 直接上 Gen 4。                    │
│  单步可靠性都没搞定就搞自主循环 = 最常见的事故模式。          │
│                                                             │
└─────────────────────────────────────────────────────────────┘
1
2
3
4
5
6
7
8
9
10
11
12
13

核心总结 ​

  1. Agent Loop 就是最简 Workflow。所有复杂编排都是在这个循环上加状态管理、持久化和并行。
  2. State Machine 的核心价值:Typed State 防止状态混乱,Checkpointing 支持暂停恢复,Human-in-the-Loop 引入人类判断。
  3. Checkpointing ≠ Durable Execution:存状态容易,自动恢复 + 精确一次语义才是难点。Temporal 式架构通过 Workflow/Activity 分离实现真正的持久化执行。
  4. Dynamic Workflows 把编排逻辑从 LLM 上下文移到 JavaScript 脚本里,解决了 context drift 和目标漂移。

章节测试 ​

测试1:LangGraph 的 Checkpointing 和 Temporal 的 Durable Execution 核心区别是什么? ​

A. 技术栈不同(Python vs Go) B. Checkpointing 存状态但需手动恢复,Durable Execution 自动检测故障并恢复 C. Checkpointing 速度更快 D. 没有实质区别

测试2:为什么 Durable Execution 要求 Workflow 代码是 100% 确定性的? ​

测试3:跳过 Gen 2/3 直接上 Gen 4(Dynamic Workflows)为什么危险? ​


参考答案 ​

测试1答案 ​

答案:B。Checkpointing = "我帮你存了,你来恢复"。Durable Execution = "我一定帮你跑到完,所有事情我来处理"。后者多了一层自动故障检测、恢复和去重。

测试2答案 ​

Workflow 代码在崩溃恢复时会被重放。如果 Workflow 里有非确定性操作(time.now()、随机数、直接调 HTTP),重放时会产生不同的结果,破坏状态一致性。所有副作用必须隔离在 Activity 里,Activity 的结果被缓存,重放时直接返回缓存值。

测试3答案 ​

Dynamic Workflows 的可靠性依赖单次 Agent 调用的可靠性。如果单个 Agent 的工具调用准确率、状态管理、错误处理这些 Harness 层(Gen 2/3)的问题没解决,并行 1000 个 Agent 只会放大错误而不是提高效率。"没搞定单次可靠性就搞自主循环"是 2025-2026 业界公认的最常见反模式。


相关笔记 ​

  • [[05-agent-workflow]] — ReAct、Plan-Execute 基础
  • [[11-agent-architecture-patterns]] — Prompt Chaining 等五种模式
  • [[15-harness-loop-skills]] — Loop Engineering 的六构建块

下一步学习 ​

  • [ ] 用 LangGraph 写一个带 Human-in-the-Loop 审批的代码审查 Workflow
  • [ ] 对比 LangGraph checkpoint 和 Temporal workflow 在崩溃恢复上的行为差异
  • [ ] 用 Claude Code /workflows 跑一次 Fan-Out-Synthesize

学习状态:🟡 开始学习

最后更新于:

Pager
上一篇13. Agent Modes — 编程 Agent 的交互模式设计 / Designing Interaction Modes for Coding Agents
下一篇15. Context Engineering - 从 Prompt 设计到上下文编排 / Context Engineering: From Prompt Design to Context Orchestration

持续记录,持续成长

Copyright © Tidenflow