Skip to content

feat(core): add response-side structured output validation with error-feedback retry - #2858

Merged
jujn merged 26 commits into
agentscope-ai:mainfrom
helloworldtang:feat/structured-output-validation-retry
Oct 14, 2026
Merged

jujn merged 26 commits into
agentscope-ai:mainfrom
helloworldtang:feat/structured-output-validation-retry

Conversation

@helloworldtang

@helloworldtang helloworldtang commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Native structured output previously sent the JSON Schema to the provider with response_format, but the actual model response was parsed and exposed without a client-side schema check. This PR adds the missing response-side validation while keeping the implementation aligned with the existing structured-output routing and fallback behavior.

Behavior

Native structured-output validation is enabled by default.

For the native path:

  1. The model receives the JSON Schema through response_format.
  2. The returned text is parsed as JSON.
  3. The parsed JsonNode is validated against the requested schema.
  4. If validation succeeds, the same parsed payload is stored in Msg.metadata[_structured_output].
  5. If the output is empty, invalid JSON, or schema-invalid, the rejected native response is removed from the conversation context and the agent falls back to the existing generate_response tool path.

The fallback path remains unchanged: tool arguments continue to be validated before the structured-output tool completes.

Opt-out

Providers that already guarantee schema conformance can disable the client-side schema check:

ReActAgent agent = ReActAgent.builder()
        .name("assistant")
        .model(model)
        .validateStructuredOutput(false)
        .build();

When disabled:

  • Native output must still be valid JSON so it can be attached as structured data.
  • Schema conformance is trusted to the provider.
  • Schema-invalid output does not trigger the synthetic-tool fallback solely because of schema validation.

The configuration is copied by Builder.copy() and therefore survives builder reuse.

@CLAassistant

CLAassistant commented Aug 27, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
2 out of 3 committers have signed the CLA.

✅ helloworldtang
✅ jujn
❌ zwork


zwork seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@codecov

codecov Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 69.56522% with 14 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...in/java/io/agentscope/core/tool/ToolValidator.java 46.66% 4 Missing and 4 partials ⚠️
...e/src/main/java/io/agentscope/core/ReActAgent.java 80.64% 4 Missing and 2 partials ⚠️

📢 Thoughts on this report? Let us know!

* @throws StructuredOutputValidationException when all attempts fail
*/
public static JsonNode generateWithRetry(
Function<List<StructuredOutputValidator.ValidationError>, String> generate,

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.

[P1] 新增的校验重试入口没有接入现有结构化输出调用链。
当前 ReActAgent.call(..., Class/JsonNode) 的 native 路径仍直接调用 wrapNativeStructuredResult(),只解析 JSON,没有调用这里的 validator/generator。实测 required-number schema 收到 {"answer":"wrong"} 时,标准 agent.call() 仍然成功。因此这个 PR 目前没有为现有 AgentScope 结构化输出 API 增加 response-side validation 或 retry。建议将校验和纠错重试集成到 ReActAgent 的 Reactor 调用链,并保留 usage、thinking、hooks、session、取消及状态回滚语义。

text = text.substring(0, closingFence).trim();
}
}
int start = text.indexOf('{');

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.

P1] 解析失败时不能把原始文本合成为业务对象。
当前找不到 JSON 或 JSON 解析失败时会返回 {"result": raw}。如果目标 schema 合法要求 result:string,纯文本或畸形 JSON 就会直接校验成功。实测输入 this is not JSON 会成功返回 {"result":"this is not JSON"},绕过重试和“模型实际输出必须是 JSON”的保证。解析失败应生成独立的 parse error 并进入 retry/exception,不能构造可能符合用户 schema 的字段。另外,第一个 {...} 解析失败后也不应直接放弃后面可能存在的合法 JSON。

