ReAct 模式
ReAct 将推理 Reasoning 和行动 Acting 结合起来,让 Agent 在思考和执行之间交替进行。
实现步骤
定义工具集
tools = [
Tool(name="search", func=google_search, description="搜索互联网获取最新信息"),
Tool(name="calculator", func=calculate, description="执行数学计算"),
Tool(name="file_reader", func=read_file, description="读取本地文件内容"),
]
思考-行动-观察循环
def agent_loop(query, max_steps=5):
history = [{"role": "user", "content": query}]
for step in range(max_steps):
# Think: 让模型决定下一步
thought = llm.think(history, tools)
if thought.action == "answer":
return thought.content
# Act: 执行工具调用
result = execute_tool(thought.action, thought.input)
# Observe: 将结果反馈给模型
history.append({"role": "assistant", "content": f"结果: {result}"})
return "达到最大步数限制"
关键技术点
- 记忆管理:使用向量数据库存储历史交互,支持长期记忆
- 规划能力:复杂任务先分解子目标再逐步执行
- 错误恢复:工具调用失败时自动重试或调整策略
Agent 技术的更多背景见 AI Agent 研究现状与展望,框架对比见 Agent 框架对比:AutoGPT vs MetaGPT。