Tool Runtime

Tool Runtime 是 AI Service 中负责工具执行的运行时环境,包括参数校验、权限检查、沙箱执行、超时控制、错误处理和结果归一化。

#type / concept #status / evergreen #tech / ai #tech / architecture

[!info] related notes

Tool Runtime

一句话定义

Tool Runtime 是 AI Service 中负责工具执行的运行时环境。它不只是调用函数,而是在调用前后做参数校验、权限检查、沙箱隔离、超时控制、错误处理和结果归一化。

核心原理

执行流程

LLM 输出 tool_call


Tool Runtime
    ├─ 1. 查找工具 (ToolRegistry)
    ├─ 2. 参数校验 (JSON Schema)
    ├─ 3. 权限检查
    ├─ 4. 审批检查 (高风险)
    ├─ 5. 执行 (带超时和沙箱)
    ├─ 6. 结果归一化
    ├─ 7. 错误处理
    └─ 8. 审计记录


返回 ToolResult

Python 实现

class ToolRuntime:
    def __init__(self, registry: ToolRegistry, sandbox: Sandbox = None):
        self.registry = registry
        self.sandbox = sandbox

    async def execute(self, tool_call: ToolCall, context: ExecutionContext) -> ToolResult:
        # 1. 查找工具
        tool = self.registry.get(tool_call.name)
        if not tool:
            return ToolResult(error=f"Tool not found: {tool_call.name}")

        # 2. 参数校验
        try:
            validated_args = self.validate_args(tool.parameters, tool_call.arguments)
        except ValidationError as e:
            return ToolResult(error=f"Invalid arguments: {e}")

        # 3. 权限检查
        if not self.check_permission(context.user, tool):
            return ToolResult(error="Permission denied")

        # 4. 审批检查
        if tool.requires_approval and not context.approved:
            return ToolResult(interrupt=InterruptRequest(
                type="approval_required",
                tool_call=tool_call,
                message=f"即将执行 {tool.name},确认吗?",
            ))

        # 5. 执行(带超时)
        try:
            if self.sandbox:
                result = await self.sandbox.execute(tool.handler, validated_args, timeout=tool.timeout)
            else:
                result = await asyncio.wait_for(
                    tool.handler(validated_args, context),
                    timeout=tool.timeout,
                )
            return ToolResult(data=result)
        except asyncio.TimeoutError:
            return ToolResult(error=f"Tool execution timeout ({tool.timeout}s)")
        except Exception as e:
            return ToolResult(error=str(e))

常见坑

  1. 不做参数校验: 模型传了非法参数直接崩溃
  2. 不做超时控制: 工具执行卡住
  3. 不做沙箱隔离: 工具崩溃影响整个 Agent
  4. 错误信息太技术化: 模型看不懂错误信息

参考资料

创建于 2026/6/30 更新于 2026/7/15