mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
686 字
2 分钟
ReAct 与 Agent 架构:让大模型主动推理行动
2025-06-12

2022 年,普林斯顿大学和 Google Research 发表了一篇改变 AI Agent 格局的论文。

标题是:《ReAct: Synergizing Reasoning and Acting in Language Models》

核心思想简洁有力:让大模型在「推理」和「行动」之间交替进行,而不是孤立地做其中之一。

这个范式成为现代 AI Agent 的基础架构,被 LangChain、AutoGPT 等几乎所有 Agent 框架采用。

ReAct 定义了 AI Agent 的基本工作方式。

本文要点#

  • ReAct 论文背景与动机
  • Reasoning + Acting 协同范式
  • Thought/Action/Observation 循环
  • HotpotQA/FEVER 实验结果
  • 与纯推理/纯行动的对比
  • Tool Use 的整合方式

一、论文背景#

1.1 研究动机#

flowchart TB subgraph ReAct要解决的问题 A[纯推理(Reasoning only)的问题] A --> A1[Chain of Thought 可以提升推理] A --> A2[但缺乏与外部世界的交互] A --> A3[容易产生幻觉,无法获取实时信息] B[纯行动(Acting only)的问题] B --> B1[可以调用工具、访问外部信息] B --> B2[但缺乏规划,行动盲目] B --> B3[容易做出错误决策] C[ReAct 的解决] C --> C1[推理指导行动:先想清楚再行动] C --> C2[行动验证推理:用行动获取信息验证想法] C --> C3[交替进行,形成闭环] D[核心洞察] D --> D1["「推理和行动应该协同工作,而非孤立进行」"] end

1.2 论文信息#

论文:ReAct: Synergizing Reasoning and Acting
in Language Models
作者:Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du,
Ishaan Gulrajani, Karthik Narasimhan, Yuan Cao
机构:Princeton University, Google Research
发表:ICLR 2023
引用:5000+ 次

二、ReAct 范式详解#

2.1 Thought/Action/Observation 循环#

flowchart TB A[用户任务] --> B[Thought: 思考] B --> C[Action: 执行行动] C --> D[Observation: 观察结果] D --> E{任务完成?} E -->|否| B E -->|是| F[Final Answer] style B fill:#e3f2fd style C fill:#fff3e0 style D fill:#e8f5e9
flowchart TB subgraph ReAct循环详解 A[Thought(思考)] A --> A1[分析当前状态] A --> A2[确定下一步行动] A --> A3[生成行动的理由] A --> A4[维护内部推理链] B[Action(行动)] B --> B1[调用外部工具] B --> B2[查询信息] B --> B3[执行具体操作] B --> B4[与环境交互] C[Observation(观察)] C --> C1[接收行动结果] C --> C2[解析返回信息] C --> C3[更新内部状态] C --> C4[作为下轮思考的输入] D[循环直到] D --> D1[任务完成] D --> D2[达到最大步数] D --> D3[遇到错误] end

2.2 完整示例#

flowchart TB subgraph ReAct执行示例 A[任务] A --> A1["除了苹果遥控器,哪些公司生产的遥控器可以控制 Apple TV?"] B[Thought 1] B --> B1[需要先了解 Apple TV 支持哪些遥控器] C[Action 1] C --> C1[search[Apple TV compatible remotes]] D[Observation 1] D --> D1["Apple TV 可以使用 Siri Remote,也支持第三方遥控器如 Roku Remote、 Harmony Elite 等"] E[Thought 2] E --> E1[找到了一些兼容的遥控器,需要确认生产公司] F[Action 2] F --> F1[search[who makes Roku Remote]] G[Observation 2] G --> G1[Roku Remote 由 Roku Inc. 生产] H[Thought 3] H --> H1[还需要确认 Harmony Elite 的生产公司] I[Action 3] I --> I1[search[who makes Harmony Elite remote]] J[Observation 3] J --> J1[Harmony Elite 由 Logitech 生产] K[Thought 4] K --> K1[现在可以回答问题了] L[Final Answer] L --> L1["除了苹果遥控器,Roku Inc. 生产的 Roku Remote 和 Logitech 生产的 Harmony Elite 都可以控制 Apple TV。"] end

2.3 代码实现#

