AI Agent的规划能力:从ReAct到Tree-of-Planning
规划:Agent的核心能力 AI Agent与聊天机器人的本质区别在于规划能力——将复杂目标分解为可执行步骤并动态调整的能力。从简单的ReAct循环到复杂的树搜索规划,Agent规划算法经历了快速演进。 ReAct:推理与行动的交错 基本循环 ReAct(Reasoning + Acting)是Agent规划的基石,核心思想是交错推理和行动: Thought: 用户要查北京天气,我需要调用天气API Action: search_weather(city="北京") Observation: 北京今天晴,25°C Thought: 获取到天气信息,可以回答用户了 Answer: 北京今天天气晴朗,气温25°C,适合外出活动。 实现细节 class ReActAgent: def __init__(self, llm, tools, max_steps=10): self.llm = llm self.tools = tools self.max_steps = max_steps def run(self, task): trajectory = [] for step in range(self.max_steps): # 生成下一步思考和行为 prompt = self._build_prompt(task, trajectory) response = self.llm.generate(prompt) thought, action = self._parse(response) trajectory.append({"thought": thought, "action": action}) if action["type"] == "finish": return action["answer"] # 执行工具 if action["type"] == "tool": result = self.tools[action["name"]](**action["params"]) trajectory.append({"observation": result}) return "达到最大步数限制" def _build_prompt(self, task, trajectory): prompt = f"""任务:{task} 可用工具:{list(self.tools.keys())} 历史: """ for item in trajectory: if "thought" in item: prompt += f"Thought: {item['thought']}\n" prompt += f"Action: {item['action']}\n" elif "observation" in item: prompt += f"Observation: {item['observation']}\n" prompt += "Thought:" return prompt ReAct的局限 无记忆反馈:失败的经验不会影响后续尝试 线性思维:无法回溯到之前的选择点尝试其他路径 容易陷入循环:在复杂任务中反复尝试相同的失败方案 Reflexion:从失败中学习 核心改进 Reflexion在ReAct基础上增加了自我反思机制。当任务执行失败时,Agent会生成反思并存储到长期记忆中: ...
