基于ReACT架构的Agent智能体设计与实现
一、这是什么?(概念解释)
ReACT(Reasoning + Acting) 是一种让LLM智能体同时进行"推理"和"行动"的架构模式。
核心思想:
- Reasoning(推理):让LLM思考要做什么
- Acting(行动):让LLM执行具体的工具调用
- 循环迭代:通过 观察 -> 思考 -> 行动 的循环,逐步完成任务
ReACT循环:
Thought(思考) -> Action(行动) -> Observation(观察) -> Thought(思考) -> ...
直到得出最终答案(Final Answer)。
二、有什么用?(应用场景)
| 场景 | 说明 |
|---|---|
| 复杂问答 | 需要多步推理才能回答的问题 |
| 信息检索 | 先搜索信息,再整合回答 |
| 数据分析 | 查询数据 -> 分析 -> 生成报告 |
| 任务规划 | 将复杂任务分解为多个步骤 |
| 决策系统 | 根据实时信息做出决策 |
| 智能客服 | 理解问题 -> 查询知识库 -> 回答用户 |
| 个人助理 | 安排日程、查询信息、执行任务 |
三、完整示例代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import dotenv
from langchain_classic.agents import create_react_agent, AgentExecutor
from langchain_community.tools import GoogleSerperRun
from langchain_community.utilities import GoogleSerperAPIWrapper
from langchain_core.prompts import ChatPromptTemplate
from pydantic import BaseModel, Field
from langchain_core.tools import render_text_description_and_args
from langchain_openai import ChatOpenAI
dotenv.load_dotenv()
# ============ 第一步:定义工具 ============
class SearchArgsSchema(BaseModel):
query: str = Field(description="执行谷歌搜索的查询语句")
# 定义搜索工具
google_serper = GoogleSerperRun(
name="google_serper",
description=(
"一个低成本的谷歌搜索API。"
"当你需要回答有关时事的问题时,可以调用该工具。"
"该工具的输入是搜索查询语句。"
),
args_schema=SearchArgsSchema,
api_wrapper=GoogleSerperAPIWrapper(),
)
tools = [google_serper]
# ============ 第二步:定义 ReACT Prompt ============
prompt = ChatPromptTemplate.from_template(
"Answer the following questions as best you can. You have access to the following tools:\n\n"
"{tools}\n\n"
"Use the following format:\n\n"
"Question: the input question you must answer\n"
"Thought: you should always think about what to do\n"
"Action: the action to take, should be one of [{tool_names}]\n"
"Action Input: the input to the action\n"
"Observation: the result of the action\n"
"... (this Thought/Action/Action Input/Observation can repeat N times)\n"
"Thought: I now know the final answer\n"
"Final Answer: the final answer to the original input question\n\n"
"Begin!\n\n"
"Question: {input}\n"
"Thought:{agent_scratchpad}"
)
# ============ 第三步:创建 ReACT Agent ============
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
agent = create_react_agent(
llm=llm,
prompt=prompt,
tools=tools,
tools_renderer=render_text_description_and_args, # 渲染工具描述
)
# ============ 第四步:创建 Agent 执行器 ============
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True, # 打印执行过程
max_iterations=5, # 最大迭代次数
handle_parsing_errors=True, # 处理解析错误
)
# ============ 第五步:执行 Agent ============
result = agent_executor.invoke({
"input": "查询下2026年3月5日深圳天气,包括温度、湿度、风力等,用中文回答"
})
print(result)
四、ReACT 循环流程图
┌─────────────────────────────────────────────────────────────────────────┐
│ ReACT 智能体执行流程 │
└─────────────────────────────────────────────────────────────────────────┘
用户问题 Agent LLM 工具执行
│ │ │
▼ ▼ │
"深圳今天天气?" ──────────────▶│ 思考 (Thought 1) │
│ │ "我需要查询深圳天气" │
│ │ │
│ ▼ │
│ 决定行动 (Action 1) │
│ "使用 google_serper" │
│ │ │
│ ▼ │
│ 准备参数 (Action Input 1) │
│ "深圳天气 2026-03-05" │
│ │ │
▼ ▼ ▼
调用工具 ──────────────────────────────────────────────▶│
│ 执行搜索
│◀─────────────────────────────────────────│
│ │ │
▼ ▼ ▼
观察 (Observation 1) 返回结果
"深圳今天晴天,25°C" │ │
│ │ │
▼ ▼ │
思考 (Thought 2) │ │
"我已经获得天气信息, │ │
现在可以回答用户了" │ │
│ │ │
▼ ▼ │
最终回答 (Final Answer) │ │
"根据查询结果,深圳 │ │
今天晴天,温度25°C" │ │
│ │ │
▼ ▼ ▼
返回给用户 完成
┌─────────────────────────────────────────────────────────────────────────┐
│ ReACT 核心要素 │
└─────────────────────────────────────────────────────────────────────────┘
Thought (思考): LLM 分析当前情况,决定下一步做什么
Action (行动): LLM 选择要调用的工具
Action Input (参数): LLM 为工具准备参数
Observation (观察): LLM 获取工具执行结果
Final Answer (答案): LLM 整合所有信息,给出最终答案
五、执行示例
假设用户问:"深圳今天天气怎么样?"
第1轮迭代:
Thought: 我需要查询深圳今天的天气信息
Action: google_serper
Action Input: 深圳今天天气
Observation: 根据搜索结果,深圳今天晴天,温度25°C,湿度60%
第2轮迭代:
Thought: 我已经获得了深圳今天的天气信息,现在可以回答用户了
Final Answer: 根据查询结果,深圳今天晴天,温度25°C,湿度60%,风力3级
六、ReACT vs 其他 Agent 架构
| 特性 | ReACT | Plan-and-Execute | Self-Ask |
|---|---|---|---|
| 思维方式 | 边想边做 | 先规划后执行 | 自问自答 |
| 适用场景 | 通用任务 | 复杂多步任务 | 信息检索 |
| 灵活性 | 高 | 中 | 低 |
| 实现复杂度 | 低 | 中 | 中 |
| Token消耗 | 中 | 高 | 低 |
参考资源
- LangChain Agents:python.langchain.com/docs/module…
- ReACT 论文:arxiv.org/abs/2210.03…
- AgentExecutor 文档:python.langchain.com/docs/module…
总结一句话:ReACT 让 Agent 拥有了"思考-行动-观察"的循环能力,是实现通用智能体的经典架构模式!