Agent ReAct模式

Agent模式1 — ReAct模式 ReAct Agent - 基于 Reasoning + Acting 模式的智能代理 ReAct 模式的核心思想是让 LLM 交替进行: 1. Thought (思考): 分析当前情况,决定下一步行动 2. Action (行动): 选择并执行一个工具 3. Observation (观察): 获取工具执行结果 这个循环持续进行,直到 Agent 认为可以给出最终答案。 回答中的解析可以按照 Thought: Action: Action Input: 进行正则匹配获取 比如 def _parse_response(self, response: str) -> tuple[str, Optional[str], Optional[dict], Optional[str]]: """ 解析 LLM 响应 Returns: (thought, action, action_input, final_answer) """ thought = "" action = None action_input = None final_answer = None # 提取 Thought thought_match = re.search(r"Thought:\s*(.+?)(?=Action:|Final Answer:|$)", response, re.DOTALL) if thought_match: thought = thought_match.group(1).strip() # 检查是否有 Final Answer final_match = re.search(r"Final Answer:\s*(.+?)$", response, re.DOTALL) if final_match: final_answer = final_match.group(1).strip() return thought, None, None, final_answer # 提取 Action action_match = re.search(r"Action:\s*(\w+)", response) if action_match: action = action_match.group(1).strip() # 提取 Action Input input_match = re.search(r"Action Input:\s*(\{.+?\})", response, re.DOTALL) if input_match: try: import json action_input = json.loads(input_match.group(1)) except json.JSONDecodeError: # 尝试更宽松的解析 action_input = {"input": input_match.group(1)} else: # 尝试匹配非 JSON 格式的输入 input_match = re.search(r"Action Input:\s*(.+?)(?=Thought:|Action:|$)", response, re.DOTALL) if input_match: raw_input = input_match.group(1).strip() # 根据工具类型推断参数名 if action == "calculator": action_input = {"expression": raw_input} elif action == "web_search": action_input = {"query": raw_input} elif action == "shell": action_input = {"command": raw_input} elif action == "http_request": action_input = {"url": raw_input} elif action == "python_repl": action_input = {"code": raw_input} else: action_input = {"input": raw_input} return thought, action, action_input, final_answer 提示词模板 ...

2026-01-26 11:12:34    |    2 分钟    |    303 字    |    Fengbin