* @param schema the schema to validate against
* @return the list of validation errors; empty when the output conforms
*/
public static List<ValidationError> validate(JsonNode output, JsonSchema schema) {

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.

[P2] null output 或缺失 schema 当前会 fail-open。
这里返回空列表,但该 API 的契约将空列表解释为“output conforms”。实测 schema.validate(null) 返回 [];JsonSchema.builder().name("x").build() 传给 generator 后,任意输出都会在第一次尝试成功。缺失 schema 应抛出配置错误;null output 应返回明确的 validation error 或抛出解析异常,不能与校验通过使用相同结果。

*/
public final class StructuredOutputValidator {

private static final SchemaRegistry REGISTRY =

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.

[P2] 当前 Networknt 配置不会执行 format assertions。
使用当前 2.0.0 依赖实测,strict schema 声明 format: email 时,{"email":"not an email"} 仍返回零错误。如果本地校验承诺 strict/schema-conforming,建议通过 SchemaRegistryConfig 启用 formatAssertionsEnabled(true),并补充 email、date-time 等回归测试;如果有意只把 format 作为 annotation,则需要在 API 文档中明确说明限制。

@xzxiaoshan

xzxiaoshan commented Aug 27, 2026 •

Copy link
Copy Markdown
Collaborator

关于这个 PR 在 native 路径上补响应侧校验的必要性, 持保留意见,想先对齐一下设计前提:

能力契约已经建立了信任边界。 Model.supportsNativeStructuredOutput() 返回 true,意味着 provider 侧通过 response_format / strict mode 在生成阶段(constrained decoding)就强制输出符合 schema。schema 在解码时就被约束,框架侧再做一次 JSON Schema 校验是重复劳动——只增加延迟和成本,几乎拦截不到任何真实错误。我们不应该在框架层默认"不信任 provider 的能力声明"。

fallback 路径已经有完整的"校验 + 错误反馈重试"闭环。 模型不支持原生结构化输出时,ReActAgent 注入 generate_response 合成工具,参数 schema 内嵌用户 schema;工具执行前会做运行时校验,失败时把带字段路径的可操作错误信息(每行 path: message)作为 tool result 回灌给模型自我修正(受 maxIters 约束)。这正是本 PR 所描述的 error-feedback retry 模式,已存在于主调用链中,所以"response side 完全没有校验"的空白比 PR 描述的要小。

如果某个 provider 声称支持但实际不严格遵守, 那是该 Model 实现的 supportsNativeStructuredOutput() 声明不诚实,正确修复是把它的能力开关关掉、让它降级走 fallback 路径(那里已有校验),而不是给所有 native 调用方加一层防御性校验。

基于 1,我认为把校验接入 native 主路径没有必要。 对独立工具类 StructuredOutputGenerator,从框架角度我也持保留态度:它本质上只是一个"生成 → 校验 → 把错误拼回 prompt 重试"的薄循环,用户基于 networknt 几十行即可自行实现;框架在 agent 层已经提供了完整的结构化输出能力(两条路径均含校验保障)。为一个自拼 prompt 的小众场景在 core 中增加 API 面积,收益不足、维护成本却在。除非能给出框架内的具体集成点或真实用户需求,否则建议不引入。


另外我在核对代码时发现一个与本 PR 无关的性能问题:ToolValidator.validateInput 每次工具调用都会把 schema 重新序列化并完整重新编译(networknt getSchema(String) 不走其内部缓存),ReAct 循环中同一工具会被反复调用,存在重复编译开销。建议单独开 issue 跟进。

@helloworldtang

Copy link
Copy Markdown
Contributor Author

感谢两位的详细评审,逐条回应如下。对应实现已完成并推送(29 个 structured-output 测试 + agentscope-core 全量 2328 通过,spotless 干净)。

@guslegend0510:

  • [P1] 校验重试未接入现有调用链 — 已通过 opt-in middleware 接入:StructuredOutputValidationMiddleware 挂在 onModelCall(native 路径的 responseFormat 会流入 GenerateOptions,而模型调用统一经过 middleware 链)。它工作在事件流层面而非修改 ReActAgent 内部,因此 usage、thinking、hooks、session、取消与状态回滚语义原样保留;纠错消息只追加在 model call 输入里,不会污染 agent 上下文。挂上该 middleware 后,agent.call(..., Class/JsonNode) 的 native 路径即具备校验 + 错误反馈重试。
  • [P1] 解析失败合成业务对象 — 已改 fail-closed:提取不到 JSON 抛 StructuredOutputParseException 进入重试/异常,不再构造 {"result": raw}。你提到的子项也已处理:首个平衡 {...} 解析失败后会继续扫描后续候选,而不是直接放弃。
  • [P2] null output / 缺失 schema fail-open — schema 缺失现在抛出配置错误;null output 返回显式的 output is null 校验错误,不再与"校验通过"同形。
  • [P2] format assertions — 已通过 SchemaRegistryConfig 启用 formatAssertionsEnabled(true),并补充了 email 回归测试。

@xzxiaoshan:

你的设计前提我完全认同,这正是本次改法调整的依据:

  1. 框架不应默认不信任 provider 的能力声明 — 同意。所以校验没有接进 native 主路径,而是做成 opt-in middleware:不挂载就零开销、零行为变化,信任边界保持不变。
  2. fallback 路径已有完整闭环 — 同意,也不重复造。middleware 只作用于 native 路径,服务两类场景:(a) 审计/合规要求框架侧对"模型实际返回了什么"留存验证证据;(b) 个别 provider 的 strict mode 并非完整 constrained decoding(不支持的 schema 关键字被丢弃后仍自由采样),此时框架侧校验是实际能拦住错误的唯一一层。
  3. 声明不诚实的 provider 应关能力开关降级 — 同意这是正解,middleware 与它互补而非替代:开关解决"该 provider 整体不可信",middleware 解决"可信 provider 的个别漏网"。
  4. "框架内的具体集成点" — 这条 middleware 就是:StructuredOutputValidationMiddleware 复用 StructuredOutputGenerator 的提取与反馈构造(后者退为内部引擎)。如果维护者认为 API 面积仍大,generateWithRetry 可以降为 package-private、只保留 middleware 入口,听你们的意见。
  5. ToolValidator.validateInput 每次重新编译 schema — 确认存在,与本 PR 无关,我可以单独开 issue 跟进;StructuredOutputValidator 里的 compiled-schema 缓存模式可直接参考。

@xzxiaoshan

xzxiaoshan commented Aug 27, 2026 •

Copy link
Copy Markdown
Collaborator

看一下框架中已有的 generate_response 原理,以及在后面版本合入的 #2697 增强处理。

且:这些类怎么会全部塞到 core 模块的 formatter 包中呢?从功能上来看是 middleware。

@guslegend0510

Copy link
Copy Markdown
Contributor

发现新的 P1:失败轮输出进入 middleware 校验前,已经被 ReasoningContext 累计并触发 hooks;后续仅回写 text,没有回滚 thinking/tool 状态。隔离集成测试可稳定复现:最终成功结果会混入失败轮 thinking,usage 也没有正确累计。

@helloworldtang

Copy link
Copy Markdown
Contributor Author

感谢评审,4 条意见已全部处理并 force-push(commit 0d4d57a):

  1. 校验接入实际调用链:新增 StructuredOutputValidationMiddleware(挂 onModelCall,与 TaskReminder/OtelTracing 同惯例),native 路径校验失败会带错误反馈自动重试;失败尝试绝不作为通过内容释放
  2. 解析失败 fail-closed:不再合成 {"result": raw},parse error 进入同一重试循环
  3. fail-open 改 fail-closed:schema 缺失直接抛错
  4. format assertions 已启用(email/date-time),附回归测试
    额外:新增 StructuredOutputRetryPolicy(maxAttempts/tokenBudget/失败监听,默认值可覆盖)+ FailedAttempt 事件留痕;流式调用不校验(与参考实现同款边界)。全量 2328 测试通过。

@helloworldtang

Copy link
Copy Markdown
Contributor Author

感谢指出,这个 P1 成立:失败轮的 thinking/tool 状态已写入 ReasoningContext 并触发过 hooks,middleware 重试只替换了 text,状态污染会导致最终结果混入失败轮 thinking、usage 累计也不对。我正在处理——方案方向是让重试路径具备状态回滚能力(回滚 ReasoningContext 到校验前快照,或把校验循环下沉到 reason 状态提交点之前),确认方案后会更新 PR。隔离复现如果方便贴一下,我可以对照验证修复。

@guslegend0510

Copy link
Copy Markdown
Contributor

可以,我这边有隔离复现,基于当前 head 69de1a6。
用例通过真实 ReActAgent.call(..., Class) 和 StructuredOutputValidationMiddleware 连续返回两轮:

  • 第一次:schema 不合法,thinking=failed-thinking,usage=10/20
  • 第二次:schema 合法,thinking=valid-thinking,usage=30/40
    当前最终结果为:
  • text:{"answer":7}
  • thinking:failed-thinkingvalid-thinking
  • usage:30/40
    说明失败轮 thinking 已污染最终结果,失败轮 usage 也被丢失。
    运行命令:
    mvn -pl agentscope-core
    -Dtest=StructuredOutputRetryContextLeakReviewTest test
    当前测试 BUILD SUCCESS 是因为它故意断言现有错误行为,用于稳定复现;修复后预期 thinking 只包含 valid-thinking,usage 应按重试语义正确累计。
    StructuredOutputRetryContextLeakReviewTest.java

@helloworldtang

Copy link
Copy Markdown
Contributor Author

感谢提供隔离复现,已按该场景修复并推送(commit faa0559)。

根因:middleware 工作在 model call 层,收到流时 ReasoningContext 已完成 thinking/tool 状态累计并触发过 reasoning hooks,架构上无法回滚——所以把校验循环下沉到了 ReActAgent reasoning 层(reasoningWithOutputValidation),middleware 方案移除。

修复行为:

  • 失败轮的 ReasoningContext 不提交即丢弃:thinking/tool 状态不进入最终消息
  • 失败轮 usage 向前携带并聚合进最终消息(sumUsage,input/output/cached/time 均累计):重试消耗的 token 仍被正确计入
  • 纠错消息追加进会话后以全新 context 重启 reasoning;耗尽 maxAttempts 抛 StructuredOutputValidationException
  • 每次拒绝仍发 structured_output.failed_attempt 事件

已按你的复现场景新增回归测试 StructuredOutputRetryContextLeakTest(两轮输出 failed-thinking/10-20 → valid-thinking/30-40):断言最终 thinking 只含 valid-thinking、usage 聚合为 40/60。全量 2321 测试通过,CI 全绿。

@guslegend0510 guslegend0510 left a comment

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.

LGTM

@helloworldtang

Copy link
Copy Markdown
Contributor Author

感谢大佬,看PR已提交 目前处于 LGTM 状态——如果还有需要我调整或补充的地方,随时告诉我。

@helloworldtang

Copy link
Copy Markdown
Contributor Author

@xzxiaoshan 感谢你详细的设计前提讨论,几点逐条回应(也对 LGTM 之前悬而未决的讨论做一个收口):

1. 关于 native 路径校验的必要性——"不信任 provider"与 opt-in 语义

当前实现是严格 opt-in 的:只有业务显式调用 agent.call(msg, Class) / (msg, JsonNode)(即显式要求强类型结果)时,响应侧校验 + 重试才激活;不携带目标类型的自由文本调用完全不受影响,supportsNativeStructuredOutput() 的信任边界本身没有被改变。更准确的表述是"强保证需要显式请求",而非框架默认不信任 provider。

成本侧:本地 JSON Schema 校验是微秒级 CPU 操作,相对模型调用的秒级延迟与 Token 成本可忽略;重试成本只在真实失败时发生,且受 StructuredOutputRetryPolicy(maxAttempts/tokenBudget)约束,业务可以配置到接近关闭。可靠性侧:provider 的 strict mode 声明与实际实现存在差距(OpenAI 官方文档自认 strict mode 有 schema 特性局限;GLM/MiniMax 等兼容层的 response_format 质量参差——本仓库近期 PR 恰好也在修这类 provider 差异)。业界对照:Spring AI、Instructor 等均在原生结构化输出路径上保留了响应侧校验,不依赖 provider 单点保证。

2. 与 #2697 的关系——互补而非重复

认同 #2697 的 L0-L4 分层视角:它加固的是 fallback 路径(L2 模式提示、L3 强制调用 generate_response、L4 重试上限),本 PR 补的是 native 路径的响应侧校验 + 错误反馈重试(native 路径此前完全没有等价能力)。两条路径合起来,结构化输出的可靠性矩阵才是完整的:同一 schema,无论 provider 能力如何,都有有界且可观测的保障。

错误反馈格式也已对齐:native 重试提示的每行 path: message 与 fallback ToolValidator 的回灌格式一致,模型在两条路径下收到的是同构的纠错信号。一处语义差异需要说明:#2697 L4 是"超限优雅降级(正常结束)",本 PR 超限抛 StructuredOutputValidationException——fail-closed 是按评审口径落地的(解析失败合成 {"result": raw} 曾被认定为绕过校验),如果你认为 native 路径需要可选的降级策略,我们可以讨论在 policy 层显式建模。

3. 关于 formatter 包的位置

重构后校验循环已内建到 ReActAgent 的 reasoning 层(middleware 方案因无法回滚轮次状态被移除),formatter 包现在只保留输出格式契约类:Validator(schema 校验)/ Generator(解析与纠错提示)/ RetryPolicy(伴随配置)。这个分组沿"输出格式契约"职责划分;如果你认为应该独立成包(如 structured),我可以在后续 PR 里单独调整,避免本 PR 的 diff 面继续扩大。

@helloworldtang

Copy link
Copy Markdown
Contributor Author

合并最新 main 后重读了一遍代码,补了一轮收尾(commit 34ae45bb),说明如下:

  1. 耗尽异常与既有降级的交互:doStructuredCall 里原有的 native→fallback 降级(fix(dashscope): enhance support for native structured output in DashScope models #1935 引入的 catch-all onErrorResume)会把耗尽重试抛出的 StructuredOutputValidationException 也接住、降级到合成工具路径——不配合调 generate_response 的模型会以纯文本正常结束,fail-closed 语义与 tokenBudget 停止实际未生效。现在该异常显式穿透,技术性失败仍走原有降级。
  2. 接好迁移时丢了执行点的三个旋钮:tokenBudget(累计用量达到预算即停止重试)、onFailedAttempt、emitAttemptEvents 现已生效;终态异常同时携带历次 FailedAttempt(该字段此前一直未被填充)。
  3. javadoc 校正:失败轮消息实际会保留在会话中(供模型看到错在哪),不泄漏的是返回的最终消息,耗尽时整体回滚;另移除两处对已删除 middleware 的残留引用。

新增 StructuredOutputRetryPolicyEnforcementTest(耗尽+会话回滚 / tokenBudget 提前判停 / PARSE_ERROR 留痕)。agentscope-core 全量 2338 测试通过,spotless 干净。

@helloworldtang

Copy link
Copy Markdown
Contributor Author

@jujn @Buktal 二位好,这个 PR 想请维护者帮忙看一下:guslegend0510 已 review 通过(含三轮修改),评审中提出的全部问题已处理完毕;CI 全绿(双平台 build + codecov + license),昨天又补了一轮自查收尾(见上一条评论)。与 @xzxiaoshan 的设计讨论已在 8-31 逐条回应,目前等回复中。如果还有需要调整的地方,随时告诉我,谢谢!

@Buktal Buktal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

  1. 考虑把 attempt 那几个计数器挂到 call 级状态(别把整个重试环上移去重跑 doCallInner,工具副作用会被重放):防止带工具调用时每进新 iteration 就重置,maxAttempts 和 tokenBudget 就形同虚设了。
  2. 考虑把 structuredOutputPolicy 挪到 ReActAgent 的 builder 里:模型层 DTO 里塞个带回调的 agent 策略,模型适配器那边也用不上。
  3. 建议把两套解析/重试收敛成一套,agent 复用 extractJsonObject 或者把 generateWithRetry 删了只留 retryPrompt:不然两套语义进了公共 API,以后再统就只能走废弃流程了。
  4. 建议给 correction 打个标,成功后像 fallback 那样清理下会话(再补个测试):不然纠错残迹一直留着,后面每轮调用都得多花 token。

一些小问题:

  1. Generator 里那几处中文评审注释(P1-2 什么的)顺手改成英文吧。
  2. 校验那块每次 new ObjectMapper 有点浪费,复用个静态的就行。
  3. Validator 里那个手写 CACHE 跟 registry 自带的重复了、还无界,删了吧。
  4. 校验和最终解析用的文本拼接方式不一样,统一走 getTextContent、记得加空值防护。
  5. FailedAttempt 的 validationErrors 传 null 也能过,构造里归一化一下更稳。
  6. onFailedAttempt 回调没保护,用户代码一抛异常整个 call 就被带偏了,包个 try/catch 吧。
  7. 异常类的字段声明跑到构造器后面去了,挪到前面跟大家保持一致。
  8. 几处全限定名(JsonSchema.validate 签名那些)改成 import 吧。
  9. listenerReceivesFailures 那个测试没测到被测类,删掉或者改实吧。

@helloworldtang

Copy link
Copy Markdown
Contributor Author

感谢详细的 review,13 条已全部处理(commits 51fceccf + cd8b4134,core 全量 2341 测试通过):

1. attempt 计数器挂 call 级状态 — 计数器、累计 usage、failedAttempts 已迁到 CallExecution(与 soTool 同 rank),跨 iteration 不再重置。另补了一个消息 id 去重守卫:嵌套 iteration 边界上同一最终消息会上浮穿过多个 wrapper,只挂 scope 不去重会双倍计数,现在既不重置也不双计。补了回归测试:两次校验失败之间穿插一次工具调用,预算仍在 maxAttempts 处精确耗尽。

2. structuredOutputPolicy 挪到 ReActAgent.Builder — 认同层次错位,GenerateOptions 里的字段/accessor/builder/merge 已全部移除。

3. 解析收敛为一套 — 校验循环改用 StructuredOutputGenerator.extractJsonObject(顺带覆盖 markdown fence / prose 包裹的场景),generateWithRetry 已删除。

4. correction 打标 + 成功后清理 — 新增 _structured_output_retry_residue metadata key,失败轮与 correction 都打标;成功后 removeRetryResidue 清理会话(对齐 fallback 的 compressStructuredOutputContext)。补了回归测试:重试轮模型仍能看到失败输出和纠错消息(自纠需要),成功后的后续调用输入中零残留。

小问题 9 条均已照办:注释英文化、复用静态 MAPPER(随统一入口自然消亡)、手写 CACHE 删除(registry 2.0.0 自带缓存)、统一 getTextContent + 空值防护、FailedAttempt 构造归一化 null、listener 加了防御性 try/catch(chunk callback 同款)、异常字段声明前移、全限定名改 import、那个只测 lambda 的测试已替换为 FailedAttempt 归一化测试。

@Buktal Buktal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

  1. StructuredOutputGenerator.java:74-129 的 extractJsonObject 的实现有点...

看看以下代码能否符合你的要求
`public static JsonNode parseJsonOutput(String raw) {
String text = raw == null ? "" : raw.trim();
String candidate = stripCodeFence(text);
try {
return MAPPER.readTree(candidate);
} catch (JsonProcessingException e) {
throw new StructuredOutputParseException(
"output is not valid JSON: " + e.getOriginalMessage());
}
}

private static String stripCodeFence(String text) {
if (!text.startsWith("")) { return text; } int firstBreak = text.indexOf('\n'); if (firstBreak < 0) { return text; // malformed fence — let readTree report it } String body = text.substring(firstBreak + 1); int closing = body.lastIndexOf("");
return (closing >= 0 ? body.substring(0, closing) : body).trim();
}`

  1. ReActAgent.java:2402 / 1404-1414
    校验能过但最终 wrap 挂掉体验很糟,建议复用校验阶段解析好的 payload,保持单 source of truth

  2. StructuredOutputRetryPolicy.java:34 / ReActAgent.java:5175
    顺手更新为 ReActAgent.Builder 的实际 API 入口就好

  3. ReActAgent.java:2560-2566 / 1424
    跟 wrapNativeStructuredResult 看齐补上 .usage(...) 拷贝,能确保用量记账完整

  4. StructuredOutputGenerator.java:74 / 44
    生成逻辑移走后只剩 extract 和 prompt helper,可以考虑改叫 StructuredOutputUtils 或 StructuredOutputExtractor 更贴切

@helloworldtang
helloworldtang force-pushed the feat/structured-output-validation-retry branch from 3d8e11d to e27618b Compare September 8, 2026 03:45
@helloworldtang

Copy link
Copy Markdown
Contributor Author

Thanks @Buktal — all five points are addressed in 3150d68, plus one hardening that fell out of writing the acceptance tests (baca0e0):

1. extractJsonObject simplification — adopted your proposed shape: stripCodeFence + readTree, keeping only a two-line leading-prose retry from the first {; trailing prose is tolerated by Jackson's first-value read. The multi-candidate brace-scanning state machine is gone.

One behavioral note worth flagging: a malformed leading candidate followed by a valid JSON object is now rejected (fail-closed) rather than scanned over — e.g. noise { oops } tail {"answer":5} no longer extracts {"answer":5}. The unit test was updated accordingly (toleratesTrailingProse replaces extractsJsonAfterMalformedCandidate). Also, readTree alone would admit JSON arrays/scalars; those still cannot pass validation since the class schema is root-type object, so the fail-closed guarantee is unchanged.

2. Payload reuse (single source of truth) — the payload parsed during validation is stored on the call scope (soValidatedPayload) and consumed by wrapNativeStructuredResult; the raw-text re-parse remains only as a fallback for when validation did not run. Prose-wrapped output that passes validation now keeps its structured metadata — anchored by testProseWrappedOutputYieldsStructuredData, which fails on the previous re-parse behavior.

3. Javadoc entry point — StructuredOutputRetryPolicy now references ReActAgent.Builder.structuredOutputPolicy(...).

4. Residue re-tagging — markRetryResidue now copies usage (and generateReason, which is metadata-backed and travels with the copied metadata map).

5. Rename — StructuredOutputGenerator → StructuredOutputUtils; only extraction and prompt helpers remain, and no references to the old name exist repo-wide.

Follow-up hardening (baca0e0): while writing an acceptance test for (2) we noticed the nested-iteration dedupe guard recorded the message id before validation ran, so a message reusing the id of a failed attempt would skip re-validation entirely and return unvalidated output. The guard id is now recorded only after validation succeeds. Anchored by testSameIdMessageRevalidatedAfterFailedAttempt, which fails on the previous behavior (the call ended after 2 model calls with a schema-violating result returned unvalidated).

The branch now includes the latest main; the structured-output suite is green (24 tests across 3 classes).

@Buktal Buktal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@helloworldtang

Copy link
Copy Markdown
Contributor Author

@zouyx @chickenlj @jujn 说明一下:最新一次 Update branch 后,CI 在 AguiPermissionResumeTest(agentscope-harness 模块)上失败,经排查与本 PR 无关:

  • 本 PR 改动全部位于 agentscope-core(structured output 校验),未触及 harness 模块;
  • 该测试由 fix(agui): preserve tool results after permission resume #3100 引入,报错 Thread already has an active run ... AGUI_INTERRUPT_CONTRACT_ERROR,属于 run 合同的并发时序问题;
  • 本地基于同一 commit 复跑 3 次全部通过,无法复现;
  • main 分支近期 CI 也有多次同类失败(如 9-09 d20ebbe0、9-02 两次,均在 harness 模块)。

疑似时序敏感的 flaky test,麻烦有权限的同学 rerun 一下即可;需要我们协助排查随时说。

…hrow, typed kind

Round-4 review follow-ups on the failure-domain routing:

- The exhaustion rethrow was effectively unreachable: the guard required
  soFailedAttempts.size() == 1, which the default 3-attempt budget can
  never satisfy, so a persistent internal fault still ended as a
  model-blaming StructuredOutputValidationException. The guard now
  checks that ALL attempts are kind == UNKNOWN_FAILURE and rethrows the
  last raw cause.
- The bare rethrow was picked up by the fallback router's
  degrade-on-any-other-error branch, silently costing a synthetic-tool
  round trip (and able to mask the fault). It now rethrows the typed
  StructuredOutputUnknownFailureException (original cause preserved),
  which the router short-circuits — the third failure domain now has its
  own exit type, symmetric with Validation/Configuration.
- FailedAttempt.Kind gains UNKNOWN_FAILURE: platform faults no longer
  report as PARSE_ERROR to onFailedAttempt listeners; the kind drives
  the control flow instead of comparing an English prose sentinel.
- The correction prompt for unknown-domain failures is now produced by a
  dedicated unknownFailurePrompt(); retryPrompt no longer special-cases
  the marker string.
- Tests: the static-mock seam now uses CALLS_REAL_METHODS as the default
  answer with only extractJsonObject overridden (first-call or
  always-failing), so unstubbed methods run for real; the persistent
  test asserts the typed wrapper, the original cause and exactly
  default-budget model calls with no fallback round trip.

Anchored by testPersistentUnknownFailureRethrowsOriginalException (fails
on the previous behaviour with StructuredOutputValidationException).
…se-chain short-circuit, release notes

Round-5 review follow-ups:

- Move the orphaned retryPrompt javadoc back onto retryPrompt (it had
  drifted onto the new no-arg unknownFailurePrompt, attaching an
  @PARAM errors tag to a no-arg method).
- Guard against a null rawException on the all-unknown-domain path: walk
  the attempts for the last non-null rawException and fall back to a
  synthetic cause, so StructuredOutputUnknownFailureException and its
  log line always carry the original fault.
- Match the fallback short-circuit through the whole cause chain
  (configuration + unknown-domain failures): an intermediate operator
  wrap can no longer silently reopen the degrade path.
- Add the compatibility note to docs/v2/{en,zh} release notes under
  Unreleased, mirroring the format of agentscope-ai#2862.
Round-6 review follow-ups:

- isNonDegradableFailure now delegates to a new shared
  ExceptionUtils.containsCause(error, predicate) helper: the previous
  walk only broke a direct self-reference, so a two-node cause cycle
  (A.initCause(B); B.initCause(A)) would spin forever on the reactive
  path; containsInterruptedException now delegates to the same helper so
  both chain walks behave identically.
- The null-rawException fallback logs attempt count and per-attempt
  kinds before synthesizing the cause, making the null-raw case
  investigable instead of a dead end.
…ort style

Two non-blocking notes from the round-6 approval:

- The diagnostic fallback builds the per-attempt kind list with
  String.valueOf(a.kind()) so a null kind can never make the error
  reporter itself throw.
- Spell Collectors / Predicate via imports instead of fully-qualified
  names, matching the surrounding style.
The previous run failed in agentscope-extensions-rag-bailian while
resolving com.aliyun:tea version ranges ([1.1.14,2.0.0)) from Maven
Central metadata. The same range resolves locally against both Central
and the Aliyun mirror, and main's CI is green on the same tree, so this
is a transient resolution failure rather than a code or dependency
issue. No functional change.
@helloworldtang
helloworldtang force-pushed the feat/structured-output-validation-retry branch from 905cb14 to b85828d Compare September 27, 2026 05:51
@helloworldtang

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main (b85828de) — merge conflict resolved.

冲突性质:main 侧将 doStructuredCall 重构为 CallExecution scope 架构(per-call toolkit,scope.activeToolkit.getToolSchemas(activeGroups, scope.toolRequestConfig)),与本 PR 在 onErrorResume 中新增的 fail-closed 守卫(StructuredOutputValidationException 穿透 + isNonDegradableFailure cause 链短路)正交。解法:保留 main 的新结构,将守卫逻辑原样嵌入新的 onErrorResume——语义零变更。

验证:agentscope-core 全量 2514 测试通过(0 失败 / 9 跳过),spotless 干净。

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review after the rebase onto latest main (b85828de). I re-checked the conflict resolution in ReActAgent.java — the only non-docs file whose content changed since my previous approval — and the rebase came out clean: the response-side validation loop, the per-call CallExecution retry bookkeeping (soValidationAttempts / soValidatedFinalMsgId / soValidatedPayload / soCarriedUsage / soFailedAttempts), the reasoningWithOutputValidation wiring in both executeIteration and the gotoReasoning continuation, and the fail-closed onErrorResume guards are all intact and now correctly scoped per call (which also removes the cross-call state-leak risk the earlier versions had).

CI is green, CLA signed, mergeable. Two questions on the retry-residue lifecycle (cleanup on the empty-completion path, and the size-based context rollback vs concurrent same-slot calls) plus three non-blocking notes — see inline comments. None of them block the PR; answer inline or handle in a follow-up.


Automated review by github-manager-bot

// A conforming output was produced: drop the retry
// scaffolding before persisting, mirroring the
// fallback path's context compression.
removeRetryResidue(scope.state);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Warning] removeRetryResidue(scope.state) runs only on the success branch. If doCallInner(...) completes empty, the switchIfEmpty path right below still calls saveStateToSession(scope) — so the retry scaffolding (failed-attempt messages + the synthetic structured_output_correction turn, both tagged STRUCTURED_OUTPUT_RETRY_RESIDUE) gets persisted and the next call keeps paying tokens for it. Either apply the same cleanup in the empty path, or note here why keeping residue there is intentional.

* caller's original turns; only the retry scaffolding is dropped, so subsequent
* calls do not keep paying tokens for it.
*/
private static void removeRetryResidue(AgentState agentState) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Warning] Residue lifecycle has a second edge: the doOnError rollback in doNativeStructuredCall truncates the context back to contextSizeBefore by size. That is correct only while a single call is the writer of state.contextMutable(). With the per-call CallExecution scope this is much safer than the old instance-level state, but if two calls can still interleave on the same session slot, one call's rollback would drop the other's freshly appended messages. Could you confirm the slot is serialised elsewhere (lock / per-slot queue), and if so add a one-line comment stating that invariant? If it is not serialised, an id-based removal (drop exactly the messages this call appended) would be more robust than the size-based truncation.

// Exhausted retries (maxAttempts / token
// budget) is a deliberate fail-closed decision;
// degrading to the synthetic tool path would
// spend more tokens and defeat the documented

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Info] The two fail-closed guards here (exhausted validation budget, and isNonDegradableFailure matched through the cause chain) are a deliberate behaviour change versus the previous "always degrade to the synthetic tool" behaviour. Nice that isNonDegradableFailure walks the cause chain cycle-safely — an operator wrapping the failure can no longer silently reopen the degrade path. This is the kind of change consumers map to user-facing errors, so the release-notes entry matters (see the docs comment).

Comment thread docs/v2/en/docs/others/release-notes.md Outdated

## Unreleased

### Compatibility

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Info] Good that the exception-domain change is recorded under Unreleased → Compatibility. Please make sure it is moved into the concrete version section when this lands (and mirrored in the zh page), so consumers reading the released changelog actually see that StructuredOutputValidationException may now be replaced by StructuredOutputConfigurationException / StructuredOutputUnknownFailureException.

