Skip to content

♻️ Refactor: isolate NL2Agent tool protocols and harden creation flow - #4493

Merged
WMC001 merged 7 commits into
developfrom
pyh/refacotr_nl2agent_develop
Nov 30, 2026
Merged

WMC001 merged 7 commits into
developfrom
pyh/refacotr_nl2agent_develop

Conversation

@YehongPan

Copy link
Copy Markdown
Collaborator

[Specification Details]

  1. NL2Agent 共用一套业务提示词。 中文和英文各自保留角色、业务流程和完成条件。工具调用示例和结束格式由 Core Adapter 注入。Smolagents 保留 、print 和原有结束格式,Jiuwen 原生模式使用 tool_calls 和 JSON 参数。共用工具描述也移除了 Python 调用示例。这是后续拆分提示词的样板。
  2. 补齐 OpenAI 兼容层的两处解析。 工具参数尾部多出的 </tool_call> 会被剥掉,随后仍走原有 JSON 解析和参数校验。硅基流动的流式响应中,已建立的同一工具调用允许后续分片省略 type 或传 null。首片显式传 null 仍会被拒绝。这两处兼容对走该适配层的模型通用。
  3. 资源核验漏评时,明确告诉模型补什么。 工具会返回当前批次 ID、漏评的候选及其对应需求,模型可以补齐后重交该批次。当前批次通过后才会推进,全部核验完成后才能出资源卡。
  4. Jiuwen 对提前结束做有限纠正。 用户明确要求完整创建时,Runtime 根据工具实际回执跟踪下一步。模型只保存名称就尝试结束时,会收到下一步指引。资源确认后,流程继续到 Prompt、开场白、示例问题和最终校验。工作台确认表单若被模型当作正文输出,也会触发一次纠正,让模型调用原生确认工具出卡。
  5. 资源确认后,后端主动建立 Prompt 保存基准。 后端用传给模型的同一份已验证草稿和资源绑定状态建立基准。这样 Smolagents 即使跳过 nl2a_read_generation_context,也能在资源确认后直接保存 Prompt。原有的版本冲突校验和已有 Prompt 的覆盖确认仍然生效。
  6. 页面按整轮终态显示执行结果。 单个工具失败仍显示在对应的调用记录里,流程可以继续。消息顶部优先采用 Runtime 的终态,整轮因异常终止时才显示「执行失败」。
  7. 增加环境变量中core可选项提示。

[Test Results]

jiuwen core (Qwen2.5-32B)

img_v3_0217s_40142cad-8981-4521-ac69-d3338d2d1d8g img_v3_0217s_5bac9aad-9815-4b55-9f5e-d49ea2fc2bcg img_v3_0217s_92f3f10d-24dc-4e00-82de-ea63e096feag

jiuwen core (DeepSeek-V4-Flash)

img_v3_0217s_90d3f38c-372f-4710-a1dc-3a035bcff45g img_v3_0217s_c7ebd902-9f60-4603-8870-95b79a79098g

smolagents (Qwen2.5-32B)

img_v3_0217s_218c2846-d544-4bdf-b328-014380dec87g img_v3_0217s_e57bb597-56de-4d95-9b09-efb51cab801g

smolagents (DeepSeek-V4-Flash)

image image

…ent_develop

# Conflicts:
#	frontend/app/[locale]/newchat/adapter/remote-chat-model-adapter.ts
#	frontend/tests/workbench/ExecutionStreamState.test.ts
@codecov

codecov Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

@WMC001
WMC001 merged commit 3dbf17c into develop Nov 30, 2026
14 checks passed
)
self._fail(request, str(error), reason=error.reason)
if not self.text_protocol:
if not calls and self.clarification.has_workbench_form_text(content):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ self.clarification 为 None 时直接调用 has_workbench_form_text 引发 AttributeError

JiuwenServiceModel 构造函数中 clarification 参数默认为 None(签名可见:clarification=None),且 adapter(sdk/nexent/core/agents/cores/jiuwen/adapter.py)仅在 root_clarification_allowed(run_info) 且 response_mode=="chat" 且 enable_nl2a_wrapper 不为 True 时才创建 JiuwenClarification,其余场景(NL2Agent creator 的 response_mode="python_workflow" 配置、子代理、enable_nl2a_wrapper 运行)一律传入 None。新增的 Workbench 确认表单检测在 native 模式(text_protocol=False)下直接执行 self.clarification.has_workbench_form_text(content),缺少 None 检查;同一 PR 中紧邻的 verification_pending / full_generation_pending 两处新增检查都显式写了 is not None,唯独此处遗漏。native 协议规定结束方式为纯文本(core/nl2agent.yaml: "To finish the turn, return the summary as plain text."),因此只要模型在 native 模式返回不带工具调动的纯文本最终回复且 clarification 为 None,就会抛出 AttributeError: 'NoneType' object has no attribute 'has_workbench_form_text';该异常不属于 ModelServiceError,invoke/stream 的 _correct 错误恢复循环无法捕获,整轮运行直接崩溃。

