Repository navigation
fix(agent): restore structured-output self-healing retry in fallback path - #2047
zhangliyuangit wants to merge 2 commits into
Conversation
There was a problem hiding this comment.
Pull request overview
This PR restores the 1.x “self-healing” behavior for fallback structured output in ReActAgent: when the model ends a structured-output call without invoking the synthetic generate_response tool, the agent injects a reminder and retries (up to 3 times), forcing tool_choice on the retry round to guarantee the tool call at the API level.
Changes:
- Add a retry loop in the ReAct post-reasoning finish path to re-enter reasoning after injecting a structured-output reminder (bounded by
STRUCTURED_OUTPUT_MAX_RETRIES). - Force
GenerateOptions.toolChoice = Specific("generate_response")when the retry round is identified as a TOOL_CHOICE reminder round. - Add
ReActAgentStructuredOutputRetryTestcovering success-after-retry, give-up-after-max-retries, and no-retry-when-voluntary.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java | Implements structured-output fallback retries + forced tool_choice, plus helper reminder detection/building. |
| agentscope-core/src/test/java/io/agentscope/core/agent/ReActAgentStructuredOutputRetryTest.java | Regression tests verifying the retry loop and max-retry behavior. |
| state.contextMutable() | ||
| .add(createStructuredOutputReminder()); | ||
| return reasoning(iter + 1, true); |
There was a problem hiding this comment.
Intentional, keeping as-is. Retaining the plain-text attempt in the context is what lets the forced retry round restate the same content through the tool call — 1.x behaved identically (its compressMemory used the same isStructuredOutputRelated criteria and also kept the text attempt), and production ports of the 1.x hook rely on this echo for verbatim consistency between the text round and the tool round. Removing it would change 1.x parity semantics; happy to revisit if maintainers prefer.
| .add(createStructuredOutputReminder()); | ||
| return reasoning(iter + 1, true); | ||
| } | ||
| return Mono.justOrEmpty(eventMsg); |
There was a problem hiding this comment.
Fixed in e5d2b4a. The give-up path now strips reminder-tagged messages from the persisted context before returning, and the regression test asserts a follow-up turn's model input contains no leftover reminders. (Note this is stricter than 1.x, which also leaked reminders on give-up — but the cleanup is clearly right.)
| return Msg.builder() | ||
| .name("system") | ||
| .role(MsgRole.USER) | ||
| .content( |
There was a problem hiding this comment.
Keeping as-is: this is a verbatim port of the 1.x StructuredOutputHook.createReminderMessage (name("system") + role(USER)), and teams migrating from 1.x diff old/new logs against each other — changing the name would break that parity for no functional gain. Provider formatters key off role, which is USER here as before. Can change in a follow-up if maintainers prefer consistency over parity.
| return metadata != null | ||
| && StructuredOutputReminder.TOOL_CHOICE | ||
| .toString() | ||
| .equals( | ||
| metadata.get( | ||
| MessageMetadataKeys.STRUCTURED_OUTPUT_REMINDER_TYPE)); |
There was a problem hiding this comment.
Fixed in e5d2b4a — isToolChoiceReminder now requires STRUCTURED_OUTPUT_REMINDER == true in addition to the TYPE key. (1.x checked only the TYPE key, but the extra guard is strictly safer.)
This comment was marked as abuse.
This comment was marked as abuse.
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
🤖 AI Review
Restores structured-output self-healing retry in fallback path. When model ends with plain text (no generate_response tool call), injects reminder and forces tool_choice for up to 3 retries. One recommended issue: give-up path leaves consecutive assistant messages in context (reminders removed but intermediate assistant responses remain), which breaks alternating-role format for some LLM providers.
| scope.state.contextMutable().add(out); | ||
| } else { | ||
| // Give-up path: the reminders injected by the | ||
| // self-healing retries are internal artifacts — |
There was a problem hiding this comment.
[minor] Give-up path removes reminder messages but leaves 3-4 consecutive ASSISTANT messages in context (from retry rounds). This breaks alternating-role format required by some LLM providers (e.g., Anthropic Claude). In give-up path, also remove intermediate assistant responses from retry rounds, keeping only the final result.
There was a problem hiding this comment.
✅ Verified as addressed in a4457cb: Give-up path now calls isFailedStructuredOutputRetryArtifact which removes both reminder messages and intermediate assistant responses (via soRetryAttemptMsgs), exactly as requested.
e5d2b4a to
73d0e4c
Compare
73d0e4c to
a4457cb
Compare
|
@oss-maintainer The branch has been rebased onto the latest main, and the review feedback has been addressed. The local agentscope-core suite passes with 2212 tests and 0 failures. The Java CI workflow is currently waiting for maintainer approval. Could you please approve the workflow and take another look when convenient? |
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
All previously raised review comments have been addressed.
465b455 to
013d879
Compare
|
Rebuilt this PR on the latest The regression tests were confirmed failing before the implementation and now cover retry success, retry exhaustion, error/cancellation cleanup, context hygiene, and aggregated usage. Fresh local verification passes: @oss-maintainer, could you please take another look when convenient? |
013d879 to
5e8674f
Compare
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Restores the 1.x self-healing loop for the fallback structured-output path: when the model answers in plain text instead of calling the synthetic generate_response tool, a reminder is injected and the next reasoning round forces tool_choice=Specific("generate_response"), up to 3 times, with internal reminder/intermediate artifacts removed from the context afterwards. The direction is right, the cleanup-on-error/cancel coverage is thoughtful, and the new test suite (retry success, exhaustion, error, cancellation, voluntary call) is well above the usual bar for this repo — the usage-aggregation assertion in particular is a nice touch.
The concerns are all about how the retry round is recognised and cleaned up, not about the design: the two detection mechanisms (last-message sniffing, reference identity) depend on message ordering and object identity that middlewares in this codebase are known to change, so the heal can silently degrade into a plain re-prompt or leak a discarded answer into the persisted session. None of these look like merge blockers if they are addressed or explicitly reasoned about.
Findings
- [Warning]
ReActAgent.java:2343—isToolChoiceReminder()only inspects the last input message;TaskReminderMiddleware/InboxMiddlewareappend messages after it, so forcing can silently not apply. Prefer an explicit per-call flag. - [Warning]
ReActAgent.java:3907— retry artifacts are matched by reference identity, which breaks if a hook/middleware replaces the context entry; the discarded answer then persists. - [Warning]
ReActAgent.java:1357—doOnCancelmutates the shared context off the serialized pipeline and never persists the cleaned state, unlike the error path. - [Warning]
ReActAgent.java:2347— forced options win inmergeOptions, overriding a user/hook-providedToolChoice.None; restrict forcing and log skips. - [Info]
ReActAgent.java:227— retry count is hard-coded andStructuredOutputReminderis now effectively dead as a user-facing option (only used as a metadata string); wire it or trim it. - [Info]
ReActAgent.java:2506— give-up cleanup is split between two sites covering the same invariant.
Questions
- Does
agent.call(msgs, Class)on the fallback path have any existing e2e/integration coverage on a real provider (DashScope/OpenAI compatible) confirming providers accepttool_choicepointing at a tool that is injected per-call and is not in the shared toolkit schema list? Some providers validatetool_choiceagainsttools[]. - Should a give-up after 3 retries surface anything to the caller (event/log at WARN, or a
GenerateReasonmarker on the returned message)? Today it returns plain text with only alog.debug, which is hard to distinguish from "the model legitimately answered in prose" when debugging user reports. - The PR description says reminders are removed "on both success and give-up" — is the multi-turn case intended (a later
agent.callin the same session never sees them) but the intermediate answers of an earlier successful structured call also removed from history? That looks desirable for token cost, just confirming it is deliberate since it changes what a session store contains for existing users of the fallback path.
Automated review by github-manager-bot
| options); | ||
| } | ||
| if (soTool != null | ||
| && isToolChoiceReminder(event.getInputMessages())) { |
There was a problem hiding this comment.
[Warning] Detecting the retry round by inspecting the last input message is fragile. event.getInputMessages() is the output of the onReasoning middleware chain, and several middlewares append their own transient messages to that list after the agent context (e.g. TaskReminderMiddleware adds a <system-reminder> todo message, InboxMiddleware appends inbox hints). Whenever one of them runs after us, isToolChoiceReminder() returns false and the retry degrades into a plain re-prompt — exactly the loop this PR is trying to heal, but now with a forced tool_choice that silently never applies.
Suggest carrying the intent explicitly instead of inferring it from message order, e.g. a boolean soForceToolChoice on CallExecution that runPostReasoningPipeline sets when it appends the reminder and reasoning() consumes (and clears) on the next round. That also makes the pairing between "reminder injected" and "tool_choice forced" impossible to desynchronise.
| } | ||
|
|
||
| private boolean isStructuredOutputRetryAttempt(Msg msg) { | ||
| return soRetryAttemptMsgs.stream().anyMatch(attempt -> attempt == msg); |
There was a problem hiding this comment.
[Warning] Identity comparison (attempt == msg). The retry attempt is registered from eventMsg in runPostReasoningPipeline, i.e. the object reference stored in state.contextMutable(). If any hook/middleware rewrites that entry in place (Msg is rebuilt by withGenerateReason(...)-style copy helpers, and compaction/middleware paths do replace context entries), the identity check silently no-ops and the discarded plain-text answer stays in the persisted session context — the follow-up turn then sees a stale assistant message that never produced structured output.
Reminder messages are already identified by metadata (MessageMetadataKeys.STRUCTURED_OUTPUT_REMINDER); tagging the retry attempt with a metadata key (or checking soRetryAttemptMsgs by getId()/name+text as a fallback) would make the cleanup robust against context rewriting. If identity is deliberately guaranteed here, a short comment stating "context entries are never replaced after firePostReasoning" would help future readers.
|
|
||
| return scope.doCallInner(msgs) | ||
| .onErrorResume(error -> saveStateAfterCallFailure(scope, error)) | ||
| .doOnCancel(() -> cleanupFallbackStructuredOutputContext(scope)) |
There was a problem hiding this comment.
[Warning] doOnCancel mutates scope.state from the cancelling thread. removeStructuredOutputRetryArtifacts() / compressStructuredOutputContext() clear and rebuild the live context list, which is not synchronised and can be concurrently read by the pipeline that is still winding down, and unlike the error path this branch never calls saveStateToSession/saveStateAfterCallFailure, so the in-memory scope can end up cleaned while the stored session snapshot still contains the reminder. Two smaller points:
- Can the cleanup be moved into the same
Mono.defer/doFinallychain that already owns state persistence, so cancel, error and success all mutate the context on the same serialized path? - On cancel, should the cleaned context be persisted at all, or should the session keep the pre-call context (current
saveStateAfterCallFailurebehaviour for errors)?
| options = | ||
| GenerateOptions.mergeOptions( | ||
| GenerateOptions.builder() | ||
| .toolChoice( |
There was a problem hiding this comment.
[Warning] mergeOptions(forcedOptions, options) puts the synthesized options first, and GenerateOptions.mergeOptions lets the primary win field-by-field — so this overrides a user- or hook-provided toolChoice on the retry round. ToolChoice.None is a legitimate setting (some gateways/providers reject forced tool choice, and users set it to disable tool use for a turn); with this change a structured-output retry would flip it back to Specific("generate_response") and the call then fails at the provider instead of giving up gracefully.
Consider only forcing when the effective toolChoice is null/Auto/Required, and leaving None/an explicit Specific untouched (falling through to the give-up path), plus a log.debug when forcing is skipped so the interaction is diagnosable.
| public static final String STRUCTURED_OUTPUT_TOOL_NAME = "generate_response"; | ||
|
|
||
| /** Maximum retries when the model ignores the fallback structured-output tool. */ | ||
| private static final int STRUCTURED_OUTPUT_MAX_RETRIES = 3; |
There was a problem hiding this comment.
[Info] STRUCTURED_OUTPUT_MAX_RETRIES = 3 is a hard-coded constant while the retry strategy is otherwise configurable on the builder (maxIters, model retry/backoff, and the existing StructuredOutputReminder enum in io.agentscope.core.model). Note that after this PR StructuredOutputReminder is only referenced as a metadata string (TOOL_CHOICE.toString()); the PROMPT mode documented as "inject reminder and retry" is now the behaviour actually implemented, but the enum still implies users can pick. Either wire the enum into the builder and honour both modes, or drop/annotate it so the dead option is not advertised in the public API surface. A structuredOutputMaxRetries(int) knob (0 disables) would also let latency-sensitive callers turn the loop off.
| return reasoning(iter + 1, true); | ||
| } | ||
| if (soTool != null && !soCompleted) { | ||
| removeStructuredOutputRetryArtifacts(); |
There was a problem hiding this comment.
[Info] Two different cleanup sites for one code path: the give-up branch here calls removeStructuredOutputRetryArtifacts() only, while doFallbackStructuredCall's else branch additionally calls compressStructuredOutputContext(...) through cleanupFallbackStructuredOutputContext(...). The net effect today is the same (the outer path always runs after this returns), but splitting the invariant across two places makes it easy to break later — e.g. if a future early return bypasses the outer flatMap, reminders stay in context. Would be cleaner to leave all cleanup to cleanupFallbackStructuredOutputContext(scope) and delete this call.
Problem
On the tool-based fallback structured-output path,
ReActAgentrelies on the model voluntarily calling the syntheticgenerate_responsetool. If the model instead returns a normal text answer, the call ends without structured data andgetStructuredData()fails.This regresses the 1.x self-healing behavior, which reminded the model and retried with
tool_choiceforced togenerate_response.Fixes #641
Refs #1103
Fix
ToolChoice.Specific("generate_response")only on those retry rounds.response_format, and ReAct rounds containing business tool calls unchanged.Tests
Added
ReActAgentStructuredOutputRetryTestcovering:generate_responseretry -> structured result;generate_response-> no retry;TDD checks confirmed the retry, usage accounting, error cleanup, and cancellation cleanup regressions fail before their corresponding implementation changes.
Local verification on the rebuilt branch:
mvn -pl agentscope-core -Dtest=ReActAgentStructuredOutputRetryTest testmvn -pl agentscope-core test— 2311 tests, 0 failures, 0 errors, 9 skippedmvn spotless:checkmvn -pl agentscope-core -am verify