中文译本。原文见同目录 README.md

第 6 课:规划与推理(Planning and Reasoning)——智能体如何应对复杂任务

你将学到什么

  • 为什么处理复杂任务的智能体必须做规划(planning)
  • 智能体问题解决循环:Get Mission(获取任务)、Scan Scene(扫描场景)、Think(思考)、Act(行动)、Observe(观察)
  • Plan-then-execute(先规划再执行)与 reactive(反应式)方法及其权衡
  • 分层规划(hierarchical planning):把大任务拆成可管理的小块
  • 再规划(re-planning):事情出错时智能体如何适应
  • 推理技术:Chain-of-Thought(思维链)、Tree-of-Thoughts(思维树)与 self-consistency(自洽性)
  • 编排层(orchestration layer)在管理计划中的角色
  • 常见失败模式及如何避免

前置条件


ELI5:规划就像为旅行打包

想象你要为两周旅行打包。你可以随便抓东西塞进箱子。也许运气好,需要的都有了。更可能的是:忘了牙刷,却带了三件永远不穿的外套。

更好的做法:先想清楚去哪、天气怎样、安排了哪些活动,然后列打包清单。边装边勾掉。如果中途发现空间不够,就重新排优先级——丢掉「以防万一」的东西,留下必需品。

这就是规划对 AI 智能体的作用。智能体不是对每一步盲目反应,而是提前思考、制定计划,并系统地推进。计划卡住时,好的智能体会调整,而不是沿错误路径硬冲。


为什么规划很重要

简单任务不需要规划。如果有人问「现在几点?」,智能体看一下时钟就行。不需要计划。

但考虑这样的请求:「调研云数据库市场前 5 名竞品,比较价格与功能,并写出我们新项目该用哪一家的建议。」

这个任务需要:

  • 识别竞品是谁
  • 分别调研(价格、功能、限制)
  • 理解用户的项目需求
  • 对照需求比较选项
  • 综合成一份建议

没有规划,智能体可能把某一家竞品研究得极细,上下文空间用尽,却忘了覆盖另外四家。或者直接跳到建议,却没做充分调研。

规划给智能体一张路线图。它知道要去哪、下一步是什么、如何分配时间与资源。

规划能带来什么

收益 没有规划 有规划
任务完成 可能漏步骤或卡住 系统覆盖所有步骤
资源效率 在枝节上浪费 tokens 把精力用在刀刃上
透明度 很难看清智能体在做什么 清晰的进度追踪
错误恢复 出错后迷失 能定位计划哪里断了并调整
并行 一切串行 独立步骤可并发

智能体问题解决循环

每个规划型智能体的核心都是一个问题解决循环。不同框架描述不同,但核心步骤一致:

Get Mission -> Scan Scene -> Think -> Act -> Observe

+-------------------------------------------------------------------+
|                                                                   |
|   +------------+     +------------+     +---------+               |
|   | Get Mission| --> | Scan Scene | --> |  Think  |               |
|   +------------+     +------------+     +----+----+               |
|                                              |                    |
|                                              v                    |
|                        +---------+     +-----+-----+              |
|                        | Observe | <-- |    Act     |             |
|                        +----+----+     +-----------+              |
|                             |                                     |
|                             v                                     |
|                      +------+------+                              |
|                      | Goal met?   |                              |
|                      | Yes -> Done |                              |
|                      | No -> Think |                              |
|                      +-------------+                              |
|                                                                   |
+-------------------------------------------------------------------+

逐步说明

1. Get Mission(获取任务)

智能体收到任务。可能是用户请求、触发事件,或其他智能体委派的子任务。

Mission: "Create a summary report of our team's GitHub activity this week."

2. Scan Scene(扫描场景)

智能体收集当前处境的上下文。有哪些工具可用?已有什么信息?有哪些约束?

Available tools: github_api, document_writer, calendar_api
Known context: Team = "platform-eng", Current date = March 15
Constraints: Report should be under 2 pages

3. Think(思考)

