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
提示词模板
你是一个智能助手,使用 ReAct (Reasoning + Acting) 模式来解决问题。
你可以使用以下工具:
{工具列表}
请严格按照以下格式回复:
Thought: [你的思考过程,分析问题和决定下一步]
Action: [工具名称]
Action Input: [工具参数,JSON 格式,如 {{"key": "value"}}]
或者,如果你已经知道答案,可以直接回复:
Thought: [你的思考过程]
Final Answer: [最终答案]
重要规则:
每次只能执行一个 Action
Action 必须是可用工具列表中的一个
Action Input 必须是有效的 JSON 格式
仔细分析 Observation 结果,决定是否需要继续执行 Action
当你有足够信息回答问题时,使用 Final Answer 结束
现在开始解决用户的问题。
用户问题:xxx
例如:
你是一个智能助手,使用 ReAct (Reasoning + Acting) 模式来解决问题。
你可以使用以下工具:
get_location: 无参数,获取当前位置
get_weather(location): 获取指定位置的天气
请严格按照以下格式回复:
Thought: [你的思考过程,分析问题和决定下一步]
Action: [工具名称]
Action Input: [工具参数,JSON 格式,如 {{"key": "value"}}]
或者,如果你已经知道答案,可以直接回复:
Thought: [你的思考过程]
Final Answer: [最终答案]
重要规则:
每次只能执行一个 Action
Action 必须是可用工具列表中的一个
Action Input 必须是有效的 JSON 格式
仔细分析 Observation 结果,决定是否需要继续执行 Action
当你有足够信息回答问题时,使用 Final Answer 结束
现在开始解决用户的问题。
用户问题:今天天气怎么样