- # In[1]
- 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
- # ================= 1. 定义工具 =================
- @tool(description="获取股价,传入股票名称,返回字符串信息")
- def get_price(name: str) -> str:
- return f"股票{name}的价格是20元"
- @tool(description="获取股票信息,传入股票名称,返回字符串信息")
- def get_info(name: str) -> str:
- return f"股票{name},是一家A股上市公司,专注于IT职业教育。"
- # ================= 2. 初始化模型 =================
- llm = ChatOpenAI(
- model="qwen3-max",
- temperature=0,
- openai_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1"
- )
- # ================= 3. 标准 Agent 流程 =================
- prompt = ChatPromptTemplate.from_messages([
- ("system", "你是一个智能助手,可以回答股票相关问题,请告知我思考过程。"),
- ("human", "{input}"),
- MessagesPlaceholder(variable_name="agent_scratchpad"),
- ])
- agent = create_tool_calling_agent(llm=llm, tools=[get_price, get_info], prompt=prompt)
- agent_executor = AgentExecutor(agent=agent, tools=[get_price, get_info], verbose=False)
- # ================= 4. 【核心修改】流式输出 =================
- print("— 开始流式对话 — ")
- for chunk in agent_executor.stream({"input": "传智教育股价多少,并介绍一下"}):
- # 1. 当 Agent 决定要调用工具时
- if "actions" in chunk:
- for action in chunk["actions"]:
- print(f" 我需要查询信息,正在调用工具:【{action.tool}】")
- print(f" 传入参数:{action.tool_input} ")
- # 2. 当工具返回结果时
- elif "steps" in chunk:
- for step in chunk["steps"]:
- print(f" 工具查询完毕,得到结果:{step.observation} ")
- # 3. 当 Agent 输出最终回答时
- elif "output" in chunk:
- print(f"✅ 最终回答:{chunk[‘output’]}")
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/233832.html