文章目录[隐藏]
近几年,智能体和大语言模型的结合成为自然语言处理和实际应用开发的热点。本文的目的就是理解如何快速搭建一个基于 ReAct(Reasoning + Acting)模式的智能体。
什么是 ReAct 模式?
ReAct 模式是一种让语言模型不仅做出推理(Reasoning),还能主动调用工具或执行动作(Acting)的设计范式。这种模式通过交替的思考(Thought)和行动(Action)步骤,使模型能动态地搜索信息、调用API或计算,直到得出最终结果。
典型步骤:
- Thought:模型内部推理、分析当前情况
- Action:根据推理结果,调用某个工具或者接口完成某个具体操作
- Observation:获取行动的结果信息,进入下一轮推理或决定正确答案
ReAct 模式示例流程解析
下面基于 https://github.com/junjiem/dify-plugin-agent-mcp_sse/blob/dac9837/prompt/template.py 的提示词,举个简单的示例:
任务:用户问“十天前星期几?”
智能体流程:
- 获取当前时间(Action 调用当前时间接口)
- 推理十天前日期(Thought)
- 调用日期对应星期的工具(Action 调用根据日期获取星期)
- 总结并给出答案(Final Answer)
设计提示词(Prompt)核心要素
为了让语言模型按 ReAct 模式思考和行动,提示词需要包含:
- 明确的身份说明(告诉模型它是谁,有什么工具)
- 思考和行动的固定格式(如 Thought、Action、Observation)
- 工具调用的规范格式,方便模型输出结构化指令
- 最终答案输出的标记(Final Answer)
实际流程
首先第一句提示词:
Respond to the human as helpfully and accurately as possible.
十天前星期几
You have access to the following tools:
[{"name": "getNowTime", "desc": "获取当前时间"}, {"name":"getWeekOfDay", "desc": "根据日期获取当天星期几"}]
Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).
Valid "action" values: "Final Answer" or ["getNowTime", "getWeekOfDay"]
Provide only ONE action per $JSON_BLOB, as shown:
{
"action": $TOOL_NAME,
"action_input": $ACTION_INPUT
}
Follow this format:
Question: input question to answer
Thought: consider previous and subsequent steps
Action:
$JSON_BLOB
Observation: action result
... (repeat Thought/Action/Observation N times)
Thought: I know what to respond
Action:
{
"action": "Final Answer",
"action_input": "Final response to human"
}
Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action: $JSON_BLOB then Observation:.
此时大模型回复:
Thought: I need to determine the day of the week for the date that was ten days ago from today. First, I will get the current date and then calculate the day of the week for ten days ago.
Action:
{
"action": "getNowTime",
"action_input": {}
}
调用工具并将结果拼到 Message 继续喂给大模型:
2025-11-26 15:17:01
大模型返回:
Thought: I now know the current date is 2025-11-26. I will calculate the date ten days ago, which is 2025-11-16, and then determine the day of the week for that date.
Action:
{
"action": "getWeekOfDay",
"action_input": "2025-11-16"
}
继续调用工具并将结果拼接继续喂给大模型
Sunday
大模型回复:
Thought: I now know that ten days ago from today, which is 2025-11-26, was a Sunday.
Action:
{
"action": "Final Answer",
"action_input": "十天前是星期日。"
}
至此大模型已经给出了 Final Answer,流程结束。
结束
希望这篇文章帮你快速入门 ReAct 智能体开发,也祝你项目顺利推进!
发表回复