Skip to content

feat(core): Enhance reliability of structured output degradation path - #2697

Merged
xzxiaoshan merged 25 commits into
agentscope-ai:mainfrom
xzxiaoshan:fix/structured-output-fallback
Oct 10, 2026
Merged

xzxiaoshan merged 25 commits into
agentscope-ai:mainfrom
xzxiaoshan:fix/structured-output-fallback

Conversation

@xzxiaoshan

@xzxiaoshan xzxiaoshan commented Aug 13, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Structured-output fallback could finish without structured data when the model skipped the synthetic generate_response tool. This PR makes that path deterministic while keeping the request and durable context clean.

Fixes #2696
Fixes #3393
Fixes #641
Fixes #1103
Fixes #1699

What changed

  • On fallback calls, AgentScope now injects a per-request <system-reminder> that tells the model it must call generate_response:
    • If the final model input is a user message, the reminder is appended to a request-local copy of that message.
    • Otherwise it is appended as a new user message.
    • The reminder is never written to state.contextMutable(), hooks, middleware, session persistence, or later calls.
  • If the model still finishes without calling generate_response, reasoning is retried up to 3 times:
    • Models that declare supportsToolChoiceSpecific() = true receive ToolChoice.Specific("generate_response") on retry.
    • Other models continue with the prompt reminder only.
    • After the retry ceiling, the agent logs a warning and returns the unstructured response instead of looping forever.
  • The synthetic generate_response tool remains per-call and is not registered in the shared toolkit, so concurrent structured-output calls do not interfere.
  • Model.supportsToolChoiceSpecific() defaults to false; custom or unknown models never receive named tool_choice unless they explicitly opt in.
  • Official OpenAI, DeepSeek, Anthropic, Gemini, DashScope, Ollama, and OpenAI Responses endpoints declare support. GLM, MiniMax, and thinking-enabled Kimi models remain false.

Compatibility

  • No persistent AgentState field was added for structured-output mode.
  • The reminder and synthetic tool are request-local, so context, cache prefixes, and multi-turn sessions are unaffected.
  • Existing public APIs are preserved; supportsToolChoiceSpecific is additive.

@xzxiaoshan
xzxiaoshan force-pushed the fix/structured-output-fallback branch from c8bbd73 to 6e5800b Compare August 13, 2026 13:23
@codecov

codecov Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.26829% with 17 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...e/src/main/java/io/agentscope/core/ReActAgent.java 75.47% 9 Missing and 4 partials ⚠️
...n/java/io/agentscope/core/model/ChatModelBase.java 0.00% 3 Missing ⚠️
.../src/main/java/io/agentscope/core/model/Model.java 0.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

AgentScopeJavaBot

This comment was marked as outdated.

@AgentScopeJavaBot AgentScopeJavaBot 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.

🤖 AI Review

This PR enhances the reliability of the structured-output fallback path in ReActAgent. When the model does not support native structured output (response_format), a synthetic generate_response tool is injected; however, the model could previously ignore it and emit free text, leaving the caller without structured data. The fix introduces three mechanisms: (1) persistent enter/exit system-reminder banners that prime the model about the active mode, (2) a force-retry strategy — ToolChoice.Specific for OpenAI, prompt-reminder for GLM/MiniMax — capped at 3 retries, and (3) context compression that strips SO-related messages after completion. The implementation is well-structured, thoroughly tested (11 new test cases), and solves the problem described in issue #2696. A few design concerns around persistent reminder accumulation and an optimistic capability default warrant attention.

(inline comments could not be attached — line numbers fell outside PR hunks. See archived report.)

@AgentScopeJavaBot AgentScopeJavaBot added enhancement New feature or request area/core/model Model providers and formatters labels Aug 15, 2026
@xzxiaoshan
xzxiaoshan force-pushed the fix/structured-output-fallback branch from 76c7724 to 3d49478 Compare August 16, 2026 09:55
@xzxiaoshan

This comment was marked as outdated.

dargoner pushed a commit to dargoner/agentscope-java that referenced this pull request Aug 25, 2026
合并 PR agentscope-ai#2697,增强结构化输出降级路径、强制 generate_response 调用,并兼容主线消息上下文持久化逻辑。
@dargoner

Copy link
Copy Markdown
Contributor

跟进一下这个 PR 的进度。

现状核对:6 commits / 9 files,目前只有机器人 COMMENTED,没有人工 approve;分支落后 main 20 个提交;关联的 issue #2696 仍为 open。