class ReActAgent:
"""ReAct Agent 实现"""
def __init__(self, llm, tools, max_iterations=10):
self.llm = llm
self.tools = {tool.name: tool for tool in tools}
self.max_iterations = max_iterations
def run(self, task: str) -> str:
"""执行 ReAct 循环"""
history = []
prompt = self._build_prompt(task)
for i in range(self.max_iterations):
# 1. LLM 生成 Thought 和 Action
response = self.llm.generate(prompt + self._format_history(history))
thought, action, action_input = self._parse_response(response)
history.append({
"thought": thought,
"action": action,
"action_input": action_input
})
# 2. 检查是否完成
if action == "Finish":
return action_input
# 3. 执行 Action
if action in self.tools:
observation = self.tools[action].run(action_input)
else:
observation = f"Error: Unknown action {action}"
history[-1]["observation"] = observation
return "Maximum iterations reached"
def _build_prompt(self, task: str) -> str:
"""构建 ReAct 提示词"""
return f"""Answer the following questions as best you can. You have access to the following tools:
{self._format_tools()}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{self._tool_names()}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Question: {task}
"""
def _parse_response(self, response: str):
"""解析 LLM 响应"""
thought = ""
action = ""
action_input = ""
lines = response.strip().split("\n")
for line in lines:
if line.startswith("Thought:"):
thought = line.replace("Thought:", "").strip()
elif line.startswith("Action:"):
action = line.replace("Action:", "").strip()
elif line.startswith("Action Input:"):
action_input = line.replace("Action Input:", "").strip()
return thought, action, action_input

三、与纯推理/纯行动对比#

3.1 三种模式对比#

flowchart TB subgraph 纯推理 Reasoning Only A1[问题] --> B1[思考] B1 --> C1[思考] C1 --> D1[回答] end subgraph 纯行动 Acting Only A2[问题] --> B2[行动] B2 --> C2[行动] C2 --> D2[回答] end subgraph ReAct A3[问题] --> B3[思考] B3 --> C3[行动] C3 --> D3[观察] D3 --> E3[思考] E3 --> F3[行动] F3 --> G3[观察] G3 --> H3[回答] end

3.2 HotpotQA 实验结果#

xychart-beta title "HotpotQA 多跳问答准确率" x-axis ["Act-only", "Reason-only", "ReAct"] y-axis "准确率 %" 0 --> 40 bar [28, 29, 35]
| 方法 | HotpotQA | FEVER | 特点 |
|---------------|-------------|-------------|------------------|
| Act-only | 28.0% | 60.9% | 行动盲目 |
| Reason-only | 29.4% | 56.3% | 缺乏外部信息 |
| ReAct | 35.1% | 64.0% | 协同最优 |
| ReAct + Reflexion | 37.2% | 66.5% | 加反思更强 |
关键发现:
• ReAct 显著优于单一模式
• 推理和行动相互促进
• 外部信息减少幻觉

3.3 错误类型分析#

flowchart TB subgraph 错误类型分布 A[Act-only 的主要错误] A --> A1[搜索词不精确(31%)] A --> A2[盲目跟随搜索结果(27%)] A --> A3[缺乏对结果的判断(21%)] B[Reason-only 的主要错误] B --> B1[事实性幻觉(39%)] B --> B2[推理链断裂(24%)] B --> B3[缺乏事实依据(18%)] C[ReAct 的主要错误] C --> C1[工具调用格式错误(21%)] C --> C2[搜索策略不当(19%)] C --> C3[信息提取错误(16%)] D[结论] D --> D1[ReAct 的错误更容易诊断和修复] end

四、Tool Use 整合#

4.1 工具定义#

from dataclasses import dataclass
from typing import Callable, Dict, Any
@dataclass
class Tool:
"""工具定义"""
name: str
description: str
func: Callable
parameters: Dict[str, Any] # JSON Schema
# 常用工具示例
search_tool = Tool(
name="search",
description="Search for information on the web",
func=search_function,
parameters={
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query"
}
},
"required": ["query"]
}
)
calculate_tool = Tool(
name="calculate",
description="Perform mathematical calculations",
func=calculate_function,
parameters={
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "The mathematical expression to evaluate"
}
},
"required": ["expression"]
}
)
lookup_tool = Tool(
name="lookup",
description="Look up a specific entity in a knowledge base",
func=lookup_function,
parameters={
"type": "object",
"properties": {
"entity": {
"type": "string",
"description": "The entity to look up"
}
},
"required": ["entity"]
}
)

4.2 工具选择策略#

