LangChain 工具调用拦截(@wrap_tool_call)
核对 @wrap_tool_call 的 ToolCallRequest 不可变参数规范化、自定义与 ToolRetryMiddleware 重试、只读工具缓存、ToolErrorMiddleware 异常转换、Command 状态更新及异步实测。
学完这一章,你能够
- 核对 @wrap_tool_call 的 ToolCallRequest 不可变参数规范化、自定义与 ToolRetryMiddleware 重试、只读工具缓存、ToolErrorMiddleware 异常转换、Command 状态更新及异步实测。
@wrap_tool_call 工作流与 ToolCallRequest 协议
@wrap_tool_call 负责包裹 Agent 的每一次工具执行,结构上同样通过 handler(request) 控制调用前后逻辑或条件短路。其返回值须严格遵守工具协议——正常返回 ToolMessage,涉及状态更新时返回 Command,不可直接返回裸字符串或普通字典。
请求对象 ToolCallRequest 封装了 tool_call(含 name、args 与用于关联请求/响应的唯一 id)、tool(当前工具对象,部分场景可为 None)、state、runtime(ToolRuntime)以及不可变修改方法 request.override()。记录审计日志时建议默认仅输出工具名、参数键名与调用 ID,避免把密码、Token 等敏感参数值写入日志。
工具失败重试、ToolRetryMiddleware 与参数规范化
对于只读外部查询的临时异常(如 TemporaryServiceError),可在 @wrap_tool_call 中执行有限次指数退避重试;但对建单、扣款、发邮件等有副作用工具绝不可盲目重试。必须区分两种错误形态:工具抛出的 Python 异常与工具返回的 ToolMessage(status='error') 属于不同机制,后者不会被 except 捕获。本站实测前两次抛 TemporaryServiceError、第三次成功的模拟工具在自定义重试下执行 3 次返回成功,而直接返回 ToolMessage(status='error') 的工具仅执行 1 次不触发异常重试。
常规工具重试优先使用内置 ToolRetryMiddleware,支持通过 tools、max_retries(首调之后允许的额外重试次数,max_retries=2 即最多执行 3 次)、retry_on、on_failure('continue' 转为错误 ToolMessage 让 Agent 继续;'error' 重新抛出)、initial_delay、backoff_factor、max_delay 与 jitter 精细控制。本站实测 max_retries=2 使前两次失败的工具于第 3 次成功,且持续失败在 max_retries=1、on_failure='continue' 时共执行 2 次并返回 status='error' 的 ToolMessage。
模型传入的字符串参数常夹杂首尾空白或全角空格(如 ' 杭州\u3000'),可在 @wrap_tool_call 中借助 request.override(tool_call={**call, 'args': args}) 在执行前统一规范化。本站实测原 request.tool_call['args']['city'] 保持不可变,工具实际收到规范值 '杭州' 且返回的 ToolMessage 精确匹配原 tool_call_id。注意参数清洗不能替代后端对数据库 ID、文件路径与权限标识的安全校验。
只读缓存、监控、错误处理、ToolErrorMiddleware 与 Command 语义
只读且低频变更的静态资料查询适合缓存,而实时行情、用户隐私与副作用工具分别需谨慎处理或禁止简单缓存。安全工具缓存需按规范化 JSON 构造键、仅缓存成功的文本 ToolMessage、绝不缓存 Command,并在命中时必须以当前请求的 call['id'] 构造全新 ToolMessage(旧消息绑定旧 tool_call_id)。配合 time.perf_counter() 监控可记录工具名、成功/失败/异常状态与耗时。本站实测 [normalize_kw, cache_course, inner_retry_probe] 组合处理 ' PYTHON ' 与 'python' 两次调用时,底层工具仅执行 1 次、两条 ToolMessage 各自准确绑定 'tc_1'/'tc_2',命中缓存直接跳过内层探针。
错误处理应区分“特定异常转换”与“正常空查询”:对于已知外部故障,可用内置 ToolErrorMiddleware(on_error=fn, tools=[...]) 集中转换——回调函数返回字符串即生成 ToolMessage(status='error'),返回 None 则让异常继续传播(避免吞掉代码 Bug);如需“先重试再友好兜底”,应将 ToolErrorMiddleware 置于外层、ToolRetryMiddleware(on_failure='error') 置于内层(本站实测重试 2 次耗尽后转换为友好错误 ToolMessage,而未处理的 KeyError 正常抛出)。对于“未找到相关课程”这类正常空结果,应返回清晰的正常 ToolMessage 而非拼凑无关联的 Command(AIMessage);对于本身通过 Command(update={'completed_topics': ..., 'messages': [ToolMessage(..., tool_call_id=runtime.tool_call_id)]}) 更新状态的工具,@wrap_tool_call 应透明保留其 Command 语义(本站实测 completed_topics 成功写入 ['middleware'])。
组合顺序、异步拦截勘误、完整对照与生产原则
多工具中间件同样首项最外层:推荐“规范化在外 → 监控/缓存在中 → 重试在内”,或“异常转换在外 → 重试在内”。版本勘误提示:来源示例演示 @awrap_tool_call,但本站在 LangChain 1.4.9 实测证实 langchain.agents.middleware 并未导出 awrap_tool_call(hasattr == False);正确异步写法为使用 @wrap_tool_call 直接装饰 async def 并 await handler(request)(等待使用 await asyncio.sleep(),避免阻塞事件循环),或继承 AgentMiddleware 覆写 awrap_tool_call。本站实测 @wrap_tool_call 修饰 async def 配合 async_echo 工具与 ainvoke() 完整记录 ['in:async_echo', 'out:async_echo'] 并返回 'echo:ok'。
归结而言,@wrap_model_call 管理模型请求,@wrap_tool_call 管理工具执行。生产实践需坚守六条底线:副作用工具依赖幂等键而非盲目重试;私有查询缓存须按用户/租户隔离并设 TTL;规范化不代替可信后端权限与业务校验;日志脱敏不印敏感参数;只捕获明确可处理异常;含状态更新的 Command 必须携带对应 tool_call_id 的 ToolMessage 以维护完整的工具调用历史协议。
ToolCallRequest 核心属性与方法
| 属性 | 说明 |
|---|---|
| request.tool_call | 工具调用信息,包括名称、参数和调用 ID |
| request.tool | 当前工具对象,某些情况下可能为 None |
| request.state | 当前 Agent State |
| request.runtime | 当前 ToolRuntime,可访问运行时上下文 |
| request.override() | 生成修改后的工具调用请求 |
ToolRetryMiddleware 常用配置参数
| 参数 | 说明 |
|---|---|
| max_retries | 第一次执行失败后,允许的额外重试次数 |
| tools | 指定需要应用重试的工具 |
| retry_on | 允许重试的异常类型或判断函数 |
| on_failure | 重试失败后继续返回错误消息或抛出异常 |
| initial_delay | 初始等待时间 |
| backoff_factor | 指数退避系数 |
| max_delay | 最大等待时间 |
| jitter | 是否添加随机等待抖动 |
不同类型工具的缓存适用性评估
| 工具类型 | 是否适合缓存 | 说明 |
|---|---|---|
| 静态教程目录 | 适合 | 内容变化较少 |
| 公共配置查询 | 视情况 | 需要设置缓存有效期 |
| 实时天气、股票价格 | 谨慎 | 数据具有时效性 |
| 用户私人信息 | 谨慎 | 必须考虑用户隔离 |
| 创建订单、发送邮件 | 不宜简单缓存 | 属于有副作用的操作 |
多个工具中间件的推荐嵌套顺序
| 组合 | 建议顺序 | 原因 |
|---|---|---|
| 监控 + 缓存 | 监控在外 | 统计缓存命中和未命中的整体耗时 |
| 缓存 + 重试 | 缓存在外 | 命中缓存时避免执行重试逻辑 |
| 异常转换 + 重试 | 异常转换在外 | 先允许内部完成重试,最终再转换异常 |
| 参数规范化 + 缓存 | 规范化在外 | 提高缓存键一致性 |
@wrap_model_call 与 @wrap_tool_call 对比
| 对比项 | @wrap_model_call | @wrap_tool_call |
|---|---|---|
| 拦截对象 | 模型请求 | 工具执行 |
| 请求对象 | ModelRequest | ToolCallRequest |
| 主要参数 | model、messages、tools、system_message | tool_call、tool、state、runtime |
| 常见返回值 | ModelResponse、AIMessage 等 | ToolMessage、Command |
| 典型用途 | 模型重试、降级、动态请求修改 | 工具重试、参数规范化、结果缓存 |
| 内置重试 | ModelRetryMiddleware | ToolRetryMiddleware |
离线实测 @wrap_tool_call 参数规范化、工具重试、只读缓存、错误转换与 Command/异步路径
"""Offline runtime lab for LangChain Ch 24: wrap-tool-call."""
from __future__ import annotations
import asyncio
import json
import platform
from typing import Any
from typing_extensions import NotRequired
from langchain.agents import AgentState, create_agent
import langchain.agents.middleware as lam
from langchain.agents.middleware import (
ToolErrorMiddleware,
ToolRetryMiddleware,
wrap_tool_call,
)
from langchain.agents.middleware.types import ToolCallRequest
from langchain.messages import AIMessage, ToolMessage
from langchain.tools import ToolRuntime, tool
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.outputs import ChatGeneration, ChatResult
from langgraph.types import Command
from pydantic import Field
class TemporaryServiceError(Exception):
"""模拟外部课程服务临时故障。"""
class ScriptedChatModel(BaseChatModel):
responses: list[Any] = Field(default_factory=list)
cursor: list[int] = Field(default_factory=lambda: [0])
@property
def _llm_type(self) -> str:
return "scripted-offline"
def bind_tools(self, tools: Any, **kwargs: Any) -> "ScriptedChatModel":
return self.model_copy()
def _generate(self, messages: list[Any], stop: Any = None, run_manager: Any = None, **kwargs: Any) -> ChatResult:
idx = self.cursor[0]
self.cursor[0] += 1
item = self.responses[idx] if idx < len(self.responses) else AIMessage(content="done")
msg = item(messages) if callable(item) else item
return ChatResult(generations=[ChatGeneration(message=msg)])
async def _agenerate(self, messages: list[Any], stop: Any = None, run_manager: Any = None, **kwargs: Any) -> ChatResult:
return self._generate(messages, stop=stop, run_manager=run_manager, **kwargs)
def case_tool_call_request_and_arg_normalization() -> dict[str, Any]:
inspected: dict[str, Any] = {}
received_args: list[str] = []
@tool
def get_weather(city: str) -> str:
"""查询城市模拟天气。"""
received_args.append(city)
return {"杭州": "晴,25°C"}.get(city, "未知城市")
@wrap_tool_call
def normalize_city(request: ToolCallRequest, handler: Any) -> ToolMessage | Command:
inspected["attrs"] = sorted(
k for k in ("tool_call", "tool", "state", "runtime", "override") if hasattr(request, k)
)
call = request.tool_call
inspected["arg_keys"] = sorted(call.get("args", {}).keys())
orig_city = call["args"]["city"]
if call["name"] == "get_weather":
args = dict(call["args"])
args["city"] = args["city"].replace("\u3000", " ").strip()
new_req = request.override(tool_call={**call, "args": args})
inspected["orig_unchanged"] = request.tool_call["args"]["city"] == orig_city
return handler(new_req)
return handler(request)
model = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[{"name": "get_weather", "args": {"city": " 杭州\u3000"}, "id": "call_city", "type": "tool_call"}],
),
AIMessage(content="杭州模拟天气:晴,25°C"),
]
)
res = create_agent(model=model, tools=[get_weather], middleware=[normalize_city]).invoke(
{"messages": [{"role": "user", "content": "查杭州天气"}]}
)
tool_msg = next(m for m in res["messages"] if m.type == "tool")
actual = {
**inspected,
"tool_received_city": received_args[0],
"tool_msg_content": tool_msg.content,
"tool_call_id_match": tool_msg.tool_call_id == "call_city",
}
expected = {
"attrs": ["override", "runtime", "state", "tool", "tool_call"],
"arg_keys": ["city"],
"orig_unchanged": True,
"tool_received_city": "杭州",
"tool_msg_content": "晴,25°C",
"tool_call_id_match": True,
}
return {
"name": "tool_call_request_and_arg_normalization",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_custom_retry_and_builtin_tool_retry() -> dict[str, Any]:
attempts_custom: dict[str, int] = {}
@tool
def fetch_course_custom(course_id: str) -> str:
"""模拟前两次临时故障、第三次成功的课程查询。"""
attempts_custom[course_id] = attempts_custom.get(course_id, 0) + 1
if attempts_custom[course_id] < 3:
raise TemporaryServiceError("模拟课程服务暂时不可用")
return f"{course_id}:Python3 基础教程,免费"
@wrap_tool_call
def retry_course_tool(request: ToolCallRequest, handler: Any) -> Any:
for attempt in range(3):
try:
res = handler(request)
if isinstance(res, ToolMessage) and res.status == "error":
return res
return res
except TemporaryServiceError:
if attempt == 2:
raise
raise RuntimeError("unreachable")
m1 = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[{"name": "fetch_course_custom", "args": {"course_id": "python-001"}, "id": "tc_c1", "type": "tool_call"}],
),
AIMessage(content="查询成功"),
]
)
res_c = create_agent(model=m1, tools=[fetch_course_custom], middleware=[retry_course_tool]).invoke(
{"messages": [{"role": "user", "content": "查 python-001"}]}
)
tool_msg_c = next(m for m in res_c["messages"] if m.type == "tool")
# Built-in ToolRetryMiddleware success on 3rd attempt
attempts_bi = [0]
@tool
def fetch_course_bi(course_id: str) -> str:
"""内置重试测试工具。"""
attempts_bi[0] += 1
if attempts_bi[0] < 3:
raise TemporaryServiceError("temp down")
return f"{course_id}:内置重试成功"
m2 = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[{"name": "fetch_course_bi", "args": {"course_id": "py-2"}, "id": "tc_b1", "type": "tool_call"}],
),
AIMessage(content="ok"),
]
)
res_b = create_agent(
model=m2,
tools=[fetch_course_bi],
middleware=[
ToolRetryMiddleware(
tools=["fetch_course_bi"],
max_retries=2,
retry_on=(TemporaryServiceError,),
on_failure="continue",
initial_delay=0.0,
jitter=False,
)
],
).invoke({"messages": [{"role": "user", "content": "查 py-2"}]})
tool_msg_b = next(m for m in res_b["messages"] if m.type == "tool")
# Built-in ToolRetryMiddleware on_failure="continue" vs "error"
fail_cnt = [0]
@tool
def always_fail(course_id: str) -> str:
"""总是抛出临时异常。"""
fail_cnt[0] += 1
raise TemporaryServiceError("still down")
m3 = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[{"name": "always_fail", "args": {"course_id": "x"}, "id": "tc_f1", "type": "tool_call"}],
),
AIMessage(content="收到错误消息"),
]
)
res_cont = create_agent(
model=m3,
tools=[always_fail],
middleware=[
ToolRetryMiddleware(
tools=["always_fail"],
max_retries=1,
retry_on=(TemporaryServiceError,),
on_failure="continue",
initial_delay=0.0,
jitter=False,
)
],
).invoke({"messages": [{"role": "user", "content": "fail continue"}]})
cont_tool_msg = next(m for m in res_cont["messages"] if m.type == "tool")
# Tool returning ToolMessage(status="error") directly does NOT trigger exception retry
err_msg_runs = [0]
@tool
def returns_error_msg(course_id: str, runtime: ToolRuntime) -> ToolMessage:
"""直接返回错误 ToolMessage 而不抛异常。"""
err_msg_runs[0] += 1
return ToolMessage(content="软错误", tool_call_id=runtime.tool_call_id, name="returns_error_msg", status="error")
m4 = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[{"name": "returns_error_msg", "args": {"course_id": "x"}, "id": "tc_soft", "type": "tool_call"}],
),
AIMessage(content="ok"),
]
)
create_agent(model=m4, tools=[returns_error_msg], middleware=[retry_course_tool]).invoke(
{"messages": [{"role": "user", "content": "soft err"}]}
)
actual = {
"custom_attempts": attempts_custom["python-001"],
"custom_result": tool_msg_c.content,
"builtin_attempts": attempts_bi[0],
"builtin_result": tool_msg_b.content,
"continue_attempts": fail_cnt[0],
"continue_msg_status": cont_tool_msg.status,
"soft_error_not_retried_runs": err_msg_runs[0],
}
expected = {
"custom_attempts": 3,
"custom_result": "python-001:Python3 基础教程,免费",
"builtin_attempts": 3,
"builtin_result": "py-2:内置重试成功",
"continue_attempts": 2,
"continue_msg_status": "error",
"soft_error_not_retried_runs": 1,
}
return {
"name": "custom_retry_and_builtin_tool_retry",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_readonly_tool_cache_and_nesting_order() -> dict[str, Any]:
tool_calls_executed = [0]
cache: dict[str, str] = {}
order_log: list[str] = []
@tool
def search_course(keyword: str) -> str:
"""查询模拟课程。"""
tool_calls_executed[0] += 1
return {"python": "Python3 基础教程", "java": "Java 基础教程"}.get(keyword, "未找到相关课程")
@wrap_tool_call
def normalize_kw(request: ToolCallRequest, handler: Any) -> Any:
order_log.append("norm_in")
call = request.tool_call
args = dict(call["args"])
if isinstance(args.get("keyword"), str):
args["keyword"] = args["keyword"].strip().lower()
request = request.override(tool_call={**call, "args": args})
res = handler(request)
order_log.append("norm_out")
return res
@wrap_tool_call
def cache_course(request: ToolCallRequest, handler: Any) -> Any:
order_log.append("cache_in")
call = request.tool_call
key = json.dumps(call["args"], sort_keys=True, ensure_ascii=False)
if key in cache:
order_log.append("cache_hit")
return ToolMessage(content=cache[key], tool_call_id=call["id"], name=call["name"])
res = handler(request)
if isinstance(res, ToolMessage) and res.status != "error" and isinstance(res.content, str):
cache[key] = res.content
order_log.append("cache_write")
return res
@wrap_tool_call
def inner_retry_probe(request: ToolCallRequest, handler: Any) -> Any:
order_log.append("inner_run")
return handler(request)
model = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{"name": "search_course", "args": {"keyword": " PYTHON "}, "id": "tc_1", "type": "tool_call"},
{"name": "search_course", "args": {"keyword": "python"}, "id": "tc_2", "type": "tool_call"},
],
),
AIMessage(content="两次均查到 Python3 基础教程"),
]
)
res = create_agent(
model=model,
tools=[search_course],
middleware=[normalize_kw, cache_course, inner_retry_probe],
).invoke({"messages": [{"role": "user", "content": "查两次 Python"}]})
tmsgs = [m for m in res["messages"] if m.type == "tool"]
actual = {
"underlying_tool_executions": tool_calls_executed[0],
"tool_msg_ids": [m.tool_call_id for m in tmsgs],
"tool_msg_contents": [m.content for m in tmsgs],
"order_log": order_log,
}
expected = {
"underlying_tool_executions": 1,
"tool_msg_ids": ["tc_1", "tc_2"],
"tool_msg_contents": ["Python3 基础教程", "Python3 基础教程"],
"order_log": [
"norm_in",
"cache_in",
"inner_run",
"cache_write",
"norm_out",
"norm_in",
"cache_in",
"cache_hit",
"norm_out",
],
}
return {
"name": "readonly_tool_cache_and_nesting_order",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_tool_error_middleware_and_empty_result_formatting() -> dict[str, Any]:
attempts = [0]
@tool
def flaky_course(course_id: str) -> str:
"""按课程 ID 模拟故障。"""
attempts[0] += 1
if course_id == "temp":
raise TemporaryServiceError("backend 503")
if course_id == "bug":
raise KeyError("unexpected bug")
return "未找到相关课程"
def on_tool_error(error: Exception, request: ToolCallRequest) -> str | None:
if isinstance(error, TemporaryServiceError):
return "课程服务暂时不可用,请稍后重试。"
return None
@wrap_tool_call
def format_empty(request: ToolCallRequest, handler: Any) -> Any:
res = handler(request)
if isinstance(res, ToolMessage) and res.content == "未找到相关课程":
return ToolMessage(
content="课程目录中没有匹配结果,可以请用户更换关键词。",
tool_call_id=request.tool_call["id"],
name=request.tool_call["name"],
)
return res
# Compose ToolErrorMiddleware outer + ToolRetryMiddleware inner (on_failure="error")
m_temp = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[{"name": "flaky_course", "args": {"course_id": "temp"}, "id": "tc_t", "type": "tool_call"}],
),
AIMessage(content="服务暂不可用"),
]
)
res_temp = create_agent(
model=m_temp,
tools=[flaky_course],
middleware=[
ToolErrorMiddleware(on_error=on_tool_error, tools=["flaky_course"]),
ToolRetryMiddleware(
tools=["flaky_course"],
max_retries=1,
retry_on=(TemporaryServiceError,),
on_failure="error",
initial_delay=0.0,
jitter=False,
),
],
).invoke({"messages": [{"role": "user", "content": "temp"}]})
temp_msg = next(m for m in res_temp["messages"] if m.type == "tool")
# Unhandled KeyError propagates because on_tool_error returns None
key_err_propagated = False
try:
m_bug = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[{"name": "flaky_course", "args": {"course_id": "bug"}, "id": "tc_b", "type": "tool_call"}],
),
]
)
create_agent(
model=m_bug,
tools=[flaky_course],
middleware=[ToolErrorMiddleware(on_error=on_tool_error, tools=["flaky_course"])],
).invoke({"messages": [{"role": "user", "content": "bug"}]})
except KeyError:
key_err_propagated = True
# Empty result formatted as normal ToolMessage
m_empty = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[{"name": "flaky_course", "args": {"course_id": "missing"}, "id": "tc_m", "type": "tool_call"}],
),
AIMessage(content="请换一个关键词"),
]
)
res_empty = create_agent(model=m_empty, tools=[flaky_course], middleware=[format_empty]).invoke(
{"messages": [{"role": "user", "content": "missing"}]}
)
empty_msg = next(m for m in res_empty["messages"] if m.type == "tool")
actual = {
"retried_then_converted_attempts": attempts[0] - 2, # 2 attempts for temp (plus 1 bug, 1 missing)
"converted_status": temp_msg.status,
"converted_content": temp_msg.content,
"unhandled_key_error_propagated": key_err_propagated,
"empty_formatted_status": empty_msg.status,
"empty_formatted_content": empty_msg.content,
}
expected = {
"retried_then_converted_attempts": 2,
"converted_status": "error",
"converted_content": "课程服务暂时不可用,请稍后重试。",
"unhandled_key_error_propagated": True,
"empty_formatted_status": "success",
"empty_formatted_content": "课程目录中没有匹配结果,可以请用户更换关键词。",
}
return {
"name": "tool_error_middleware_and_empty_result_formatting",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_command_state_update_and_async_wrap_tool_call() -> dict[str, Any]:
class ProgressState(AgentState):
completed_topics: NotRequired[list[str]]
@tool
def complete_topic(topic: str, runtime: ToolRuntime) -> Command:
"""记录已完成的学习主题。"""
topics = list(runtime.state.get("completed_topics", []))
if topic not in topics:
topics.append(topic)
return Command(
update={
"completed_topics": topics,
"messages": [ToolMessage(content=f"已记录完成:{topic}", tool_call_id=runtime.tool_call_id)],
}
)
saw_command = [False]
@wrap_tool_call
def passthrough_wrapper(request: ToolCallRequest, handler: Any) -> ToolMessage | Command:
res = handler(request)
if isinstance(res, Command):
saw_command[0] = True
return res
m_cmd = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[{"name": "complete_topic", "args": {"topic": "middleware"}, "id": "tc_cmd", "type": "tool_call"}],
),
AIMessage(content="已完成登记"),
]
)
res_cmd = create_agent(
model=m_cmd,
tools=[complete_topic],
state_schema=ProgressState,
middleware=[passthrough_wrapper],
).invoke({"messages": [{"role": "user", "content": "完成 middleware"}]})
# Async wrap_tool_call contract in LangChain 1.4.9
async_trace: list[str] = []
@tool
async def async_echo(text: str) -> str:
"""异步回显工具。"""
return f"echo:{text}"
@wrap_tool_call
async def async_tool_monitor(request: ToolCallRequest, handler: Any) -> Any:
async_trace.append(f"in:{request.tool_call['name']}")
try:
return await handler(request)
finally:
async_trace.append(f"out:{request.tool_call['name']}")
m_async = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[{"name": "async_echo", "args": {"text": "ok"}, "id": "tc_a", "type": "tool_call"}],
),
AIMessage(content="异步完成"),
]
)
res_async = asyncio.run(
create_agent(model=m_async, tools=[async_echo], middleware=[async_tool_monitor]).ainvoke(
{"messages": [{"role": "user", "content": "async"}]}
)
)
async_tmsg = next(m for m in res_async["messages"] if m.type == "tool")
actual = {
"saw_command_in_wrapper": saw_command[0],
"completed_topics": res_cmd.get("completed_topics"),
"awrap_tool_call_exported": hasattr(lam, "awrap_tool_call"),
"async_trace": async_trace,
"async_tool_result": async_tmsg.content,
}
expected = {
"saw_command_in_wrapper": True,
"completed_topics": ["middleware"],
"awrap_tool_call_exported": False,
"async_trace": ["in:async_echo", "out:async_echo"],
"async_tool_result": "echo:ok",
}
return {
"name": "command_state_update_and_async_wrap_tool_call",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main() -> None:
cases = [
case_tool_call_request_and_arg_normalization(),
case_custom_retry_and_builtin_tool_retry(),
case_readonly_tool_cache_and_nesting_order(),
case_tool_error_middleware_and_empty_result_formatting(),
case_command_state_update_and_async_wrap_tool_call(),
]
print(
json.dumps(
{"version": platform.python_version(), "system": platform.system(), "cases": cases},
ensure_ascii=False,
indent=2,
)
)
if __name__ == "__main__":
main()
- 验证 ToolCallRequest.override 不可变规范化、自定义与 ToolRetryMiddleware 重试及软错误不重试、规范化+缓存嵌套命中、ToolErrorMiddleware+ToolRetryMiddleware 组合与空结果整理,以及 Command 状态写入与异步装饰器实测。
所需环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。
当前源码 SHA256:592ef6b7dc85da4f4c672d9843a30bf03b5b45fce531a29f83b4d53eea94450d
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。
ZIP SHA256:3553009784b8a10849bcc5a3cc360e64bb8f0bab2e503f5e19e3e3e9446c0de6
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么将 ToolErrorMiddleware 与 ToolRetryMiddleware 组合使用时,应把 ToolErrorMiddleware 放在外层、并将 ToolRetryMiddleware 的 on_failure 设为 'error'?
展开参考解答
因为 Wrap-style 中间件首项位于最外层:若内层 ToolRetryMiddleware 设为 on_failure='continue' 会直接吞掉异常返回默认错误消息,外层自定义 ToolErrorMiddleware 永远不会触发;设为 'error' 后,内层先完成所有重试,全部失败后再将异常上抛给外层 ToolErrorMiddleware 统一转换为业务友好提示。