metadata.put(MessageMetadataKeys.STRUCTURED_OUTPUT_RETRY_RESIDUE, true);
context.set(
i,
Msg.builderForRole(original.getRole())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Info] Minor maintainability nit, non-blocking: the residue tag is applied by rebuilding the message field-by-field (id/name/content/metadata/timestamp/usage/generateReason). Any field added to Msg later will be dropped here silently. A Msg.toBuilder() (or a copy helper next to builderForRole) would keep this resilient — fine as a follow-up.

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review of the delta since b85828de. The only new commit is the upstream main sync — no new feature work — and the merge is lossless in both directions:

  • git diff b85828de HEAD over ReActAgent.java, formatter/, MessageMetadataKeys.java and ExceptionUtils.java is empty: every PR-owned main-source file is byte-identical to the already-reviewed commit, so the conflict resolution never touched the feature.
  • All 59 files the merge brought in are upstream files (none PR-owned), all 20 PR-owned files survived, and there are no conflict markers anywhere in the repo.
  • The integration points are still intact at this head: the validator is still invoked on the response side (ReActAgent.java:2580), the retry budget is still enforced (:2688, with the token-budget branch at :2689), and the retry state (soValidationAttempts, soValidatedFinalMsgId, soValidatedPayload, soCarriedUsage, soFailedAttempts) is still per-call — it lives on CallExecution (:1802, one instantiation site at :723), not on the agent.
  • No upstream collision: upstream's ToolValidator change is purely additive and validateInput(String, Map) is unchanged, and supportsNativeStructuredOutputWithTools() is a default method on Model (:69), so the new Gemini/Anthropic server-tool models inherit it and the routing call at :1308 still compiles. All 9 MessageMetadataKeys literals remain unique.

