AstrBot icon indicating copy to clipboard operation
AstrBot copied to clipboard

[Bug] spawn_agent 的 config_id 缺少候选约束,模型手抄 UUID 易错(建议动态生成 enum)

Open AmeiMiao opened this issue 2 days ago • 3 comments

现象

spawn_agent 的 config_id 在 schema 里只是一个裸字符串(type: string、minLength: 1),没有任何可选值约束。有效 ID 只以 JSON 文本形式塞在 system prompt 的 <agent_configs> 里,模型必须跨几 KB 上下文手抄一个 36 位 UUID。

实测(QQ 私聊,4 个 agent_config):

08:08:54  Agent 使用工具: ['spawn_agent']
          参数:{'config_id': '10a7f6e9-...', 'name': 'heyboxer', ...}
          Tool Result: Agent configuration is not selected by this profile: 10a7f6e9-...
08:08:58  Agent 使用工具: ['spawn_agent']      ← 重试
          参数:{'config_id': '0a8df6e9-...', ...}
          → 成功

首字母 0 抄成了 1,其余 35 位全对。模型自己重试成功了,但白花了 3.5 秒和一次完整 tool round-trip;如果换成长上下文或多轮委派,这类失败会累积。

为什么不是模型的问题

三层原因叠在一起:

  1. schema 无约束:config_id 没有 enum、没有 pattern,JSON Schema 层面完全无法拦截。
  2. 目录靠自然语言传递:只出现在 system prompt 的一段 JSON 里,不进 schema;模型抄写时没有任何机制校验。
  3. 报错不回带候选:runtime.py 抛的 ValueError 只说了「这个 ID 不在名单里」,没给可用列表,模型只能回头翻 system prompt 重抄一遍,而不是就地改正。

现有工具也兜不住:list_agents 列的是已打开的 agent,不是可用配置目录,所以没法用它发现合法 config_id。

相关代码

astrbot/core/astr_agent_runtime/tools/subagent.py:66-71

"messages": copy.deepcopy(SUBAGENT_MESSAGES_SCHEMA),
"config_id": {
    "type": "string",
    "minLength": 1,
    "description": "Optional reusable agent spec ID from the system catalog.",
},

目录注入在 astrbot/core/astr_agent_runtime/main_agent/subagent.py:108-137:先 for tool_type in (...): tool = tool_type() 构造工具(96-101),随后才 if req.func_tool.get_tool("spawn_agent") is not None: 计算 configurations 并拼进 system prompt(108-137)。

校验在 astrbot/core/astr_agent_runtime/runtime.py:107-111:

if config_id is not None:
    if config_id not in policy.get("config_ids", []):
        raise ValueError(
            f"Agent configuration is not selected by this profile: {config_id}"
        )

建议修法

关键点:构造 enum 所需的数据,在同一函数里已经算好了。 main_agent/subagent.py:109-127 那段循环已经按「enabled 且 runtime 可用」过滤出精确的 configurations,它才是真正的合法集合(比 policy["config_ids"] 原始值更准,后者可能含 disabled 项)。现在只是没把它传给 schema。

建议让 SpawnAgentTool 接受候选 ID 列表:

class SpawnAgentTool(FunctionTool):
    name = "spawn_agent"

    def __init__(self, config_ids: list[str] | None = None) -> None:
        config_id_schema: dict[str, Any] = {
            "type": "string",
            "minLength": 1,
            "description": "Optional reusable agent spec ID from the system catalog.",
        }
        if config_ids:
            config_id_schema["enum"] = list(config_ids)
        super().__init__(
            name="spawn_agent",
            description=...,
            parameters={
                "type": "object",
                "properties": {
                    "messages": copy.deepcopy(SUBAGENT_MESSAGES_SCHEMA),
                    "config_id": config_id_schema,
                    "name": {...},
                },
                "required": ["messages"],
                "additionalProperties": False,
            },
            handler_module_path=_HANDLER_MODULE,
        )

对应 hook 里需要把「算目录」提到「建工具」之前(当前顺序相反,因为目录计算以 get_tool("spawn_agent") is not None 为前置条件)。把 108-127 抽成一个小函数即可:

    if not enabled or req.conversation is None or runtime is None:
        return True

    configurations = await build_subagent_catalog(config, runtime)   # 抽出来的 109-127
    config_ids = [c["config_id"] for c in configurations]

    for tool_type in (SpawnAgentTool, ListAgentsTool, ...):
        tool = tool_type(config_ids) if tool_type is SpawnAgentTool else tool_type()
        if tool.active:
            req.func_tool.add_tool(tool)

    if config_ids:
        req.system_prompt += ("\n<subagent_instructions>\n" ... )

注意 enum 不能顺手把 config_id 变成必填:config_id=None 是「通用 native worker」这条合法路径,要保留可选语义。

可选的小加固(与本 issue 独立,但同一处痛点):错误信息回带候选,让模型能就地改而不是重读 prompt:

raise ValueError(
    f"Agent configuration is not selected by this profile: {config_id}. "
    f"Available config_ids: {', '.join(policy.get('config_ids', []))}"
)

兼容性

三种 provider 的 schema 序列化都吃得住 string enum:

  • openai_schema():parameters 原样透传(tool.py:221-225)
  • anthropic_schema():input_schema.update(copy.deepcopy(tool.parameters)),enum 保留(tool.py:242-251)
  • google_schema():convert_schema() 的 support_fields 含 enum,且对非 string enum 有降级处理;config_id 本身就是 string,不受影响(tool.py:300-320)

另外 ToolSchema.validate_parameters 会用 Draft 2020-12 元 schema 校验,enum 是合法关键字,不会有副作用。

另一个更彻底的方向(供参考,不要求在本 issue 内做)

configurations 里本来就有 name(painter / archivist / heyboxer 这种可读短名)。如果能允许按 name 派活、内部再解析成 config_id,对模型来说比抄 UUID 稳得多——三个字符 vs 三十六个。可以做成「config_id 与 agent 二选一,先按 id 精确匹配,再按 name 匹配」,也可以只把 name 塞进 description 让模型自己对照。这个改动面比 enum 大,单独讨论更合适。

环境

  • AstrBot 4.30.0(pyproject.toml 版本行确认)
  • Python 3.12,Linux 容器
  • 4 个 agent_config,subagents.enabled = true
  • 未修改任何核心代码

如果 enum 方案你认为 OK,我可以提 PR(含 tests/unit/subagent/ 下的用例:合法 ID 出现在 enum 中、disabled 配置不进 enum、config_id 省略时仍可派通用 worker)。

AmeiMiao avatar Dec 02 '26 00:12 AmeiMiao

I would like to fix this myself.

The diagnosis matches what the schema shows: config_id is a bare string with only minLength: 1, so nothing constrains it to the IDs the profile actually has, and the model has to copy a UUID out of the prompt. I would generate an enum from the profile's agent_configs when the tool schema is built, so the constraint travels with the schema instead of living in the prompt text, and keep the existing runtime check as the backstop for a stale or hand-written ID.

One question before I write it: the IDs are per-profile (the error message says "not selected by this profile"), so the schema has to be rebuilt whenever the profile's agent configs change. I will look for the place that already rebuilds tool schemas for a profile and hook into it there rather than building the enum once at import time. If you would rather keep the schema static and validate in the tool body only, say so and I will do that instead.

Please assign @Luckyou-d if available.

Luckyou-d avatar Dec 02 '26 04:12 Luckyou-d

Good approach — constraining it in the schema rather than in the prompt text is the right direction. Two concrete answers:

1. Where to hook it: you don't need a cache-invalidation hook at all.

The subagent tools are rebuilt from scratch on every request build. In astr_agent_runtime/main_agent/subagent.py, apply_subagents() first removes the previous instances, then constructs new ones:

for name in SUBAGENT_TOOL_NAMES:
    req.func_tool.remove_tool(name)
...
for tool_type in (SpawnAgentTool, ListAgentsTool, WaitAgentTool, ...):
    tool = tool_type()
    if tool.active:
        req.func_tool.add_tool(tool)

So move the configurations computation (currently lines 108-137) to before that loop and hand the ids to SpawnAgentTool.__init__ — you get a per-profile schema for free, and a profile change takes effect on the next request. apply_subagents() is called from main_agent/builder.py:183 on every request build, so there is no path where a stale schema survives.

I'd pass it into the constructor rather than mutating tool.parameters afterwards, so the schema can't drift from the catalog that gets rendered into the system prompt.

2. Two traps worth handling.

  • Don't emit "enum": []. configurations can legitimately be empty (all configs disabled, or their runtime unavailable). An empty enum in JSON Schema means "no value is valid", and several OpenAI-compatible providers reject it outright — the model ends up unable to pass the field at all. When the list is empty, drop the config_id property entirely instead of leaving an empty enum; a generic native worker is the only option in that case anyway.
  • Build the enum from the filtered list, not from config_ids. The runtime check uses the raw policy (runtime.py:108-110: if config_id not in policy.get("config_ids", [])), while configurations is additionally filtered by enabled and by agent_config.runtime in runtime.subagents.runtimes. If you enumerate the raw list you would advertise ids that the catalog never mentions and that may fail at dispatch. Schema stricter than the runtime check is the direction you want, so enumerate configurations.

Keep the runtime ValueError as-is as the backstop — a config can be deleted or disabled between the schema build and the tool call.

Minor points: keep config_id out of required (omitting it must still mean "generic native worker"), and leave the description referring to the catalog so the model knows the ids and names are related.

For tests, tests/unit/subagent/ already exists; worth asserting (a) the enum equals the enabled-and-available ids in config order, (b) the config_id property disappears when that list is empty, (c) a stale id still raises from the runtime path.

On assignment: I'm the issue reporter, not a maintainer, so I can't assign — opening the PR referencing #11576 is the fastest route.

AmeiMiao avatar Dec 02 '26 04:12 AmeiMiao

Opened #11584. I did not go with the generated enum, and the reason is worth recording here: test_profile_selection_is_enforced_in_prompt_and_spawn asserts that func_tool.openai_schema() stays identical whether or not the profile has selectable configurations, so the tool schema is deliberately static and the per-profile selection is enforced through the prompt catalog plus the runtime check. An enum broke that test.

So the PR keeps the schema as it is and instead makes the rejection name the selectable ids:

Agent configuration is not selected by this profile: 10a7f6e9-... . Selectable config ids: 0a8df6e9-..., 5c1f...

That still removes the blind retry from your trace (the model can correct in one attempt instead of transcribing again), without moving the per-profile constraint into the schema. If you or the maintainers would rather have the enum and relax that schema-equality assertion, say so and I will redo it that way - the enum version is written and just needs the assertion changed.

Luckyou-d avatar Dec 02 '26 05:12 Luckyou-d