智能体推理下一步做什么。规划发生在这里——考虑选项并决定行动路线。

Thought: "I need to:
  1. Get the list of team members
  2. For each member, fetch their commits, PRs, and reviews this week
  3. Aggregate the data
  4. Write a summary highlighting key contributions
  I will start by getting the team member list."

4. Act(行动)

智能体执行动作——调用工具、生成文本或做决策。

Action: github_api.get_team_members(team="platform-eng")

5. Observe(观察)

智能体检查行动结果。成功了吗?提供了什么信息?计划需要改吗?

Observation: Team has 8 members: [alice, bob, carol, dave, eve, frank, grace, hank]

然后循环回到 Think,智能体根据观察决定下一步。直到任务完成。


Plan-then-execute vs. Reactive 方法

智能体处理任务有两种基本哲学。多数真实智能体会混合二者,但理解纯形式有助于做设计决策。

Plan-then-execute(先规划再执行)

如何工作: 智能体在采取任何行动之前先制定完整(或接近完整)的计划,然后逐步执行。

User: "Migrate our application from Python 2 to Python 3."

Planning phase:
  Step 1: Audit codebase for Python 2-specific syntax
  Step 2: Identify incompatible dependencies
  Step 3: Update dependencies to Python 3-compatible versions
  Step 4: Convert print statements to print functions
  Step 5: Fix string/unicode handling
  Step 6: Update integer division operators
  Step 7: Run test suite and fix failures
  Step 8: Update CI/CD pipeline to use Python 3

Execution phase:
  [Execute steps 1-8 in order]

优点:

  • 结构清晰,便于进度追踪
  • 可提前识别步骤间依赖
  • 支持独立步骤并行执行
  • 易于估算总工作量并沟通进度

缺点:

  • 计划可能错误或不完整(你不知道自己不知道什么)
  • 僵硬——难以应对意外
  • 前期规划消耗时间与 tokens
  • 简单任务可能过度规划

Reactive(反应式)方法

如何工作: 智能体一步一步来。看当前情况,决定最佳下一步,执行,再重新评估。本质上就是 第 4 课 中的 ReAct 模式。

User: "Migrate our application from Python 2 to Python 3."

Step 1:
  Think: "First, I should understand the codebase. Let me scan for Python 2 syntax."
  Act: Search for Python 2 patterns
  Observe: Found 47 print statements, 12 unicode issues, 3 deprecated imports

Step 2:
  Think: "The print statements are the most common issue. Let me start there."
  Act: Convert print statements
  Observe: 47 print statements converted

Step 3:
  Think: "Now let me tackle the unicode issues..."
  [continues step by step]

优点:

  • 高度自适应——根据实际发现做出反应
  • 不浪费规划精力
  • 适合探索性任务
  • 自然应对意外

缺点:

  • 缺少大局进度视图
  • 可能漏掉前期规划本可捕获的重要步骤
  • 难以并行——每步依赖上一次观察
  • 没有引导计划时可能跑偏

务实的中间路线

多数生产智能体采用混合方法:

  1. 轻度前期规划: 制定粗略高层计划(3–7 步)
  2. 反应式执行: 在每一步内使用 ReAct 风格推理
  3. 定期再规划: 重大步骤之后重新评估并调整计划
High-level plan (light):
  1. Audit the codebase
  2. Fix syntax issues
  3. Update dependencies
  4. Run tests and fix failures

Executing step 1 (reactive):
  Think -> Act -> Observe -> Think -> Act -> Observe -> Step complete

Re-plan after step 1:
  "The audit revealed more issues than expected. Adding step 2b for
   database migration code that uses a deprecated library."

这样既有规划的结构,又有反应式执行的适应力。

何时偏向哪种方法

情境 偏向规划 偏向反应式
任务已被充分理解 是
任务偏探索性 是
有多个独立子任务 是
对将发现什么高度不确定 是
需要沟通进度 是
速度比完备性更重要 是
失败代价高 是
任务简单(少于 3 步) 是

