Tool Execution

Tool Execution 是真正执行工具逻辑的过程,包括调用 handler、处理异步、超时控制和结果捕获。

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

[!info] related notes

Tool Execution

一句话定义

Tool Execution 是真正执行工具逻辑的过程。在完成参数校验、权限检查后,调用工具的 handler 函数,捕获返回值和异常。

核心原理

执行流程

参数校验通过


权限检查通过


注入运行时参数 (user_id, session_id)


调用 handler

    ├─ 成功 → 返回结果
    ├─ 超时 → 返回超时错误
    └─ 异常 → 返回错误信息

Python 实现

class ToolExecutor:
    async def execute(self, tool: Tool, args: dict, context: ExecutionContext) -> ToolResult:
        # 注入运行时参数
        enriched_args = self.enrich_args(args, context)

        # 执行(带超时)
        try:
            if asyncio.iscoroutinefunction(tool.handler):
                result = await asyncio.wait_for(
                    tool.handler(**enriched_args),
                    timeout=tool.timeout,
                )
            else:
                result = tool.handler(**enriched_args)

            return ToolResult(data=result)
        except asyncio.TimeoutError:
            return ToolResult(error=f"Timeout after {tool.timeout}s")
        except Exception as e:
            return ToolResult(error=f"{type(e).__name__}: {str(e)}")

    def enrich_args(self, args: dict, context: ExecutionContext) -> dict:
        enriched = args.copy()
        enriched["user_id"] = context.user_id
        enriched["session_id"] = context.session_id
        return enriched

常见坑

  1. 不做超时控制: handler 卡死
  2. 不做异常捕获: handler 抛异常导致 Agent 崩溃
  3. 不注入运行时参数: handler 需要 user_id 但 LLM 不知道

参考资料

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