Skip to content

工具 Handlers(默认与替换)

大多数工具场景不需要自己重写 Tool Loop。只有当默认的“规划 -> 执行 -> 注入结果”流程已经不够时,才应该进入 handler 层。

适合什么时候读

  • 你已经在用工具系统,并且默认 Tool Loop 已经跑通
  • 你想改工具规划逻辑或执行逻辑
  • 你需要更严格的审计、并发控制或执行协议

你会学到什么

  • plan_analysis_handlertool_execution_handler 分别负责什么
  • 为什么规划和执行必须分开
  • 什么时候该替换 handler,什么时候应该继续用默认实现

Tool Loop 的关键断点

这张图要说明的是: 真正适合替换的只有两个断点, 一个负责决策, 一个负责副作用。

最小心智模型

  • 规划器只决定“接下来要不要执行工具、执行哪些工具”
  • 执行器只负责“把这些工具真正跑起来并记录结果”
  • 结果注入和后续轮次衔接,最好继续保留框架默认协议

plan_analysis_handler

职责:

  • 决定本轮是继续执行工具,还是直接回答
  • 产出标准化的 execution_commands

典型签名:

python
async def custom_plan_handler(
    prompt,
    settings,
    tool_list,
    done_plans,
    last_round_records,
    round_index,
    max_rounds,
    agent_name,
):
    ...

典型返回:

python
{
    "next_action": "execute" | "response",
    "execution_commands": [
        {
            "purpose": str,
            "tool_name": str,
            "tool_kwargs": dict,
            "todo_suggestion": str,
        }
    ],
}

tool_execution_handler

职责:

  • 执行 execution_commands
  • 返回可审计的执行记录

典型签名:

python
async def custom_execution_handler(
    tool_commands,
    settings,
    async_call_tool,
    done_plans,
    round_index,
    concurrency,
    agent_name,
):
    ...

典型返回:

python
[
    {
        "purpose": str,
        "tool_name": str,
        "kwargs": dict,
        "todo_suggestion": str,
        "success": bool,
        "result": object,
        "error": str,
    }
]

什么时候真的需要自定义

  • 你要接入内部审计、签名或额外执行网关
  • 默认规划器无法满足你的决策协议
  • 你需要更细的并发、重试或错误记录策略

如果你只是想接入 Search、Browse、Cmd、MCP 或 FastAPI,不需要从这里开始,先用原生扩展入口。

如何注册和恢复默认

python
from agently import Agently

agent = Agently.create_agent()

agent.register_tool_plan_analysis_handler(custom_plan_handler)
agent.register_tool_execution_handler(custom_execution_handler)

# 恢复默认
agent.register_tool_plan_analysis_handler(None)
agent.register_tool_execution_handler(None)

常见误区

  • 在规划器里直接执行副作用,导致“决策”和“执行”混在一起。
  • 在执行器里重新做一遍业务推理,导致协议边界失效。
  • 还没用好默认工具系统,就先从 handler 层开始重写。

下一步去哪

  • agently-agent-extensions
  • agently-tools