Repository navigation
feat(core): add response-side structured output validation with error-feedback retry - #2858
Conversation
|
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 Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
3d30848 to
93bec48
Compare
| * @throws StructuredOutputValidationException when all attempts fail | ||
| */ | ||
| public static JsonNode generateWithRetry( | ||
| Function<List<StructuredOutputValidator.ValidationError>, String> generate, |
There was a problem hiding this comment.
[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('{'); |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
[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 = |
There was a problem hiding this comment.
[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 文档中明确说明限制。
|
关于这个 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 无关的性能问题: |
|
感谢两位的详细评审,逐条回应如下。对应实现已完成并推送(29 个 structured-output 测试 + agentscope-core 全量 2328 通过,spotless 干净)。
你的设计前提我完全认同,这正是本次改法调整的依据:
|
|
看一下框架中已有的 generate_response 原理,以及在后面版本合入的 #2697 增强处理。 且:这些类怎么会全部塞到 core 模块的 formatter 包中呢?从功能上来看是 middleware。 |
|
发现新的 P1:失败轮输出进入 middleware 校验前,已经被 ReasoningContext 累计并触发 hooks;后续仅回写 text,没有回滚 thinking/tool 状态。隔离集成测试可稳定复现:最终成功结果会混入失败轮 thinking,usage 也没有正确累计。 |
|
感谢评审,4 条意见已全部处理并 force-push(commit 0d4d57a):
|
|
感谢指出,这个 P1 成立:失败轮的 thinking/tool 状态已写入 ReasoningContext 并触发过 hooks,middleware 重试只替换了 text,状态污染会导致最终结果混入失败轮 thinking、usage 累计也不对。我正在处理——方案方向是让重试路径具备状态回滚能力(回滚 ReasoningContext 到校验前快照,或把校验循环下沉到 reason 状态提交点之前),确认方案后会更新 PR。隔离复现如果方便贴一下,我可以对照验证修复。 |
|
可以,我这边有隔离复现,基于当前 head 69de1a6。
|
|
感谢提供隔离复现,已按该场景修复并推送(commit faa0559)。 根因:middleware 工作在 model call 层,收到流时 ReasoningContext 已完成 thinking/tool 状态累计并触发过 reasoning hooks,架构上无法回滚——所以把校验循环下沉到了 ReActAgent reasoning 层( 修复行为:
已按你的复现场景新增回归测试 |
|
感谢大佬,看PR已提交 目前处于 LGTM 状态——如果还有需要我调整或补充的地方,随时告诉我。 |
|
@xzxiaoshan 感谢你详细的设计前提讨论,几点逐条回应(也对 LGTM 之前悬而未决的讨论做一个收口): 1. 关于 native 路径校验的必要性——"不信任 provider"与 opt-in 语义 当前实现是严格 opt-in 的:只有业务显式调用 成本侧:本地 JSON Schema 校验是微秒级 CPU 操作,相对模型调用的秒级延迟与 Token 成本可忽略;重试成本只在真实失败时发生,且受 2. 与 #2697 的关系——互补而非重复 认同 #2697 的 L0-L4 分层视角:它加固的是 fallback 路径(L2 模式提示、L3 强制调用 generate_response、L4 重试上限),本 PR 补的是 native 路径的响应侧校验 + 错误反馈重试(native 路径此前完全没有等价能力)。两条路径合起来,结构化输出的可靠性矩阵才是完整的:同一 schema,无论 provider 能力如何,都有有界且可观测的保障。 错误反馈格式也已对齐:native 重试提示的每行 3. 关于 formatter 包的位置 重构后校验循环已内建到 |
|
合并最新 main 后重读了一遍代码,补了一轮收尾(commit
新增 |
|
@jujn @Buktal 二位好,这个 PR 想请维护者帮忙看一下:guslegend0510 已 review 通过(含三轮修改),评审中提出的全部问题已处理完毕;CI 全绿(双平台 build + codecov + license),昨天又补了一轮自查收尾(见上一条评论)。与 @xzxiaoshan 的设计讨论已在 8-31 逐条回应,目前等回复中。如果还有需要调整的地方,随时告诉我,谢谢! |
Buktal
left a comment
There was a problem hiding this comment.
- 考虑把 attempt 那几个计数器挂到 call 级状态(别把整个重试环上移去重跑 doCallInner,工具副作用会被重放):防止带工具调用时每进新 iteration 就重置,maxAttempts 和 tokenBudget 就形同虚设了。
- 考虑把 structuredOutputPolicy 挪到 ReActAgent 的 builder 里:模型层 DTO 里塞个带回调的 agent 策略,模型适配器那边也用不上。
- 建议把两套解析/重试收敛成一套,agent 复用 extractJsonObject 或者把 generateWithRetry 删了只留 retryPrompt:不然两套语义进了公共 API,以后再统就只能走废弃流程了。
- 建议给 correction 打个标,成功后像 fallback 那样清理下会话(再补个测试):不然纠错残迹一直留着,后面每轮调用都得多花 token。
一些小问题:
- Generator 里那几处中文评审注释(P1-2 什么的)顺手改成英文吧。
- 校验那块每次 new ObjectMapper 有点浪费,复用个静态的就行。
- Validator 里那个手写 CACHE 跟 registry 自带的重复了、还无界,删了吧。
- 校验和最终解析用的文本拼接方式不一样,统一走 getTextContent、记得加空值防护。
- FailedAttempt 的 validationErrors 传 null 也能过,构造里归一化一下更稳。
- onFailedAttempt 回调没保护,用户代码一抛异常整个 call 就被带偏了,包个 try/catch 吧。
- 异常类的字段声明跑到构造器后面去了,挪到前面跟大家保持一致。
- 几处全限定名(JsonSchema.validate 签名那些)改成 import 吧。
- listenerReceivesFailures 那个测试没测到被测类,删掉或者改实吧。
|
感谢详细的 review,13 条已全部处理(commits 1. attempt 计数器挂 call 级状态 — 计数器、累计 usage、failedAttempts 已迁到 2. 3. 解析收敛为一套 — 校验循环改用 4. correction 打标 + 成功后清理 — 新增 小问题 9 条均已照办:注释英文化、复用静态 MAPPER(随统一入口自然消亡)、手写 CACHE 删除(registry 2.0.0 自带缓存)、统一 |
Buktal
left a comment
There was a problem hiding this comment.
- 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();
}`
-
ReActAgent.java:2402 / 1404-1414
校验能过但最终 wrap 挂掉体验很糟,建议复用校验阶段解析好的 payload,保持单 source of truth -
StructuredOutputRetryPolicy.java:34 / ReActAgent.java:5175
顺手更新为 ReActAgent.Builder 的实际 API 入口就好 -
ReActAgent.java:2560-2566 / 1424
跟 wrapNativeStructuredResult 看齐补上 .usage(...) 拷贝,能确保用量记账完整 -
StructuredOutputGenerator.java:74 / 44
生成逻辑移走后只剩 extract 和 prompt helper,可以考虑改叫 StructuredOutputUtils 或 StructuredOutputExtractor 更贴切
3d8e11d to
e27618b
Compare
|
Thanks @Buktal — all five points are addressed in 3150d68, plus one hardening that fell out of writing the acceptance tests (baca0e0): 1. 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. 2. Payload reuse (single source of truth) — the payload parsed during validation is stored on the call scope ( 3. Javadoc entry point — 4. Residue re-tagging — 5. Rename — 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 The branch now includes the latest |
|
@zouyx @chickenlj @jujn 说明一下:最新一次 Update branch 后,CI 在
疑似时序敏感的 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.
905cb14 to
b85828d
Compare
|
Rebased onto latest 冲突性质:main 侧将 验证: |
oss-maintainer
left a comment
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
[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) { |
There was a problem hiding this comment.
[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 |
There was a problem hiding this comment.
[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).
|
|
||
| ## Unreleased | ||
|
|
||
| ### Compatibility |
There was a problem hiding this comment.
[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()) |
There was a problem hiding this comment.
[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
left a comment
There was a problem hiding this comment.
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 HEADoverReActAgent.java,formatter/,MessageMetadataKeys.javaandExceptionUtils.javais 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 onCallExecution(:1802, one instantiation site at:723), not on the agent. - No upstream collision: upstream's
ToolValidatorchange is purely additive andvalidateInput(String, Map)is unchanged, andsupportsNativeStructuredOutputWithTools()is adefaultmethod onModel(:69), so the new Gemini/Anthropic server-tool models inherit it and the routing call at:1308still compiles. All 9MessageMetadataKeysliterals 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
|
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. |
|
Status on
One thing still open that only a maintainer can settle: the PR carries the Nothing further is required from you unless the head moves — if you do sync Automated response by github-manager-bot |
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.
|
Synced with latest 冲突解决与集成修复(三处,均已本地验证):
验证: @oss-maintainer delta to re-review:
|
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.
|
Synced with latest 与 #2697 的集成结果(我们在其合并后立即 rebase 验证):
@oss-maintainer delta to re-review: |
【1. 框架不应默认不信任 provider 的能力声明 — 同意。所以校验没有接进 native 主路径,而是做成 opt-in middleware:不挂载就零开销、零行为变化,信任边界保持不变。】 最新代码已经走到这条路上了,如果保持信任 LLM 提供商的能力定义。该 PR 需要再做考虑。 |
|
非常感谢,不过我们对 core 模块核心链路的改动持谨慎态度(特别是 ReActAgent),非必要状态尽量不引入。 |
| * @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) { |
There was a problem hiding this comment.
这段校验和 ToolValidator.validateInput 基本重复(同为 networknt 2020-12、同样的 null/错误串契约),fallback 路径的 executeStructuredToolUnobserved 已经在用它,建议直接复用,也能保持两条路径在 null 字段处理上的行为一致,不需要在 JsonSchemaUtils 里再新增一个校验入口。
|
@xzxiaoshan 感谢您的意见。为了让讨论基于最新代码,我们做了一轮源码核对和业界调研,把关键点同步如下——如果方向 OK,我们按结论把形态收敛掉。 1. 时间线更正:您引用的「opt-in middleware」是 8-27 的中间版本。8-28 @guslegend0510 发现该方案有架构性硬伤(附隔离复现):middleware 工作在 model-call 层,接收响应时 ReasoningContext 的 thinking/tool/usage 已累计且无法回滚,失败轮状态会污染最终结果。因此 middleware 方案在 补充一个机制事实:本框架的 middleware 扩展点( 2. 业界调研(这层能力在别的框架怎么放):
3. 关键差异在「表面与默认」:各框架都把这能力挂在结构化 API 表面(Spring AI 用显式 4. 具体提案:默认不做校验重试(默认信任语义与现状一致);通过显式传参启用后获得完整校验+错误反馈重试闭环(如显式设置 policy 即启用,或独立开关;具体 API 形态听你们的)。附带一个与开关无关的建议: 5. 范围说明:校验只作用于 |
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:
response_format.JsonNodeis validated against the requested schema.Msg.metadata[_structured_output].generate_responsetool 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:
When disabled:
The configuration is copied by
Builder.copy()and therefore survives builder reuse.