这个改动针对的是结构化输出降级路径的可靠性(模型不支持原生 response_format 时,强制调用 generate_response 并注入模式提示,避免模型自由发挥或陷入反复重试)。从下游使用看这类问题确实存在——我们 fork 里长期带着这份实现跑。

想请维护者/作者确认是否有已知阻塞,例如:

如果方向已经不被接受,也建议在 issue #2696 里明确说明,免得下游继续依赖这份实现。如果需要我这边补充下游的实际使用数据(什么模型、什么触发条件下会走到降级路径),我可以补到这条 PR 里。

…lback calls

The fallback structured-output path injects a persistent <system-reminder>
when entering tool mode. When the model produced no result (empty response
or stream failure), that reminder and the flipped so_tool_active flag were
still persisted, leaving durable state that claimed the mode was active
despite no output. Roll the injected reminder back on these no-result
exits so the durable context matches the other empty-response paths and
persists only the user input.
@xzxiaoshan

xzxiaoshan commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

@jujn 看评论反馈, @dargoner 他们似乎已经做过 review 并已经正式使用没有问题,是否可以 merge 。

oss-maintainer

This comment was marked as outdated.

…ing, strip on give-up

Strategy-B prompt reminders (providers without ToolChoice.Specific, e.g.
GLM/MiniMax) were appended on every forced retry and only cleaned on the
success path, so they stacked up to three per call and accumulated
without bound across calls that gave up.

- Inject by remove-then-add so at most one reminder is in context at a
  time; this also cleans leftovers persisted by a previous give-up call.
- Strip reminder-marked messages when the loop gives up after three
  forced retries. The persistent enter banner and so_tool_active flag
  are kept: the turn's interaction is retained in durable state, and
  the exit banner on the next normal call closes the mode.
- Add regression tests: reminder counts across retries ([0, 1, 1]) and
  durable-context assertions after give-up (0 reminders, 1 enter, 1
  exit banner).
… option

- OpenAIModelProviderSupport.applyAdvancedOptions now reads the
  supportsToolChoiceSpecific boolean option, mirroring
  nativeStructuredOutput, so users targeting OpenAI-compatible providers
  that only support tool_choice="auto" can configure the flag without
  subclassing.
- Extend OpenAIModelProviderTest.createUsesModelCreationContext to cover
  the new option.
- Cover AgentState.so_tool_active in AgentStateTest (default, builder,
  setter, JSON round-trip, omitted-field fallback).
- Restore supportsToolChoiceSpecific=true in MockModel.reset().
oss-maintainer

This comment was marked as outdated.

@xzxiaoshan
xzxiaoshan force-pushed the fix/structured-output-fallback branch from 16a0e41 to a0bf93d Compare September 15, 2026 00:29

@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

Delta re-review of the new author commit a0bf93d2 since my last review on a0c49d70. The commit is polish, not behaviour change: it documents why the persistent enter banner is deliberately kept while the transient force reminders are stripped on give-up, adds a JSON round-trip test for the reminder metadata types, and documents the supportsToolChoiceSpecific opt-out for OpenAI-compatible gateways in both the EN and ZH model docs. This closes the loop on the state-leak concerns raised in the previous round — nothing here blocks the PR.

Findings

  • [Info] agentscope-core/src/test/java/io/agentscope/core/state/AgentStateTest.java:185 — good test: it pins the exact assumption the give-up cleanup depends on (Boolean.TRUE.equals on a metadata value that may have come back from a durable store) rather than just asserting the round-trip is lossless. One gap: STRUCTURED_OUTPUT_REMINDER_TYPE is asserted to survive as the String "PROMPT"; if the writer side ever persists an enum name of a different shape, this assertion tracks the implementation instead of the contract. Consider asserting on the enum's name constant rather than a literal, or dropping that line since the comment already says the marker is informational and never read for cleanup.
  • [Info] agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:1418 — the comment now explains the enter/exit banner asymmetry well. Since this is precisely the kind of invariant a later "simplify the cleanup" change would break, it would be worth naming the test that protects it (the give-up/strip test) in the comment, so the two stay in sync.
  • [Info] docs/v2/en/docs/building-blocks/model.md:421 (and the mirrored ZH section) — the new "Providers without specific tool_choice support" section is the right documentation to add, and the failure mode is stated concretely (retry a constraint the gateway never applies, loop, lose structured data). Minor: the ZH and EN blocks are not literal mirrors — EN says the option "is also available as a provider-config advanced option", ZH phrases it as an additional sentence; worth keeping the wording aligned so neither drifts.

Verdict