flowchart TB subgraph 工具选择机制 A[ReAct 的工具选择] A --> A1[LLM 根据描述自主选择] A --> A2[不需要显式的工具分类] A --> A3[通过示例学习选择策略] B[提升工具选择准确性的方法] B --> B1[清晰的工具描述] B1 --> B1a[说明工具的功能] B1 --> B1b[说明适用场景] B1 --> B1c[说明返回格式] B --> B2[好的 Few-Shot 示例] B2 --> B2a[展示不同场景下的工具选择] B2 --> B2b[包含错误修正的例子] B --> B3[工具分类和分组] B3 --> B3a[按功能分组] B3 --> B3b[减少选择空间] end

五、ReAct 的变体与改进#

5.1 Reflexion + ReAct#

flowchart TB A[任务] --> B[ReAct 循环] B --> C[结果] C --> D{成功?} D -->|是| E[输出] D -->|否| F[反思] F --> G[生成改进建议] G --> B
def reflexion_react(agent, task, max_attempts=3):
"""Reflexion + ReAct"""
reflections = []
for attempt in range(max_attempts):
# 执行 ReAct
result = agent.run(task)
success = evaluate(result, task)
if success:
return result
# 反思失败原因
reflection = agent.reflect(task, result)
reflections.append(reflection)
# 更新提示词,加入反思
agent.update_prompt(reflections)
return result

5.2 Plan-and-Execute#

flowchart TB subgraph Plan-and-Execute架构 A[与 ReAct 的区别] A --> A1[ReAct:每一步都实时思考和行动] A --> A2[Plan-and-Execute:先制定完整计划,再执行] B[流程] B --> B1[Planner 制定完整计划] B --> B2[Executor 按计划执行每个步骤] B --> B3[失败时重新规划] C[适用场景] C --> C1[ReAct:不确定性高,需要灵活调整] C --> C2[Plan-and-Execute:步骤明确,可以并行] end

六、ReAct 对 Agent 的影响#

6.1 成为 Agent 标准范式#

flowchart TB subgraph ReAct的影响 A[框架采用] A --> A1[LangChain:ReAct Agent 作为核心] A --> A2[AutoGPT:基于 ReAct 的自主执行] A --> A3[BabyAGI:任务规划 + ReAct 执行] A --> A4[OpenAI Assistants:底层使用类似模式] B[研究影响] B --> B1[Agent 成为 LLM 应用热点] B --> B2[Tool Use 成为标配能力] B --> B3[推理-行动协同成为共识] C[产品影响] C --> C1[ChatGPT Plugins] C --> C2[Claude Tool Use] C --> C3[Gemini Extensions] end

6.2 现代 Agent 架构演进#

flowchart LR A[ReAct 2022] --> B[AutoGPT 2023] A --> C[LangChain Agent] B --> D[Multi-Agent 2024] C --> D D --> E[推理模型 + Agent 2025]

常见问题 FAQ#

Q1:ReAct 和 Chain of Thought 有什么区别?

A:CoT 是纯推理,在模型内部进行思考链。ReAct 是推理+行动的交替,会调用外部工具获取信息,推理基于真实数据。

Q2:ReAct 的最大步数如何设置?

A:根据任务复杂度设置。简单问答 3-5 步,复杂研究 10-20 步。太多步数可能导致成本过高。

Q3:ReAct 能解决所有任务吗?

A:不能。ReAct 适合需要外部信息的任务。对于纯知识问答、创意写作等,不需要工具调用的任务,直接生成更高效。

Q4:如何评估 ReAct Agent 的效果?

A:1)任务成功率;2)步骤效率;3)工具使用正确率;4)最终答案质量。

Q5:ReAct 和 Function Calling 有什么关系?

A:ReAct 是一种范式,Function Calling 是技术实现。ReAct 使用 Function Calling 来执行 Action。两者是范式与实现的关系。


小结#

ReAct 定义了 AI Agent 的基本工作方式:推理与行动交替进行。

核心贡献:

flowchart TB subgraph ReAct核心总结 A[核心范式] --> A1[Thought → Action → Observation 循环] B[协同机制] --> B1[推理指导行动,行动验证推理] C[实验验证] --> C1[显著优于纯推理或纯行动] D[影响深远] --> D1[成为 Agent 标准架构] E[生态采用] --> E1[LangChain、AutoGPT、OpenAI 等] end

ReAct 让 AI 从「只思考」变成「边思考边行动」。


参考资料#

支持与分享

如果这篇文章对你有帮助,欢迎支持作者或分享给更多人

ReAct 与 Agent 架构:让大模型主动推理行动
https://blog.souloss.com/posts/machine-learning/llm-paper-history/react-and-agent-architecture/
作者
Souloss
发布于
2025-06-12
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时