04 中间件

This commit is contained in:
HengZhang 2026-02-25 00:28:37 +08:00
parent 1bd0242392
commit 0f400a4297
4 changed files with 172 additions and 0 deletions

View File

@ -0,0 +1,26 @@
from langchain.agents import create_agent
from langchain_community.chat_models.tongyi import ChatTongyi
from langchain_core.tools import tool
@tool(description="查询天气")
def get_weather():
return "晴天"
agent = create_agent(
model=ChatTongyi(model="qwen3-max"),
tools=[get_weather],
system_prompt="你是一个聊天助手,可以回答用户问题"
)
res = agent.invoke(
{
"messages": [
{"role": "user", "content": "明天深圳的天气如何"},
]
}
)
for msg in res["messages"]:
print(f"{type(msg).__name__}: {msg.content}")

View File

@ -0,0 +1,37 @@
from langchain.agents import create_agent
from langchain_community.chat_models.tongyi import ChatTongyi
from langchain_core.tools import tool
@tool(description="查询股票价格")
def get_price(name: str) -> str:
return f"股票{name}的价格是20元"
@tool(description="查询股票信息")
def get_info(name: str) -> str:
return f"股票{name}是一家A股上市公司"
agent = create_agent(
model=ChatTongyi(model="qwen3-max"),
tools=[get_price, get_info],
system_prompt="你是一个智能助手,可以回答股票相关问题,请告知我思考过程,让我知道你为什么调用某个工具"
)
res = agent.stream(
{"messages": [{
"role": "user", "content": "kk公司股价多少并介绍一下"
}]},
stream_mode="values"
)
for chunk in res:
last_msg = chunk["messages"][-1]
if last_msg.content:
print(type(last_msg).__name__, last_msg.content)
if type(last_msg).__name__ == "AIMessage":
if last_msg.tool_calls:
tool_list = [tc['name'] for tc in last_msg.tool_calls]
print(f"工具调佣 {tool_list}")

View File

@ -0,0 +1,39 @@
from langchain.agents import create_agent
from langchain_community.chat_models.tongyi import ChatTongyi
from langchain_core.tools import tool
@tool(description="获取体重,返回值整数,单位千克")
def get_weight() -> int:
return 93
@tool(description="获取身高,返回值整数,单位厘米")
def get_height() -> int:
return 185
agent = create_agent(
model=ChatTongyi(model="qwen3-max"),
tools=[get_height, get_weight],
system_prompt="""你是严格遵循ReAct框架的智能体必须按[思考,行动,观察,再思考]的流程解决问题
每轮仅能思考并调用1个工具禁止单词调用多个工具并告知我你的思考过程工具调用的原因按思考行动
观察三个结构告知我"""
)
res = agent.stream(
{"messages": [{
"role": "user", "content": "计算我的BMI"
}]},
stream_mode="values"
)
for chunk in res:
last_msg = chunk["messages"][-1]
if last_msg.content:
print(type(last_msg).__name__, last_msg.content)
if type(last_msg).__name__ == "AIMessage":
if last_msg.tool_calls:
tool_list = [tc['name'] for tc in last_msg.tool_calls]
print(f"工具调佣 {tool_list}")

70
04_middle_ware.py Normal file
View File

@ -0,0 +1,70 @@
"""
agent 前后
model 前后
工具
模型
"""
from langchain.agents import create_agent, AgentState
from langchain.agents.middleware import before_agent, after_agent, before_model, after_model, wrap_model_call, \
wrap_tool_call
from langchain_community.chat_models.tongyi import ChatTongyi
from langchain_core.tools import tool
from langgraph.runtime import Runtime
@tool(description="查询天气, 传入城市名称字符串,返回字符串天气信息")
def get_weather(city: str) -> str:
return f"{city} : 晴天"
@before_agent
def log_before_agent(state: AgentState, runtime: Runtime) -> None:
print(f"before agent: info_num: {len(state["messages"])}")
@after_agent
def log_after_agent(state: AgentState, runtime: Runtime) -> None:
print(f"after agent: info_num: {len(state["messages"])}")
@before_model
def log_before_model(state: AgentState, runtime: Runtime) -> None:
print(f"before model: info_num: {len(state["messages"])}")
@after_model
def log_after_model(state: AgentState, runtime: Runtime) -> None:
print(f"after model: info_num: {len(state["messages"])}")
@wrap_model_call
def model_call_hook(request, handler):
print(f"model call: {request}")
return handler(request)
@wrap_tool_call
def model_tool_hook(request, handler):
print(f"model tool: {request.tool_call['name']}")
print(f"args: {request.tool_call['args']}")
return handler(request)
agent = create_agent(
model=ChatTongyi(model="qwen3-max"),
tools=[get_weather],
middleware=[model_call_hook, model_tool_hook, log_before_model,
log_after_model, log_before_agent, log_after_agent],
system_prompt="""你是严格遵循ReAct框架的智能体必须按[思考,行动,观察,再思考]的流程解决问题
每轮仅能思考并调用1个工具禁止单词调用多个工具并告知我你的思考过程工具调用的原因按思考行动
观察三个结构告知我"""
)
res = agent.stream(
{"messages": [{
"role": "user", "content": "查询北京的天气"
}]},
stream_mode="values"
)
for chunk in res:
print(chunk["messages"][-1].content)