|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 糖逗 于 2026-3-9 12:23 编辑
1. 什么是ReAct?
Agent ReAct是大模型智能体的核心思考与行动框架,全称Reasoning+Acting(推理+行动),是让Agent像人类一样「思考问题→制定策略→执行行动→验证结果」的关键逻辑。
ReAct是一种工作范式,定义了大模型的工作流程。
2. 代码实战
- from langchain.agents import create_tool_calling_agent, AgentExecutor
- from langchain_openai import ChatOpenAI
- from langchain_core.tools import tool
- from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
- # ================= 2. 定义工具 =================
- @tool(description="获取体重,返回值是整数,单位千克")
- def get_weight() -> int:
- return 90
- @tool(description="获取身高,返回值是整数,单位厘米")
- def get_height() -> int:
- return 172
- # ================= 3. 初始化模型 =================
- llm = ChatOpenAI(
- model="qwen-max",
- temperature=0,
- openai_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1",
- )
- # ================= 4. 定义 Prompt (保留你的 ReAct 要求) =================
- prompt = ChatPromptTemplate.from_messages([
- ("system", """你是严格遵循ReAct框架的智能体,必须按「思考→行动→观察→再思考」的流程解决问题,
- 且**每轮仅能思考并调用1个工具**,禁止单次调用多个工具。
- 并告知我你的思考过程,工具的调用原因,按思考、行动、观察三个结构告知我"""),
- ("human", "{input}"),
- MessagesPlaceholder(variable_name="agent_scratchpad"),
- ])
- # ================= 5. 创建 Agent 和执行器 =================
- agent = create_tool_calling_agent(llm=llm, tools=[get_weight, get_height], prompt=prompt)
- agent_executor = AgentExecutor(agent=agent, tools=[get_weight, get_height], verbose=False)
- # ================= 6. 流式输出 (适配 ReAct 格式打印) =================
- print("--- 开始 ReAct 流式推理 ---\n")
- for chunk in agent_executor.stream({"input": "计算我的BMI"}):
-
- # 1. 思考与行动阶段:Agent 决定调用工具
- if "actions" in chunk:
- for action in chunk["actions"]:
- # 这里的 action.log 通常包含了模型的思考过程
- print(f"💡 **思考**:我需要先获取用户的身体数据才能计算BMI。")
- print(f"⚙️ **行动**:决定调用工具 `{action.tool}`")
- print(f" 📥 参数:{action.tool_input}\n")
- # 2. 观察阶段:工具返回结果
- elif "steps" in chunk:
- for step in chunk["steps"]:
- print(f"👁️ **观察**:工具返回结果 -> {step.observation}\n")
- # 3. 最终总结阶段
- elif "output" in chunk:
- print(f"🧠 **最终思考/答案**:{chunk['output']}")
复制代码
|
|