Planning Strategy Simulator

Task: "Research and compare the top 3 JavaScript frameworks"


分层规划(Hierarchical planning)

把大任务拆成小任务

有些任务太复杂,无法用一张扁平清单规划。分层规划把大目标拆成子目标,再拆成更细的子子目标——类似项目管理中的工作分解结构(WBS)。

项目管理类比

想想软件项目如何组织:

Epic: Launch new payment system
  |
  +-- Story: Design payment API
  |     +-- Task: Define endpoints
  |     +-- Task: Design data models
  |     +-- Task: Write API specification
  |
  +-- Story: Implement payment processing
  |     +-- Task: Integrate with payment gateway
  |     +-- Task: Handle error cases
  |     +-- Task: Add retry logic
  |
  +-- Story: Add monitoring and alerts
        +-- Task: Set up logging
        +-- Task: Define SLOs
        +-- Task: Configure alert rules

智能体使用同样结构。例如,「写一篇关于 Kubernetes 网络的博文」可拆成:

Sub-goal 1: Research
  Task 1.1: Identify key networking concepts
  Task 1.2: Find recent developments and best practices

Sub-goal 2: Outline and Write
  Task 2.1: Create section structure
  Task 2.2: Write each section with code examples

Sub-goal 3: Review
  Task 3.1: Check technical accuracy
  Task 3.2: Verify code examples work

分层规划的好处

  • 可管理的块。 每个任务小到足以在不丢焦点的情况下执行。
  • 清晰的依赖。 能看出哪些任务依赖其他任务,哪些可并行。
  • 进度追踪。 准确知道自己在整体计划中的位置。
  • 委派。 在多智能体系统中,不同子目标可交给专长不同的智能体。

抽象层级

层级 描述什么 示例
Goal(目标) 成功长什么样 「把应用部署到生产」
Sub-goal(子目标) 工作的主要阶段 「准备环境」
Task(任务) 具体行动 「创建 Cloud Run 服务」
Step(步骤) 原子操作 「运行 gcloud run deploy」

智能体通常在子目标与任务层做规划。步骤由每个任务内的 ReAct 风格执行处理。


再规划:事情出错时如何适应

没有任何计划能在第一次接触现实后完整存活。好的智能体会发现计划失败并调整。

何时再规划

触发 示例 响应
任务失败 API 返回错误 尝试替代方案,或跳过稍后再处理
新信息 发现数据库 schema 与预期不同 更新计划以匹配实际 schema
需求变更 用户中途加了新需求 把新需求纳入计划
资源约束 上下文空间或 API 配额不足 简化剩余步骤
依赖被阻塞 所需服务宕机 重排任务,先做未阻塞项

再规划策略

1. 局部调整(Local adjustment)

只修眼前问题,不改整体计划。

Original plan step: "Query the users table for active accounts"
Failure: "Table 'users' does not exist"
Adjustment: "Query the 'accounts' table instead (it has the same data)"

2. 步骤插入(Step insertion)

为意外情况增加新步骤。

Original plan:
  1. Fetch data
  2. Process data
  3. Generate report

After discovering data needs cleaning:
  1. Fetch data
  1b. Clean and validate data    <-- inserted
  2. Process data
  3. Generate report

3. 计划修订(Plan revision)

根据所学显著重构剩余计划。

Original plan: "Migrate the monolith to microservices"
After analysis: "The codebase is too tightly coupled for a direct migration."
Revised plan: "First, introduce module boundaries within the monolith
               (strangler fig pattern), then gradually extract services."

4. 目标修改(Goal modification)

极端情况下,智能体认识到原目标不可达,并提出修订目标。例如,目标是「把延迟降到 50ms 以下」,但单次数据库查询就要 80ms,智能体可能建议把目标定为 100ms,并对高频端点加缓存。

关键原则:先尝试局部修复;只有局部修复不可行时,才重构剩余计划。


推理技术