Approving the merge resolution. The previously raised items on the feature itself are unchanged and still stand.


Automated review by github-manager-bot

@helloworldtang

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough re-review and for confirming the merge resolution is lossless.

All three approvals are in place and CI is green — is there a merge window we should wait for, or anything else needed from our side before this can be merged? Happy to help with any follow-up.

@oss-maintainer

Copy link
Copy Markdown
Collaborator

Status on 494777f4 (current head):

  • Review: APPROVED — my approval is pinned to this exact commit, so nothing has changed since the review and there is no delta to re-check
  • Checks: all green — build (ubuntu-latest), build (windows-latest), Check License, Check Module Sync, validate, codecov/patch, license/cla ✅
  • Merge state: mergeable=true / mergeable_state=clean, no conflicts
  • Blocker from the review side: none — merging is a maintainer action, so there is no further review step waiting on you

One thing still open that only a maintainer can settle: the PR carries the TBD label, which looks unassigned, and there is no merge window published on our side. So the answer to your question is: nothing to wait for from the contribution side, the remaining step is a maintainer picking it up (and confirming the label).

Nothing further is required from you unless the head moves — if you do sync main again, please ping @oss-maintainer and I'll re-review the delta only.


Automated response by github-manager-bot

zwork added 2 commits October 10, 2026 07:25
Conflict resolutions and integration fixes:

