响应式与计划执行式:LLM代理模式的实用比较
构建LLM智能体系统时,选择合适的推理模式至关重要。本文深入比较了两种主流的智能体推理模式:ReAct(推理与行动)和计划与执行,并通过实际案例帮助您做出明智的技术决策。
要点总结
-
理解两种主要代理模式
- ReAct的推理-行动循环机制
- Plan-and-Execute 的计划-执行分离策略
-
基于 LangChain 的实现
- ReAct模式代码实现和最佳实践
- 规划并执行模式工程解决方案
-
性能和成本分析
- 响应时间和准确性的定量分析
- 详细计算代币消耗和 API 成本
-
实际案例与应用
- 实际数据分析任务
- 针对不同场景的最佳模式选择
-
系统选择方法
- 场景特征和模式匹配指南
- 混合策略实施建议
1.两种模式的工作原理
1.1 React 模式
ReAct(推理与行动)模式是一种迭代方法,它在思考和行动之间交替进行。其核心工作流程包括:
- 推理:分析现状和目标
- 执行操作:执行特定操作
- 观察:获取行动结果
- 迭代:根据观察结果持续思考和行动
典型的 ReAct 提示模板:
REACT_PROMPT = """Answer the following questions as best you can. You have access to the following tools:
{tools}
Use the following format:
Thought: you should always think about what to do
Action: the action to take, should be one of [{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
Question: {input}
Thought: {agent_scratchpad}"""
1.2 计划与执行模式
计划执行模式采用“先计划,后执行”的策略,将任务分为两个不同的阶段:
-
规划阶段:
- 分析任务目标
- 分解成子任务
- 制定执行计划
-
执行阶段:
- 按顺序执行子任务
- 流程执行结果
- 如有需要,调整计划
典型的计划与执行提示模板:
PLANNER_PROMPT = """You are a task planning assistant. Given a task, create a detailed plan.
Task: {input}
Create a plan with the following format:
1. First step
2. Second step
...
Plan:"""
EXECUTOR_PROMPT = """You are a task executor. Follow the plan and execute each step using available tools:
{tools}
Plan:
{plan}
Current step: {current_step}
Previous results: {previous_results}
Use the following format:
Thought: think about the current step
Action: the action to take
Action Input: the input for the action"""
2. 实现方式对比
2.1 使用 LangChain 实现 ReAct
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI
def create_react_agent(tools, llm):
return initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION,
verbose=True
)
# Usage example
llm = ChatOpenAI(temperature=0)
tools = [
Tool(
name="Search",
func=search_tool,
description="Useful for searching information"
),
Tool(
name="Calculator",
func=calculator_tool,
description="Useful for doing calculations"
)
]
agent = create_react_agent(tools, llm)
result = agent.run("What is the population of China multiplied by 2?")
2.2 使用 LangChain 进行计划和执行实施
from langchain.agents import PlanAndExecute
from langchain.chat_models import ChatOpenAI
def create_plan_and_execute_agent(tools, llm):
return PlanAndExecute(
planner=create_planner(llm),
executor=create_executor(llm, tools),
verbose=True
)
# Usage example
llm = ChatOpenAI(temperature=0)
agent = create_plan_and_execute_agent(tools, llm)
result = agent.run("What is the population of China multiplied by 2?")
3. 性能和成本分析
3.1 性能比较
| 指标 | 反应 | 计划与执行 |
|---|---|---|
| 响应时间 | 快点 | 慢点 |
| 代币消耗 | 中等的 | 更高 |
| 任务完成准确率 | 85% | 92% |
| 复杂任务处理 | 中等的 | 强的 |
3.2 成本分析
使用 GPT-4 模型完成复杂任务:
| 成本项目 | 反应 | 计划与执行 |
|---|---|---|
| 平均代币使用量 | 2000-3000 | 3000-4500 |
| API调用 | 3-5次 | 5-8次 |
| 每项任务的成本 | 0.06-0.09美元 | 0.09-0.14美元 |
4. 案例研究:数据分析任务
让我们通过一个实际的数据分析任务来比较这两种模式:
任务目标:分析 CSV 文件,计算销售统计数据,并生成报告。
4.1 ReAct 实现
from langchain.agents import create_csv_agent
from langchain.chat_models import ChatOpenAI
def analyze_with_react():
agent = create_csv_agent(
ChatOpenAI(temperature=0),
'sales_data.csv',
verbose=True
)
return agent.run("""
1. Calculate the total sales
2. Find the best performing product
3. Generate a summary report
""")
4.2 计划与执行实施
from langchain.agents import PlanAndExecute
from langchain.tools import PythonAstREPLTool
def analyze_with_plan_execute():
agent = create_plan_and_execute_agent(
llm=ChatOpenAI(temperature=0),
tools=[
PythonAstREPLTool(),
CSVTool('sales_data.csv')
]
)
return agent.run("""
1. Calculate the total sales
2. Find the best performing product
3. Generate a summary report
""")
5. 选择指南和最佳实践
5.1 何时选择 ReAct
-
简单直接任务
- 单一明确目标
- 几个步骤
- 需要快速响应
-
实时交互式场景
- 客户服务对话
- 即时查询
- 简单计算
-
成本敏感型情景
- 代币预算有限
- 需要控制 API 调用
5.2 何时选择计划执行
-
复杂的多步骤任务
- 需要进行任务分解
- 步骤依赖关系
- 中间结果验证
-
高精度场景
- 财务分析
- 数据处理
- 报告生成
-
长期规划任务
- 项目规划
- 研究分析
- 战略决策
5.3 最佳实践建议
-
混合使用策略
- 根据子任务的复杂性选择模式
- 将两种模式结合到一个系统中
-
性能优化技巧
- 实现缓存机制
- 启用并行处理
- 优化提示模板
-
成本控制方法
- 设置代币限额
- 实施任务中断
- 使用结果缓存
结论
响应式和计划执行式各有优势,选择哪种模式应考虑任务特性、性能要求和成本限制。在实际应用中,您可以灵活选择甚至结合使用这两种模式,以达到最佳效果。
文章来源:https://dev.to/jamesli/react-vs-plan-and-execute-a-practical-comparison-of-llm-agent-patterns-4gh9