规划需要推理——合乎逻辑地思考问题的能力。若干技术能帮助智能体更有效地推理。

Chain-of-Thought(CoT,思维链)

是什么: 智能体逐步推进问题,在每个阶段展示推理。不是直接跳到答案,而是「大声思考」。

类比: 数学考试展示解题过程。不只写答案,而是写出每一步计算。

Without Chain-of-Thought:
  Q: "If a server handles 100 requests/second and we need to handle 10,000
      requests/second, how many servers do we need?"
  A: "100 servers"

With Chain-of-Thought:
  Q: [same question]
  A: "Let me work through this:
      - One server handles 100 requests/second
      - We need 10,000 requests/second total
      - 10,000 / 100 = 100 servers for the raw capacity
      - But we should account for redundancy. With N+1 redundancy, we need 101.
      - And servers do not run at 100% efficiency. At 80% target utilization:
        10,000 / (100 * 0.8) = 125 servers
      - With N+1 redundancy: 126 servers
      Answer: 126 servers for production, assuming 80% target utilization
              and N+1 redundancy."

逐步推理能抓住仓促答案会漏掉的细节(冗余、利用率)。

何时使用 CoT:

  • 数学与逻辑问题
  • 多步推理
  • 中间步骤很重要的任务
  • 调试与根因分析

Tree-of-Thoughts(ToT,思维树)

是什么: 不是只走一条推理链,而是探索多条可能路径,并评估哪条最有希望。像在承诺一条路径之前先头脑风暴多种方案。

类比: 棋手考虑几种可能走法,对每种向前多想几步,再选最佳路径。

Problem: "Our API is timing out under load. How should we fix it?"

Branch 1: Add caching
  -> Evaluate: "Would reduce database load by ~60%. Implementation
     takes 2 days. Risk: cache invalidation complexity."
  Score: 7/10

Branch 2: Optimize database queries
  -> Evaluate: "Could improve query time by ~40%. Implementation
     takes 3 days. Risk: low, well-understood approach."
  Score: 6/10

Branch 3: Add horizontal scaling
  -> Evaluate: "Handles any load level. Implementation takes 1 day
     with Kubernetes. Risk: increases infrastructure cost."
  Score: 8/10

Decision: Start with horizontal scaling (fastest win), then add
          caching for long-term efficiency.

何时使用 ToT:

  • 有多种有效方法的问题
  • 战略决策
  • 第一个想法未必最好的任务
  • 架构与设计决策

Self-consistency(自洽性)

是什么: 智能体用不同推理路径多次求解同一问题,再检查答案是否一致。多数路径得到同一结论则置信度高;若分歧,则需要更多调查。

类比: 问三个不同修车师傅同一个车问题。若都说「发电机坏了」,你可以较有把握。若各说各的,就需要更多诊断。

Problem: "Is this code change safe to deploy on a Friday?"

Reasoning path 1 (risk analysis):
  "The change modifies the payment flow. Payment changes on Friday
   mean weekend incidents. Verdict: No."

Reasoning path 2 (scope analysis):
  "The change is 5 lines and has 95% test coverage. Small, well-tested
   changes are low risk. Verdict: Yes, with monitoring."

Reasoning path 3 (historical analysis):
  "Similar changes in the past have caused issues 15% of the time.
   That is above our 10% threshold. Verdict: No."

Consensus: 2 out of 3 say No. Recommendation: Wait until Monday.

何时使用自洽性:

  • 高风险决策
  • 错误代价高的任务
  • 没有单一明确答案的模糊问题
  • 关键推理的验证

推理技术对比

技术 方法 优势 成本 最适合
Chain-of-Thought 逐步线性 完备性 1x(单次) 多数推理任务
Tree-of-Thoughts 探索多路径 找到最佳方案 3–5x(多分支) 战略决策
Self-consistency 多次独立尝试 置信度校准 3–5x(多遍) 高风险验证

编排层(Orchestration layer)

编排层是管理智能体如何规划、推理与执行的控制系统。可以把它想成乐队指挥——不演奏任何乐器,但决定谁在何时演奏什么。

编排层做什么

+----------------------------------------------------------+
|                   ORCHESTRATION LAYER                    |
|                                                          |
|  +----------+  +-----------+  +----------+  +--------+  |
|  | Plan     |  | Execute   |  | Monitor  |  | Re-plan|  |
|  | Manager  |  | Engine    |  | & Eval   |  | Logic  |  |
|  +----------+  +-----------+  +----------+  +--------+  |
|                                                          |
|  Responsibilities:                                       |
|  - Break goals into executable steps                     |
|  - Decide execution order and parallelism                |
|  - Route steps to the right tools or sub-agents          |
|  - Track progress and state                              |
|  - Detect failures and trigger re-planning               |
|  - Manage context window usage                           |
|  - Enforce guardrails and safety checks                  |
+----------------------------------------------------------+

实践中的编排

在 Google Cloud 的 Vertex AI Agent Engine 中,编排层负责:

  • 路由(Routing): 把用户请求导向正确的智能体或工具
  • 状态管理(State management): 追踪智能体在计划中的位置
  • 工具执行(Tool execution): 调用工具并处理结果
  • 错误处理(Error handling): 捕获失败并决定如何恢复
  • 上下文管理(Context management): 保持上下文窗口有序

Agent Development Kit(ADK) 提供定制编排行为的构建块。你定义智能体的工具、指令与行为——框架处理执行循环。

关键编排决策

决策 选项 权衡
前期规划多少 完整计划 vs. 只下一步 完备性 vs. 灵活性
何时再规划 每步之后 vs. 仅失败时 适应性 vs. 开销
如何处理失败 重试、跳过、中止或再规划 韧性 vs. 成本
串行 vs. 并行 一次一步 vs. 并发 简洁 vs. 速度
展示多少推理 仅内部 vs. 暴露给用户 透明度 vs. 噪声

常见失败模式

即使设计良好的规划智能体也可能以可预期的方式失败。了解这些失败模式有助于建立防御。

1. 无限循环(Infinite loops)

发生什么: 智能体卡在重复同一动作,或无止境地再规划却毫无进展。

示例:

Think: "I need to find the user's email. Let me search the database."
Act: search_database(query="user email")
Observe: No results found.
Think: "I need to find the user's email. Let me search the database."
Act: search_database(query="user email")
Observe: No results found.
[repeats forever]

预防:

  • 为任何循环设置最大迭代次数
  • 追踪已采取的动作并检测重复
  • 同一动作失败 N 次后,强制尝试不同方法
  • 包含「优雅放弃」选项——向用户求助

2. 计划漂移(Plan drift)

发生什么: 智能体逐渐偏离原目标,跟着有趣的枝节走,而不是保持在轨道上。

示例:

Original goal: "Write a summary of Q4 sales performance"
Step 1: Fetch Q4 sales data [on track]
Step 2: Notice an anomaly in November data [slightly off track]
Step 3: Deep dive into November anomaly [drifting]
Step 4: Research industry trends that might explain the anomaly [lost]
Step 5: Write a report about industry trends [completely off track]

预防:

  • 定期检查:「我正在做的是否与原目标对齐?」
  • 在每一步推理中包含原目标
  • 在计划中设定范围边界
  • 用单独的评估步骤检查相关性

3. 简单任务过度规划(Over-planning)

发生什么: 智能体花在规划上的时间比直接做任务还多。

示例:

User: "What is 2 + 2?"

Agent Plan:
  Step 1: Identify the mathematical operation (addition)
  Step 2: Identify the operands (2 and 2)
  Step 3: Verify the operands are valid numbers
  Step 4: Perform the addition
  Step 5: Verify the result
  Step 6: Format the response

[Just say "4"!]

预防:

  • 决定是否规划前先估计任务复杂度
  • 简单任务(单步、答案明确)应完全跳过规划
  • 设定与任务复杂度成比例的规划时间预算