- ReActAgent.wrapNativeStructuredResult: kept the validated-payload
  reuse (single source of truth) with a re-parse fallback; main had the
  plain re-parse. Uses the already-imported JsonUtils simple name.
- release notes (en/zh): main moved to a 2.0.4 release-draft section;
  the structured-output compatibility note now lives inside 2.0.4 as
  "### Compatibility" / "### 兼容性" instead of a standalone Unreleased
  block.
- ReActAgent.Builder.copy(): main's build() now goes through
  copy().buildInstance(); the copy() field list predates this PR's
  structuredOutputPolicy field, so builder-configured retry policies
  were silently dropped. Copy the field (verified by
  StructuredOutputRetryPolicyEnforcementTest, which failed 4/5 on the
  un-fixed merge).
…t extraction seam

The main sync brought a subscribeOn(boundedElastic()) hop into the
reasoning pipeline, so the structured-output validation — and the
extractJsonObject call the unknown-domain tests inject into — now runs
on a Reactor worker thread. Mockito static mocks only intercept calls
on the thread that created them, so the four unknown-domain tests
silently lost their injection (the real extractor ran instead and the
tests failed on attempt counts).

- ReActAgent gains a private volatile structuredOutputExtractionOverride
  seam, consulted by the validation loop; null means the real extractor.
  Never assigned by production code.