上下文代码:

            if not self.text_protocol:
                if not calls and self.clarification.has_workbench_form_text(content):
                    self._workbench_confirmation_required = True
                if self._workbench_confirmation_required and (
                    self._clarification_form is None
                    or self._clarification_form.questions[0].id != "workbench_creation_mode"
                ):
                    self._fail(request, WORKBENCH_CONFIRMATION_REQUIRED)

修复方案:

            if not self.text_protocol and self.clarification is not None:
                if not calls and self.clarification.has_workbench_form_text(content):
                    self._workbench_confirmation_required = True
                if self._workbench_confirmation_required and (
                    self._clarification_form is None
                    or self._clarification_form.questions[0].id != "workbench_creation_mode"
                ):
                    self._fail(request, WORKBENCH_CONFIRMATION_REQUIRED)

将 Workbench 表单检测整体放入 self.clarification is not None 的保护内,与同文件中 verification_pending / full_generation_pending 的 is not None 防御风格保持一致。clarification 为 None 的运行本来就不存在 Workbench 确认表单,跳过检测不影响逻辑;native 模式下模型的纯文本最终回复照常返回,不再因 AttributeError 使整轮运行失败。


🤖 generated by github-code-review

- If a requested text change could make other Prompt fields inconsistent and the user has not already said which related fields to synchronize, first call `{{ wrapper_name }}` with a `requirement_clarification` multiple-choice question listing only the potentially affected fields. After the submitted action, save the originally requested fields plus only the fields the user confirmed, together in one call. If the user confirms none, update only the original fields. Never cascade automatically.
- If the requested replacement is unclear or missing, use `requirement_clarification` to ask only for the missing content. Do not restart requirement discovery for facts that remain authoritative in the verified draft.
- Every task must still follow the Prompt field allowlist, real bound resources, declared inputs, trusted tool results, and transport escaping rules.
- Every task must still follow the Prompt field allowlist, real bound resources, declared inputs, trusted tool results,.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ 删除 transport escaping 短语后句尾残留 ",." 残缺标点