4. 级联失败(Cascading failures)

发生什么: 一步失败引发后续步骤连锁失败,智能体却未发现根因。

示例:

Step 1: Fetch user profile -> Returns error (auth expired)
Step 2: Process user preferences -> Fails (no profile data)
Step 3: Generate recommendations -> Fails (no preferences)
Step 4: Format output -> Fails (no recommendations)
Agent: "I was unable to complete the task due to formatting errors."
  [Wrong! The real problem was expired authentication in step 1]

预防:

  • 把每一步输出当作下一步的输入校验
  • 失败时回溯找根因
  • 对关键依赖快速失败,而不是在没有它们时硬继续
  • 报告真正的根因,而不只是最新症状

5. 上下文耗尽(Context exhaustion)

发生什么: 计划及其执行历史填满上下文窗口,留给智能体推理当前步骤的空间不足。

预防:

  • 摘要已完成步骤,而不是保留全部细节
  • 把中间结果外置存储,用 ID 引用
  • 为上下文做预算:为当前步骤推理预留固定空间
  • 详见 第 5 课:记忆与上下文

失败模式小结

失败模式 症状 关键预防
无限循环 同一动作重复 最大迭代次数 + 重复检测
计划漂移 智能体跑题 定期目标对齐检查
过度规划 简单任务规划过多 规划前估计复杂度
级联失败 报告了错误根因 失败时回溯 + 快速失败
上下文耗尽 智能体失去连贯性 上下文预算 + 摘要

综合示例:实践中的组合

以下是一个浓缩示例,展示规划、推理与再规划如何结合:

User: "Analyze our error logs from the past week and create Jira tickets
       for the top issues."

PLAN:
  Phase 1: Query error logs (past 7 days, ERROR + FATAL severity)
  Phase 2: Group by type, rank by frequency, identify top 5
  Phase 3: For each issue, check for existing tickets, create if new
  Phase 4: Summarize findings

EXECUTE (ReAct within each phase):
  Act: log_query(severity=["ERROR","FATAL"], days=7)
  Observe: 12,847 entries returned
  Act: log_analyze(group_by="error_message", sort="count_desc")
  Observe: Top issues identified (connection timeouts, null pointer, rate limits)

  Act: jira_search(query="Connection timeout payment-service")
  Observe: No existing ticket -> Create new ticket PLATFORM-1234

RE-PLAN (mid-execution):
  Observe: PLATFORM-999 already exists for NullPointerException
  Adjust: Update existing ticket with new occurrence count instead of creating duplicate

DELIVER:
  "Analyzed 12,847 errors. Created 4 new tickets, updated 1 existing one."

注意:智能体前期用分层规划,每阶段内用 ReAct 风格执行,发现已有工单时再规划。所有模式协同工作。


关键要点

  1. 规划把复杂任务变成可管理步骤。 没有它,智能体要么漏掉重要步骤,要么在枝节上浪费力气。

  2. 问题解决循环(Mission, Scene, Think, Act, Observe)是每个规划智能体的引擎。 理解这个循环有助于设计与调试智能体行为。

  3. Plan-then-execute 与 reactive 是光谱的两端。 多数实用智能体采用混合:轻度前期规划 + 反应式执行。

  4. 分层规划处理复杂任务,拆成目标、子目标、任务与步骤。这与项目管理的方式一致。

  5. 再规划必不可少。 计划会破裂。好的智能体尽早发现失败并调整。适应能力把有用智能体与脆弱智能体区分开。

  6. 推理技术(CoT、ToT、自洽性)让规划更有效。 CoT 用于逐步逻辑,ToT 用于探索备选,自洽性用于验证关键决策。

  7. 警惕常见失败模式。 无限循环、计划漂移、过度规划、级联失败与上下文耗尽是可预期、有已知解法的问题。

  8. 编排层把一切串起来。 它管理计划生命周期、路由执行、处理错误,并让智能体保持在轨道上。


延伸阅读


下一课: 多智能体系统