No blocking findings. The remaining item on my side from earlier rounds was the give-up-path state cleanup, and the added round-trip test plus this comment make the intent explicit. Rebase onto main when convenient so CI can re-run against the current tree.


Automated review by github-manager-bot

@xzxiaoshan
xzxiaoshan removed the request for review from AgentScopeJavaBot October 4, 2026 15:32
oss-maintainer

This comment was marked as outdated.

jujn added 6 commits October 8, 2026 22:28
# Conflicts:
#	agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/main/java/io/agentscope/extensions/model/openai/OpenAIChatModel.java
#	agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/main/java/io/agentscope/extensions/model/openai/OpenAIModelProviderSupport.java
#	agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-openai/src/test/java/io/agentscope/extensions/model/openai/OpenAIModelProviderTest.java
@jujn jujn changed the title issue#2696: 增强结构化输出降级路径可靠性,强制调用 generate_response 并注入模式提示。 feat(core): Enhance reliability of structured output degradation path Oct 10, 2026
@jujn

jujn commented Oct 10, 2026

Copy link
Copy Markdown
Collaborator

Assign to @wahllllll (Review)

@wahllllll

wahllllll commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Second pass over 4fe0e54f (@xzxiaoshan) — the earlier approval is stale now that three more commits landed on top of it.

First, the Kimi fix in ccd5b0a5 is exactly right. supportsToolChoiceSpecific(false) on thinking Kimi models closes the gap where KimiFormatter.applyKimiToolChoice rewrote Specific into auto on the way out — the request looked constrained and wasn't. Adding the #3393 reference too, thanks.

Three merge leftovers, fix attached

I opened xzxiaoshan#1 (wahllllll:fix/structured-output-merge-residue → fix/structured-output-fallback): 3 files, +7/−5, no behaviour change. Take the commit as-is, cherry-pick it, or ignore it — the notes below stand on their own. Your 3421ac5 merge of main does not affect any of them: I re-read all three files at that revision and the counts are unchanged.

  1. ReActAgent.Builder.copy() assigns copy.agentId twice. The second one sits after copy.description. Setters are idempotent so runtime is unaffected, but main has exactly one line and the duplicate reads as if a field between the two is being re-wired.

  2. HarnessAgentIdTest chains .legacySessionHistory(true) twice in both fixtures — same merge residue. Removing them makes the file identical to main, so it drops out of this PR's diff entirely. That also answers, for free, why a harness test file is in a structured-output PR.

  3. MockModel's field javadoc defends its default with the assumption this branch drops. It reads:

    Defaults to true since most models support it; only the few providers that don't override it to false.

    "Most models support it" is precisely the assumption 4fe0e54f drops when it flips the interface default to false, so the reader's only stated reason for the mock returning true is the claim you just rejected — nothing signals that the mock is deliberately diverging. It also calls a test mock a "provider". Reworded to say what the mock does and to point at setSupportsToolChoiceSpecific(...).

Four things worth deciding before merge

1. The supportsToolChoiceSpecific() default flip is a behaviour change for self-hosted endpoints.

4fe0e54f changes it true → false in Model, and ChatModelBase from field == null || field to Boolean.TRUE.equals(field). The direction is right — never assume a named tool_choice on an unknown endpoint — and OpenAIModelProvider / DeepSeekModelProvider scoping it to DEFAULT_BASE_URL.equals(baseUrl) is a sane way to draw the line.

The consequence is worth a sentence somewhere though: anyone pointing an OpenAI-compatible model at a self-hosted or gateway URL — vLLM, an internal gateway, direct Moonshot — silently moves off the hard ToolChoice.Specific constraint and onto the prompt reminder. The hard constraint is the reliability this PR adds, so for exactly those deployments the benefit halves unless they opt in. The per-provider table in docs/v2/.../model.md documents the end state well; what's missing is a migration note and a release-notes line saying the default moved.

2. ReActAgent.java:3111 — the forced retry can't escalate for non-Specific models.

The reminder text is regenerated identically each round, and the hard constraint is gated on soForceToolChoiceCount > 0 (ReActAgent.java:2806). So:

model round 1 rounds 2–4
supportsToolChoiceSpecific() == true soft hard Specific
supportsToolChoiceSpecific() == false soft soft, identical prompt

The three-round budget is real, but the pressure on the model does not increase — rounds 2 and 3 only re-append the model's own rejected answer. Your testStructuredOutputPromptReminderPresentOnEveryFallbackRound asserting List.of(1, 1, 1) at ReActAgentStructuredOutputTest.java:721 is the proof: same count every round. Escalating wording per round, or a "your previous answer was rejected" prefix, would make the retries do something the first call didn't.

3. Rejected answers are persisted; the reminder isn't.

ReActAgent.java:2932-2934 adds eventMsg to state.contextMutable() before the isFinished check at :2956. So up to three rejected free-text answers stay in the durable context, while the reminder that prompted the retry is deliberately transient (appendTransientSoToolReminder, :3125). The asymmetry is legible in the code, but it means a long-lived agent accumulates refused answers it can never act on. Worth a comment stating that's intentional, or filtering them out at :2961.

4. KimiModelProvider's nativeStructuredOutput flipped false → true.

Not a defect — you updated the class javadoc in step, so it's deliberate, and nativeStructuredOutputWithTools(false) stays as it was. It's just the one change in 4fe0e54f that has nothing to do with tool_choice, and it decides which structured-output path Kimi takes. That deserves its own release-notes line rather than riding along inside a tool_choice fix.

Verification

mvn -o -pl agentscope-core,agentscope-harness -am spotless:check test \
  -Dtest='ReActAgentStructuredOutputTest,HarnessAgentIdTest'

BUILD SUCCESS. ReActAgentStructuredOutputTest: 13 run, 0 failures, 0 errors, 1 skipped. HarnessAgentIdTest: 1 run, 0 failures. Spotless clean on both modules.

@wahllllll

Copy link
Copy Markdown
Contributor

Verified bfbd0bc — all three cleanups landed, and two of the files are byte-identical to what I had on my branch:

file vs my branch 8184a65
ReActAgent.java identical
HarnessAgentIdTest.java identical
MockModel.java javadoc wording only — yours is tighter

Counts agree: copy.agentId is back to one occurrence and .legacySessionHistory(true) back to three, so HarnessAgentIdTest.java is now identical to main and drops out of this PR's diff entirely.

I've closed xzxiaoshan#1 as superseded — no point leaving a conflicting PR sitting in your fork.

Re-anchoring the four open items on the new head, since my earlier comment was written against 4fe0e54f and you have merged main twice since:

  1. supportsToolChoiceSpecific() default true → false — still the one I would most like a release-notes line for. Self-hosted and gateway OpenAI-compatible endpoints move off the hard tool_choice constraint silently, and for them that constraint is the reliability this PR adds.
  2. The forced retry cannot escalate for non-Specific models — the reminder text is regenerated identically each round, so rounds 2 and 3 only re-append the answer the model already produced.
  3. Rejected answers persist into state.contextMutable() while the reminder that prompted the retry stays transient.
  4. KimiModelProvider.nativeStructuredOutput false → true — deliberate, the javadoc moved with it; it is just the one change here unrelated to tool_choice.

None of these block the merge on my side. 1 and 4 are release-notes material; 2 and 3 are design calls that are yours to make.

@xzxiaoshan
xzxiaoshan merged commit 8eb9115 into agentscope-ai:main Oct 10, 2026
6 checks passed
@jujn jujn added the 2.0.5 label Oct 10, 2026
@jujn

jujn commented Oct 10, 2026

Copy link
Copy Markdown
Collaborator

helloworldtang pushed a commit to helloworldtang/agentscope-java that referenced this pull request 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 pushed a commit to helloworldtang/agentscope-java that referenced this pull request Oct 11, 2026
Brings main (incl. agentscope-ai#2697, agentscope-ai#3324, agentscope-ai#2751, agentscope-ai#3129) into the branch. Only
conflict: ReActAgentStructuredOutputTest.java — this branch's added test
(testToolBasedExtractionPreservesMessageIdentity) sat exactly where
agentscope-ai#2697 later appended its new tests; kept both sides (our test plus the
incoming suite) and both import sets. ReActAgent.java auto-merged.

Verified: ReActAgentStructuredOutputTest 16 tests green including both
this branch's identity test and the merged-in tests.
@wahllllll

Copy link
Copy Markdown
Contributor

@jujn 感谢!也谢谢把机制文档贴出来,我们照着核了一遍,有几条确实是我们之前没做到的,接下来会调整:

  • 评审完整跟进一个 PR 后,会显式给出 LGTM —— 之前只写问题清单,没留下这个计分标记;
  • 新开的 PR 都会关联对应 issue,不再出现没有 issue 的 PR;
  • 注释尽量克制,不留 AI 样板式注释。

#2697 这个修复本身很扎实,后续有需要复核的 PR 随时 @ 我。

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

Labels

2.0.5 area/core/model Model providers and formatters enhancement New feature or request

Projects

None yet

6 participants