Tool Executor
Tool Executor 是 Tool Runtime 中真正执行工具逻辑的模块。它负责调用工具的 handler 函数、处理返回值和捕获异常。
#concept
#evergreen
#ai
[!info] related notes
- 所属 MOC: Tool Calling Engineering MOC
- 相关: Tool Runtime, Tool Registry
Tool Executor
一句话定义
Tool Executor 是真正执行工具逻辑的模块。Tool Runtime 负责校验和控制,Tool Executor 负责”调用函数并返回结果”。
核心原理
最小异步调用示例
下面只演示适配器调用:handler 统一接收业务参数和独立的可信 context。调用前的校验、鉴权、审批与审计由 Tool Runtime 负责;此函数不能作为绕过 Runtime 的公开入口。
from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass
from typing import Any
import asyncio
@dataclass(frozen=True)
class ExecutionContext:
user_id: str
session_id: str
Handler = Callable[[Mapping[str, Any], ExecutionContext], Awaitable[Any]]
async def execute_handler(
handler: Handler,
args: Mapping[str, Any],
context: ExecutionContext,
timeout: float,
) -> Any:
if timeout <= 0:
raise ValueError("timeout must be positive")
# 只适用于协作式异步 handler;超时会请求取消,不保证副作用回滚。
return await asyncio.wait_for(handler(dict(args), context), timeout=timeout)
不要通过“args 没有 user_id 才注入”的方式取身份:模型传来的同名字段不能覆盖认证主体。即使分开传 context,handler 仍需按可信主体验证目标资源,不能把任意 args 当 SQL、路径或 URL 直接执行。
同步与异步适配
- 异步 I/O:统一为可等待的 handler,并传播取消和下游超时。
- 阻塞 I/O:可用受限线程池适配;取消等待不会杀死已经运行的线程。
- CPU 密集或不可信代码:放到受限 worker/子进程,明确终止和资源回收;普通线程不是沙箱。
不能只用 iscoroutinefunction 判断后把所有同步函数直接放进事件循环。async 函数内部调用阻塞库同样会阻塞循环。
常见坑
- 身份来自模型参数:可信 context 与业务参数分离。
- 调用超时当作终止:见 Tool Timeout,远端副作用可能仍在继续。
- 重复实现结果处理:执行器产出结果,归一化层负责输出契约。
- 吞掉取消:保留取消信号,清理资源后向上传播;业务错误由上层分类。