智能Agent的规划与推理:从ReAct到Tree-of-Thought的任务分解策略

一、Agent"迷路"的困境:复杂任务下的推理坍塌
大语言模型驱动的 Agent 在单步决策中表现尚可,但面对多步骤、多分支的复杂任务时,推理链常常在中途断裂或陷入循环。一个典型场景:让 Agent 完成"调研某技术方案并输出对比报告",它可能在第一步就迷失方向——是先搜索资料,还是先确定评估维度?即使开始了推理,也容易在中间步骤偏离目标,产生"幻觉行动"或重复调用同一工具。
根本原因在于:LLM 的自回归生成本质上是线性的,而复杂任务需要树状或图状的推理结构。ReAct(Reasoning + Acting)范式通过交替"思考-行动-观察"缓解了部分问题,但在长链推理中仍会累积误差。Tree-of-Thought(ToT)将推理空间扩展为搜索树,却带来了计算成本的指数增长。如何在推理深度与计算效率之间找到平衡,是构建可靠 Agent 的核心挑战。
二、推理范式演进:从线性链到搜索树的底层机制
2.1 三种推理范式的对比
graph TD
A[LLM 推理范式] --> B[Chain-of-Thought<br/>线性链式推理]
A --> C[ReAct<br/>思考-行动-观察循环]
A --> D[Tree-of-Thought<br/>树状搜索推理]
B --> B1[优点: 简单直接]
B --> B2[缺点: 无法回溯纠错]
C --> C1[优点: 可与环境交互]
C --> C2[缺点: 单路径易陷入局部最优]
D --> D1[优点: 可探索多分支回溯]
D --> D2[缺点: 计算成本指数增长]
B2 --> E[核心问题:<br/>推理路径不可回溯]
C2 --> E
D2 --> F[核心问题:<br/>搜索空间爆炸]
2.2 ReAct 的执行循环
ReAct 的核心是一个有限状态机:Thought → Action → Observation → Thought → ...。每一步的 Thought 是对当前状态的推理,Action 是选择并执行工具,Observation 是工具返回的结果。关键约束在于:每一步只能基于当前上下文窗口中的信息做决策,而上下文窗口的容量是有限的。
当推理链超过 10 步以上,早期关键信息可能被截断或稀释,导致 Agent "遗忘"初始目标。这并非模型能力不足,而是推理架构的固有缺陷——线性链无法表达"如果这条路走不通,回到分叉点尝试另一条路"的回溯逻辑。
2.3 Tree-of-Thought 的搜索策略
ToT 将每一步推理扩展为多个候选分支,通过评估函数对每个分支打分,选择最有前景的路径继续探索。搜索策略包括:
- BFS(广度优先):每层保留 top-k 分支,逐层扩展。适合解空间较浅但宽度大的任务。
- DFS(深度优先):沿一条路径深入到底,遇到死胡同回溯。适合解空间深但分支少的任务。
- A* 启发式搜索:结合当前代价与启发式估计,优先扩展最有前景的节点。
ToT 的代价是:每扩展一层,LLM 调用次数乘以分支因子 b。3 层深度、分支因子 5 的搜索需要 125 次 LLM 调用,这在生产环境中几乎不可接受。
三、混合推理引擎:ReAct + 剪枝 ToT 的生产级实现
# hybrid_agent.py — 混合推理引擎
# 设计意图:结合 ReAct 的高效执行与 ToT 的回溯能力,
# 在关键决策点启用树搜索,其余步骤走线性推理
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
import json
class ReasoningMode(Enum):
REACT = "react" # 线性推理模式
TOT_BFS = "tot_bfs" # 广度优先树搜索
TOT_DFS = "tot_dfs" # 深度优先树搜索
@dataclass
class ThoughtNode:
"""推理树节点:记录思考内容、评估分数与子节点"""
thought: str
score: float = 0.0
action: Optional[str] = None
observation: Optional[str] = None
children: list = field(default_factory=list)
parent: Optional['ThoughtNode'] = None
is_pruned: bool = False
class HybridReasoningAgent:
"""混合推理 Agent:在关键决策点切换推理模式"""
def __init__(self, llm_client, tools: dict, config: dict = None):
self.llm = llm_client
self.tools = tools
self.config = config or {
"max_react_steps": 15, # ReAct 最大步数
"tot_branch_factor": 3, # ToT 分支因子(控制搜索宽度)
"tot_max_depth": 3, # ToT 最大搜索深度
"prune_threshold": 0.3, # 剪枝阈值:低于此分数的分支直接丢弃
"confidence_threshold": 0.7, # 低于此置信度时切换到 ToT 模式
}
self.root = None
self.reasoning_trace = [] # 完整推理轨迹,用于调试与可观测性
def _call_llm(self, prompt: str, temperature: float = 0.0) -> str:
"""调用 LLM,统一入口便于替换模型与追踪调用"""
response = self.llm.chat(
messages=[{"role": "user", "content": prompt}],
temperature=temperature,
)
return response.choices[0].message.content
def _evaluate_thought(self, thought: str, goal: str) -> float:
"""评估推理分支的质量,返回 [0, 1] 分数"""
eval_prompt = f"""评估以下推理步骤对目标的相关性和合理性。
目标: {goal}
推理步骤: {thought}
请从以下维度打分(0-1):
1. 相关性:该步骤是否直接服务于目标?
2. 可行性:该步骤提出的行动是否可执行?
3. 信息增益:该步骤是否能带来新的有用信息?
只输出一个 0 到 1 之间的数字,不要其他内容。"""
score_str = self._call_llm(eval_prompt, temperature=0.0)
try:
score = float(score_str.strip())
return max(0.0, min(1.0, score))
except ValueError:
return 0.5 # 解析失败时给中等分数
def _should_switch_to_tot(self, thought: str, goal: str) -> bool:
"""判断当前推理步骤是否需要切换到树搜索模式"""
confidence_prompt = f"""判断以下推理步骤的确定性程度。
目标: {goal}
当前推理: {thought}
如果该步骤的后续路径明确且唯一,输出 "HIGH"。
如果存在多种可能的后续方向且难以选择,输出 "LOW"。
只输出 HIGH 或 LOW。"""
result = self._call_llm(confidence_prompt, temperature=0.0).strip()
return result.upper() == "LOW"
def react_step(self, goal: str, history: list) -> ThoughtNode:
"""执行一步 ReAct 推理"""
prompt = f"""你是一个智能 Agent,正在完成以下目标:{goal}
历史步骤:
{self._format_history(history)}
请输出下一步的思考和行动,格式如下:
THOUGHT: [你的推理过程]
ACTION: [工具名称](参数)
可用工具: {list(self.tools.keys())}"""
response = self._call_llm(prompt, temperature=0.0)
thought, action = self._parse_react_response(response)
node = ThoughtNode(thought=thought, action=action)
if action:
tool_name, args = self._parse_action(action)
if tool_name in self.tools:
node.observation = self.tools[tool_name](**args)
return node
def tot_search(self, goal: str, current_state: str,
mode: ReasoningMode = ReasoningMode.TOT_BFS) -> ThoughtNode:
"""执行 Tree-of-Thought 搜索"""
self.root = ThoughtNode(thought=current_state)
branch_factor = self.config["tot_branch_factor"]
max_depth = self.config["tot_max_depth"]
prune_threshold = self.config["prune_threshold"]
if mode == ReasoningMode.TOT_BFS:
return self._tot_bfs(goal, self.root, branch_factor,
max_depth, prune_threshold)
else:
return self._tot_dfs(goal, self.root, branch_factor,
max_depth, prune_threshold)
def _tot_bfs(self, goal: str, root: ThoughtNode,
branch_factor: int, max_depth: int,
prune_threshold: float) -> ThoughtNode:
"""广度优先 ToT 搜索:逐层扩展并剪枝"""
current_level = [root]
for depth in range(max_depth):
next_level = []
for node in current_level:
# 为每个节点生成 branch_factor 个候选推理分支
candidates = self._generate_branches(
goal, node.thought, branch_factor
)
for thought in candidates:
score = self._evaluate_thought(thought, goal)
child = ThoughtNode(
thought=thought, score=score, parent=node
)
# 剪枝:低分分支直接丢弃,减少搜索空间
if score >= prune_threshold:
node.children.append(child)
next_level.append(child)
else:
child.is_pruned = True
self.reasoning_trace.append(
f"[PRUNE] depth={depth} score={score:.2f} "
f"thought={thought[:50]}..."
)
if not next_level:
break
# 每层只保留 top-k 分支,控制搜索宽度
next_level.sort(key=lambda n: n.score, reverse=True)
current_level = next_level[:branch_factor]
# 选择全局最优路径
return self._select_best_path(root)
def _tot_dfs(self, goal: str, node: ThoughtNode,
branch_factor: int, max_depth: int,
prune_threshold: float, depth: int = 0) -> ThoughtNode:
"""深度优先 ToT 搜索:沿最有前景的路径深入"""
if depth >= max_depth:
return node
candidates = self._generate_branches(
goal, node.thought, branch_factor
)
scored = []
for thought in candidates:
score = self._evaluate_thought(thought, goal)
if score >= prune_threshold:
child = ThoughtNode(
thought=thought, score=score, parent=node
)
node.children.append(child)
scored.append(child)
# 按分数降序排列,优先探索最有前景的分支
scored.sort(key=lambda n: n.score, reverse=True)
for child in scored:
result = self._tot_dfs(
goal, child, branch_factor, max_depth,
prune_threshold, depth + 1
)
# 如果找到高分解,立即返回(早停机制)
if result.score >= 0.9:
return result
return scored[0] if scored else node
def _generate_branches(self, goal: str, current: str,
count: int) -> list[str]:
"""为当前状态生成多个候选推理分支"""
prompt = f"""目标: {goal}
当前状态: {current}
请生成 {count} 种不同的下一步推理方向,每种一行,格式:
1. [推理方向1]
2. [推理方向2]
3. [推理方向3]
确保每种方向有本质区别,不要只是措辞变化。"""
response = self._call_llm(prompt, temperature=0.7)
branches = []
for line in response.strip().split("\n"):
line = line.strip()
if line and line[0].isdigit():
# 去除序号前缀
content = line.lstrip("0123456789. ").strip()
if content:
branches.append(content)
return branches[:count]
def _select_best_path(self, root: ThoughtNode) -> ThoughtNode:
"""从推理树中选择得分最高的叶节点路径"""
best_node = root
best_score = root.score
def traverse(node: ThoughtNode):
nonlocal best_node, best_score
if not node.children: # 叶节点
# 路径总分 = 各节点分数的加权平均
path_score = self._path_average_score(node)
if path_score > best_score:
best_score = path_score
best_node = node
for child in node.children:
traverse(child)
traverse(root)
return best_node
def _path_average_score(self, leaf: ThoughtNode) -> float:
"""计算从根到叶节点的路径平均分"""
scores = []
node = leaf
while node is not None:
if node.score > 0:
scores.append(node.score)
node = node.parent
return sum(scores) / len(scores) if scores else 0.0
def run(self, goal: str) -> dict:
"""执行完整的混合推理流程"""
history = []
step = 0
while step < self.config["max_react_steps"]:
# 执行一步 ReAct
node = self.react_step(goal, history)
history.append(node)
step += 1
# 检查是否需要切换到 ToT 模式
if self._should_switch_to_tot(node.thought, goal):
self.reasoning_trace.append(
f"[SWITCH] Step {step}: 切换到 ToT 模式"
)
best_path = self.tot_search(
goal, node.thought, ReasoningMode.TOT_BFS
)
# 将 ToT 找到的最优路径合并回 ReAct 历史
path_nodes = self._reconstruct_path(best_path)
history.extend(path_nodes)
step += len(path_nodes)
# 检查是否已完成目标
if self._is_goal_reached(node.thought, goal):
break
return {
"goal": goal,
"steps": step,
"history": [
{"thought": n.thought, "action": n.action,
"observation": n.observation}
for n in history
],
"trace": self.reasoning_trace,
}
def _is_goal_reached(self, thought: str, goal: str) -> bool:
"""判断目标是否已达成"""
check_prompt = f"""判断以下推理是否已经完成了目标。
目标: {goal}
最新推理: {thought}
如果目标已完成,输出 YES。否则输出 NO。只输出 YES 或 NO。"""
result = self._call_llm(check_prompt, temperature=0.0).strip()
return result.upper() == "YES"
def _reconstruct_path(self, leaf: ThoughtNode) -> list[ThoughtNode]:
"""从叶节点回溯重建路径(排除根节点)"""
path = []
node = leaf
while node.parent is not None and node.parent.parent is not None:
path.append(node)
node = node.parent
path.reverse()
return path
@staticmethod
def _format_history(history: list) -> str:
"""格式化历史步骤为可读文本"""
lines = []
for i, node in enumerate(history):
lines.append(f"Step {i+1}: THOUGHT: {node.thought}")
if node.action:
lines.append(f" ACTION: {node.action}")
if node.observation:
lines.append(f" OBSERVATION: {node.observation[:200]}")
return "\n".join(lines) if lines else "(无历史步骤)"
@staticmethod
def _parse_react_response(response: str) -> tuple:
"""解析 ReAct 格式的响应"""
thought = ""
action = ""
for line in response.split("\n"):
if line.startswith("THOUGHT:"):
thought = line.replace("THOUGHT:", "").strip()
elif line.startswith("ACTION:"):
action = line.replace("ACTION:", "").strip()
return thought, action
@staticmethod
def _parse_action(action: str) -> tuple:
"""解析工具调用格式:tool_name(arg1=val1, arg2=val2)"""
if "(" not in action:
return action, {}
tool_name = action.split("(")[0].strip()
args_str = action.split("(")[1].rstrip(")")
try:
args = json.loads(f"{{{args_str}}}")
except json.JSONDecodeError:
args = {}
return tool_name, args
四、推理深度与计算成本的权衡:三种模式的适用边界
混合推理引擎的核心 Trade-off 在于推理质量与 LLM 调用次数的矛盾:
| 推理模式 | LLM 调用次数 | 适用场景 | 失败模式 |
|---|---|---|---|
| 纯 ReAct | O(n),n 为步数 | 路径明确的线性任务 | 长链累积误差,无法回溯 |
| 纯 ToT-BFS | O(b^d),b 为分支因子,d 为深度 | 解空间浅但宽的决策 | 计算成本爆炸,延迟过高 |
| 混合模式 | O(n + b^k),k 为关键决策点数 | 复杂但局部可线性化的任务 | 关键决策点识别不准 |
混合模式的三个关键参数调优建议:
confidence_threshold(置信度阈值):设为 0.7 是经验值。降低阈值会让 Agent 更频繁切换到 ToT,增加成本但提高决策质量;提高阈值则相反。在工具调用结果确定性高的场景(如数据库查询),可以提高到 0.85;在开放式推理场景(如方案设计),应降低到 0.6。tot_branch_factor(分支因子):3 是成本与覆盖率的平衡点。分支因子为 2 时,搜索空间太小容易遗漏最优解;为 5 时,LLM 调用次数增长 4 倍但边际收益递减。prune_threshold(剪枝阈值):0.3 是激进剪枝策略。在计算资源充裕时可以降低到 0.2,保留更多候选分支;在延迟敏感场景可以提高到 0.5,快速收敛。
禁用场景:当 LLM 的单次调用延迟超过 2 秒时,ToT 模式的用户体验极差(3 层 BFS 可能需要 30 秒以上),此时应退化为纯 ReAct 并通过更好的 Prompt 设计弥补推理能力的不足。
五、总结
智能 Agent 的推理能力取决于推理架构与任务复杂度的匹配程度。纯线性推理(ReAct)在路径明确的任务中高效可靠,但面对分支决策时容易陷入局部最优;纯树搜索(ToT)提供了回溯能力,但计算成本在深度和宽度上指数增长。混合策略的关键洞察是:并非每一步都需要搜索,只在置信度低的关键决策点启用树搜索,其余步骤走线性推理。
落地路线建议:先用纯 ReAct 跑通任务流程,收集推理失败的 case;分析失败模式,识别出需要回溯的关键决策点;在关键点插入 ToT 搜索,配合剪枝和早停控制成本;持续监控 LLM 调用次数与任务成功率,调整置信度阈值和分支因子。推理架构没有银弹,只有与任务特征匹配的合理权衡。
397



被折叠的 条评论
为什么被折叠?