- The four tests set it via reflection (same pattern as
  ReActAgentPerSessionStateTest) with try/finally cleanup, and drop the
  MockedStatic/Mockito imports.

Verified on the merged tree: agentscope-core 2625 tests green
(0 failures / 9 skipped); all four tests were red before the fix.
@helloworldtang

Copy link
Copy Markdown
Contributor Author

Synced with latest main (16153831) — pushed 0aec217c.

冲突解决与集成修复(三处,均已本地验证):

  1. 文本冲突(2 处):wrapNativeStructuredResult 保留校验期 payload 复用 + re-parse 回退(main 侧为原始 re-parse);release-notes 的兼容性说明并入 main 新起草的 2.0.4 章节(### Compatibility / ### 兼容性),不再使用独立的 Unreleased 段。

  2. 语义合并问题(main 侧重构与本 PR 咬合处):main 的 build() 现已改为 copy().buildInstance(),而 copy() 的字段清单早于本 PR 引入 structuredOutputPolicy 字段——builder 配置的 retry policy 被静默丢弃。已在 copy() 中补上该字段;StructuredOutputRetryPolicyEnforcementTest 在修复前 4/5 红(配置被忽略、退回默认预算),修复后全绿。

  3. 测试适配(main 新增线程跳变):main 在推理链引入了 subscribeOn(Schedulers.boundedElastic()),校验循环现在运行在 Reactor worker 线程上;Mockito 静态 mock 仅对创建它的线程生效,四个 unknown-domain 测试的注入因此失效(真实 extractor 反而被执行)。改为此前 review 中预告的 extractor seam 方案:ReActAgent 增加私有 volatile structuredOutputExtractionOverride(生产代码不赋值),测试经反射设置(模式对齐仓库既有的 ReActAgentPerSessionStateTest),替代 MockedStatic。

验证:agentscope-core 全量 2625 测试通过(0 失败 / 9 跳过),spotless 干净,全仓库编译通过。

@oss-maintainer delta to re-review:

  • d6b44805 — merge main + copy() 字段补全
  • 0aec217c — extractor seam + 四测试适配

@jujn jujn self-assigned this Oct 10, 2026
Brings in agentscope-ai#2697 (structured-output fallback determinism) and agentscope-ai#3129.

Conflict resolution: ReActAgentStructuredOutputTest.java — both sides
appended test suites at the end of the class (ours: prose/guard/
unknown-domain/retry-prompt; agentscope-ai#2697's: tool_choice forcing and
request-local reminder tests) plus overlapping imports. Kept both
suites and both import sets; closed the MathAnswer helper before the
incoming tests.

Semantic integration check (auto-merged ReActAgent.java): the two
retry mechanisms are disjoint by guard conditions — native path runs
this PR's validation retry (nativeResponseFormat != null, soTool ==
null), fallback path runs agentscope-ai#2697's forced-retry loop (soTool != null);
isNonDegradableFailure and the extraction seam are intact. Verified by
the focused structured-output suite: 48 tests green including both
sides' cases.
@helloworldtang