本行由 "Every task must still follow the Prompt field allowlist, real bound resources, declared inputs, trusted tool results, and transport escaping rules." 修改为 "Every task must still follow the Prompt field allowlist, real bound resources, declared inputs, trusted tool results,."。删除尾部短语 " and transport escaping rules" 时没有处理它前面的逗号,导致句尾变成 ",."(逗号与句号连写)。该句位于注入每次 NL2Agent 运行的业务系统提示词(### Understand the user's goal 段),残缺标点会降低模型对这条约束指令的解析质量。同一批删除 <final_answer> envelope 表述的机械编辑还在本文件留下两处双空格:"briefly confirm the actual change after success"(Target Agent Execution Policy 段)与 "return its Revision Summary or local result when there is no pending card action"(Atomic Action Contract 段);zh 版 meta/nl2agent.yaml 对应位置也有 "调用 {{ validate_completion_tool_name }} 。" 句号前的多余空格,建议一并清理。

上下文代码:

-  - Every task must still follow the Prompt field allowlist, real bound resources, declared inputs, trusted tool results, and transport escaping rules.
+  - Every task must still follow the Prompt field allowlist, real bound resources, declared inputs, trusted tool results,.

修复方案:

  - Every task must still follow the Prompt field allowlist, real bound resources, declared inputs, and trusted tool results.

在最后一个列表项 trusted tool results 前补回连词 and,并把句尾的 ",." 修成单个句号,恢复完整的英文并列句式。同时建议顺手修复同一文件中因删除 envelope 短语残留的两处双空格,以及 zh 版本 "{{ validate_completion_tool_name }} 。" 中句号前的多余空格,保持双语提示词文本整洁。


🤖 generated by github-code-review

from management.services.conversation.creation_mode import has_agent_creation_confirmation
from management.services.model.creator_snapshot import prepare_creator_model
from nexent.core.concurrency import run_blocking
from services.nl2agent_prompt_service import build_verified_bound_resources_context

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ 移除 creator_run._build_verified_bound_resources_context 后未同步既有 D3 用例的 monkeypatch,AOS-TRANSPORT-D3-001 将在准备阶段失败

本 PR 把 creator_run 的上下文构建函数从 management.services.agent.nl2agent._build_verified_bound_resources_context 换成了 services.nl2agent_prompt_service.build_verified_bound_resources_context,creator_run 模块不再拥有 _build_verified_bound_resources_context 属性。但既有的正式 D3 用例 test-e2e/cases/AOS-TRANSPORT-D3-001/test.py(不在本 PR 变更文件列表中)在 test_nl2agent_run_and_signed_draft_callback(AC-45 绑定)里仍执行 monkeypatch.setattr(creator_run, "_build_verified_bound_resources_context", verified);monkeypatch.setattr 默认 raising=True,属性不存在会直接抛 AttributeError,该用例在准备阶段即失败。即使改为 raising=False,生产路径也已改调新函数名,桩函数不再被调用,真实的 build_verified_bound_resources_context 会访问数据库,后续 assert info.agent_config.context_items[-1].content["text"] == "Verified editable draft" 等断言同样失败。项目规则要求保留并维护全部既有 D3 用例,重命名该公共桩点时必须同步更新该文件(PR 只更新了 test_shared_creator_runtime.py 等 UT 的 mock 目标,遗漏了这个 D3 用例)。

上下文代码:

 from management.services.agent.nl2agent import (
-    Nl2AgentDraftSaveError, _build_verified_bound_resources_context, _parse_nl2agent_card_action_agent_id,
+    Nl2AgentDraftSaveError, _parse_nl2agent_card_action_agent_id,
     _requires_policy_clarification,
 )

修复方案:

    async def verified(**scope):
        assert scope == {"agent_id": 7, "user_id": actor.user_id, "tenant_id": actor.tenant_id}
        return SimpleNamespace(content={"text": "Verified editable draft"})

    monkeypatch.setattr(creator_run, "build_verified_bound_resources_context", verified)

在 test-e2e/cases/AOS-TRANSPORT-D3-001/test.py 中把 monkeypatch 目标从旧的 _build_verified_bound_resources_context 改为 PR 引入的新名称 build_verified_bound_resources_context。prepare_nl2agent_snapshot 调用新函数时仍只传 agent_id/user_id/tenant_id 三个关键字参数,与桩函数断言一致;若该用例后续覆盖 _apply_card_action 路径,桩函数需额外兼容 prompt_scope 关键字(默认 None)。


🤖 generated by github-code-review

- 用户明确要求开启或关闭“严格协议与重试”“严格输出协议与静默修复”“严格输出校验与协议修复重试”时,使用 `update_execution_policy`,只向 `{{ save_tool_name }}` 保存当前目标草稿的 `enable_protocol_repair_retry=True` 或 `False`。必须传布尔值,不能传字符串、数字或 null。
- 该字段属于被创建或编辑的 Agent,不控制 NL2Agent 创建助手自身,也不控制 Workbench 会话或模型服务请求重试;不得用 Prompt 文本代替字段保存。
- 只修改策略时,无需描述、资源或 Prompt 完整;先遵守空变量名初始化规则,再保存策略,收到成功结果后用唯一一对 `<final_answer>...</final_answer>` 简洁确认实际修改。不得启动完整生成、资源搜索、改写其他字段或声称已完成生成。
- 未明确请求修改时省略此字段,保留可信草稿当前值;缺省为关闭。用户只说“重试”而未明确协议修复时,使用 `requirement_clarification` 澄清具体含义,不得保存猜测值。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ zh 版系统提示词整条删除了「只修改策略」规则,与 en 版保留的对应条目不对齐

本 PR 的目标是移除业务提示词中的 <final_answer> 信封与 Core 传输细节。en 版在 Target Agent Execution Policy 中保留了 policy-only 任务条目,仅去掉信封表述("A policy-only task needs no complete description... Apply the empty-name initialization rule first... Do not start full generation, search resources, rewrite unrelated fields, or claim generation completion.")。但 zh 版在「目标 Agent 执行策略」中把「只修改策略时,无需描述、资源或 Prompt 完整;先遵守空变量名初始化规则,再保存策略……不得启动完整生成、资源搜索、改写其他字段或声称已完成生成」整条删除(该 hunk 从 12 行减为 11 行)且没有任何替代内容。结果是中文模型失去「策略任务要先遵守空变量名初始化规则、不得因此启动完整生成或搜索资源」的关键约束,中英文语义不对齐——PR 描述本身也声明中英文各自保留角色、业务流程和完成条件。现有单测只断言 zh 侧的其他段落,不会捕获这条丢失。

上下文代码:

   - 该字段属于被创建或编辑的 Agent,不控制 NL2Agent 创建助手自身,也不控制 Workbench 会话或模型服务请求重试;不得用 Prompt 文本代替字段保存。
-  - 只修改策略时,无需描述、资源或 Prompt 完整;先遵守空变量名初始化规则,再保存策略,收到成功结果后用唯一一对 `<final_answer>...</final_answer>` 简洁确认实际修改。不得启动完整生成、资源搜索、改写其他字段或声称已完成生成。
   - 未明确请求修改时省略此字段,保留可信草稿当前值;缺省为关闭。用户只说“重试”而未明确协议修复时,使用 `requirement_clarification` 澄清具体含义,不得保存猜测值。

修复方案:

  - 该字段属于被创建或编辑的 Agent,不控制 NL2Agent 创建助手自身,也不控制 Workbench 会话或模型服务请求重试;不得用 Prompt 文本代替字段保存。
  - 只修改策略时,无需描述、资源或 Prompt 完整;先遵守空变量名初始化规则,再保存策略,收到成功结果后简洁确认实际修改。不得启动完整生成、资源搜索、改写其他字段或声称已完成生成。
  - 未明确请求修改时省略此字段,保留可信草稿当前值;缺省为关闭。

与 en 版对齐:只移除 <final_answer>...</final_answer> 信封表述,保留条目本身(策略任务无需完整描述/资源/Prompt、先遵守空变量名初始化规则、不得启动完整生成或改写其他字段),把被删除的条目重新插回「该字段属于被创建或编辑的 Agent……」与「未明确请求修改时省略此字段……」之间。修改后需按仓库规则同步刷新 test/assets/sdk_prompt_migration_hashes.json 中 zh/meta/nl2agent.yaml 的哈希。


🤖 generated by github-code-review

- If a requested text change could make other Prompt fields inconsistent and the user has not already said which related fields to synchronize, first call `{{ wrapper_name }}` with a `requirement_clarification` multiple-choice question listing only the potentially affected fields. After the submitted action, save the originally requested fields plus only the fields the user confirmed, together in one call. If the user confirms none, update only the original fields. Never cascade automatically.
- If the requested replacement is unclear or missing, use `requirement_clarification` to ask only for the missing content. Do not restart requirement discovery for facts that remain authoritative in the verified draft.
- Every task must still follow the Prompt field allowlist, real bound resources, declared inputs, trusted tool results, and transport escaping rules.
- Every task must still follow the Prompt field allowlist, real bound resources, declared inputs, trusted tool results,.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ en 版系统提示词残留 ",." 与双空格等编辑痕迹,污染模型可见文本

第 30 行把句尾的 "and transport escaping rules" 移除后残留了逗号加句号:"Every task must still follow the Prompt field allowlist, real bound resources, declared inputs, trusted tool results,.";第 35 行去掉 <final_answer>...</final_answer> 表述后残留双空格:"briefly confirm the actual change after success."。这些内容是直接注入给模型的系统提示词,破损标点与多余空格属于本次编辑的残留物,降低指令清晰度,且与 zh 版对应句式("……可信工具结果。"、"收到成功结果后……")不一致。

上下文代码:

-  - Every task must still follow the Prompt field allowlist, real bound resources, declared inputs, trusted tool results, and transport escaping rules.
+  - Every task must still follow the Prompt field allowlist, real bound resources, declared inputs, trusted tool results,.

修复方案:

  - Every task must still follow the Prompt field allowlist, real bound resources, declared inputs, trusted tool results.

  # 并修正第 35 行的双空格:
  - A policy-only task needs no complete description, resources, or Prompts. Apply the empty-name initialization rule first, then save the policy and briefly confirm the actual change after success. Do not start full generation, search resources, rewrite unrelated fields, or claim generation completion.

把第 30 行句尾的 ",." 修为单个句号,与 zh 版「可信工具结果。」对齐;去掉第 35 行 "the actual change after success" 中的多余空格。修改后需按仓库规则同步刷新 test/assets/sdk_prompt_migration_hashes.json 中 en/meta/nl2agent.yaml 的哈希。


🤖 generated by github-code-review

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants