Skip to content

工具 Handlers(默认与替换)

适用版本:4.0.8.1+

本页对应“关键 handlers 默认怎么工作、怎么替换”。

1) 两个关键 handler

Tool Loop 的可扩展点只有两类:

  1. plan_analysis_handler:做本轮决策(next_action + execution_commands
  2. tool_execution_handler:执行 execution_commands 并返回记录

2) 默认 handler 的行为

2.1 默认 Plan Handler

默认行为:

  1. 构建独立 ModelRequest 做规划
  2. 输出结构强约束为 next_action + execution_commands[]
  3. 监听 instant,若提前捕获 next_action=response 则短路返回

默认决策结构(推荐):

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

2.2 默认 Execution Handler

默认行为:

  1. tool.loop.concurrency 并发执行工具
  2. 每条命令调用 async_call_tool(tool_name, tool_kwargs)
  3. 产出标准记录(success/result/error)

3) 在 Agent 层替换 handler

python
from agently import Agently

agent = Agently.create_agent()

async def custom_plan_handler(
    prompt,
    settings,
    tool_list,
    done_plans,
    last_round_records,
    round_index,
    max_rounds,
    agent_name,
):
    if round_index > 0:
        return {"next_action": "response", "execution_commands": []}
    return {
        "next_action": "execute",
        "execution_commands": [
            {
                "purpose": "calc",
                "tool_name": "add",
                "tool_kwargs": {"a": 1, "b": 2},
                "todo_suggestion": "完成后可回复",
            }
        ],
    }


async def custom_execution_handler(
    tool_commands,
    settings,
    async_call_tool,
    done_plans,
    round_index,
    concurrency,
    agent_name,
):
    records = []
    for command in tool_commands:
        result = await async_call_tool(command["tool_name"], command.get("tool_kwargs", {}))
        records.append(
            {
                "purpose": command.get("purpose", ""),
                "tool_name": command.get("tool_name", ""),
                "kwargs": command.get("tool_kwargs", {}),
                "todo_suggestion": command.get("todo_suggestion", ""),
                "success": True,
                "result": result,
                "error": "",
            }
        )
    return records


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

恢复默认:

python
agent.register_tool_plan_analysis_handler(None)
agent.register_tool_execution_handler(None)

4) 在 Core 层替换(全局)

python
from agently import Agently

Agently.tool.register_plan_analysis_handler(custom_plan_handler)
Agently.tool.register_tool_execution_handler(custom_execution_handler)

5) 只想替换单次调用

你也可以在 Core 调用时临时传入 handler:

  • Tool.async_plan_and_execute(..., plan_analysis_handler=..., tool_execution_handler=...)
  • Tool.async_generate_tool_command(..., plan_analysis_handler=...)

6) 设计建议

  • Plan Handler 保持“纯决策”:只输出结构化指令
  • Execution Handler 保持“纯执行”:少做业务推理
  • 永远返回可审计记录(包含 success/result/error
  • 优先保留 execution_commands 字段,避免混用历史字段