Copy link
Copy Markdown
Contributor Author

Synced with latest main (8eb91158, which now includes #2697) — pushed 9d54e7fe.

与 #2697 的集成结果(我们在其合并后立即 rebase 验证):

@oss-maintainer delta to re-review: 9d54e7fe (merge of 8eb91158;唯一冲突解决在结构化输出测试文件的追加区域)。

@helloworldtang

Copy link
Copy Markdown
Contributor Author

@jujn 大佬上午好,同步一个进展并请教一个问题:本 PR 已在刚合入的 #2697 之上重新同步(9d54e7fe,全量 2630 测试通过、CI 全绿)——响应侧校验(本 PR)与请求侧确定性(#2697)现在同树共存、机制互不冲突,之前 #2696 提到的两个方向已拼成完整闭环。想了解 TBD(To Be Discuss)目前是否已有结论,或还需要我们从哪些方面补充材料?如需调整范围或拆分提交,也随时可以配合。

@xzxiaoshan

Copy link
Copy Markdown
Collaborator

能力契约已经建立了信任边界。 Model.supportsNativeStructuredOutput() 返回 true,意味着 provider 侧通过 response_format / strict mode 在生成阶段(constrained decoding)就强制输出符合 schema。schema 在解码时就被约束,框架侧再做一次 JSON Schema 校验是重复劳动——只增加延迟和成本,几乎拦截不到任何真实错误。我们不应该在框架层默认"不信任 provider 的能力声明"。


@xzxiaoshan:

你的设计前提我完全认同,这正是本次改法调整的依据:

  1. 框架不应默认不信任 provider 的能力声明 — 同意。所以校验没有接进 native 主路径,而是做成 opt-in middleware:不挂载就零开销、零行为变化,信任边界保持不变。
  2. fallback 路径已有完整闭环 — 同意,也不重复造。middleware 只作用于 native 路径,服务两类场景:(a) 审计/合规要求框架侧对"模型实际返回了什么"留存验证证据;(b) 个别 provider 的 strict mode 并非完整 constrained decoding(不支持的 schema 关键字被丢弃后仍自由采样),此时框架侧校验是实际能拦住错误的唯一一层。
  3. 声明不诚实的 provider 应关能力开关降级 — 同意这是正解,middleware 与它互补而非替代:开关解决"该 provider 整体不可信",middleware 解决"可信 provider 的个别漏网"。
  4. "框架内的具体集成点" — 这条 middleware 就是:StructuredOutputValidationMiddleware 复用 StructuredOutputGenerator 的提取与反馈构造(后者退为内部引擎)。如果维护者认为 API 面积仍大,generateWithRetry 可以降为 package-private、只保留 middleware 入口,听你们的意见。
  5. ToolValidator.validateInput 每次重新编译 schema — 确认存在,与本 PR 无关,我可以单独开 issue 跟进;StructuredOutputValidator 里的 compiled-schema 缓存模式可直接参考。

【1. 框架不应默认不信任 provider 的能力声明 — 同意。所以校验没有接进 native 主路径,而是做成 opt-in middleware:不挂载就零开销、零行为变化,信任边界保持不变。】

最新代码已经走到这条路上了,如果保持信任 LLM 提供商的能力定义。该 PR 需要再做考虑。

@jujn

jujn commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator

非常感谢,不过我们对 core 模块核心链路的改动持谨慎态度(特别是 ReActAgent),非必要状态尽量不引入。
后续若仍有这种大规模改动,建议先开一 issue 列出改动架构并艾特维护者讨论。

@jujn
jujn requested a review from xzxiaoshan October 13, 2026 15:36

@xzxiaoshan xzxiaoshan left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

这块调整一下,其他方面没什么。
cla 也需要处理。

* @param schema the JSON Schema to validate against
* @return {@code null} when the output conforms, otherwise a newline-separated error list
*/
public static String validateJsonOutput(JsonNode output, Map<String, Object> schema) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

这段校验和 ToolValidator.validateInput 基本重复(同为 networknt 2020-12、同样的 null/错误串契约),fallback 路径的 executeStructuredToolUnobserved 已经在用它,建议直接复用,也能保持两条路径在 null 字段处理上的行为一致,不需要在 JsonSchemaUtils 里再新增一个校验入口。

@helloworldtang

Copy link
Copy Markdown
Contributor Author

@xzxiaoshan 感谢您的意见。为了让讨论基于最新代码,我们做了一轮源码核对和业界调研,把关键点同步如下——如果方向 OK,我们按结论把形态收敛掉。

1. 时间线更正:您引用的「opt-in middleware」是 8-27 的中间版本。8-28 @guslegend0510 发现该方案有架构性硬伤(附隔离复现):middleware 工作在 model-call 层,接收响应时 ReasoningContext 的 thinking/tool/usage 已累计且无法回滚,失败轮状态会污染最终结果。因此 middleware 方案在 faa05594 中移除,校验循环下沉到 reasoning 层(状态提交点之前)——当前 head 已与您引用的版本不同。

补充一个机制事实:本框架的 middleware 扩展点(onModelCall/onReasoning)不持有 ReasoningContext 的所有权——最终消息的构建与提交发生在链外(ReActAgent 的 .then(...) 中)。校验重试无法以现有 middleware 形态实现无污染的提交/回滚;若希望它成为插件形态,需要新增一个「提交前」扩展点——这可作为后续议题。

2. 业界调研(这层能力在别的框架怎么放):

3. 关键差异在「表面与默认」:各框架都把这能力挂在结构化 API 表面(Spring AI 用显式 .validateSchema() 开关、默认关)。我们目前「native 结构化路径默认开启校验」——这一半对齐业界惯例可以改。

4. 具体提案:默认不做校验重试(默认信任语义与现状一致);通过显式传参启用后获得完整校验+错误反馈重试闭环(如显式设置 policy 即启用,或独立开关;具体 API 形态听你们的)。附带一个与开关无关的建议:wrapNativeStructuredResult 解析失败目前静默返回(仅 warn、getStructuredData 为 null),这个 silent failure 建议一并修掉。

5. 范围说明:校验只作用于 call(msgs, Class/JsonSchema) 的 native 最终产出(中间工具轮、非结构化调用零接触);机制本身已全量验证、与 #2697 互斥分层同树共存。本 PR 是否先按第 4 点收敛,听你们的结论。

@jujn jujn removed the TBD To Be Discuss label Oct 14, 2026
@jujn
jujn merged commit a299fb1 into agentscope-ai:main Oct 14, 2026
6 of 7 checks passed
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.

7 participants