Skip to content

fix(agent): restore structured-output self-healing retry in fallback path - #2047

Open
zhangliyuangit wants to merge 2 commits into
agentscope-ai:mainfrom
zhangliyuangit:fix/structured-output-fallback-retry
Open

zhangliyuangit wants to merge 2 commits into
agentscope-ai:mainfrom
zhangliyuangit:fix/structured-output-fallback-retry

Conversation

@zhangliyuangit

@zhangliyuangit zhangliyuangit commented Jul 8, 2026 •

Copy link
Copy Markdown

Problem

On the tool-based fallback structured-output path, ReActAgent relies on the model voluntarily calling the synthetic generate_response tool. If the model instead returns a normal text answer, the call ends without structured data and getStructuredData() fails.

This regresses the 1.x self-healing behavior, which reminded the model and retried with tool_choice forced to generate_response.

Fixes #641
Refs #1103

Fix

  • Retry a finished, tool-free fallback structured-output response up to 3 times.
  • Tag each retry with the existing structured-output reminder metadata and force ToolChoice.Specific("generate_response") only on those retry rounds.
  • Leave ordinary calls, native response_format, and ReAct rounds containing business tool calls unchanged.
  • Remove internal reminders and intermediate retry answers from persisted context on both success and give-up; the final structured result or final plain-text answer remains.

Tests

Added ReActAgentStructuredOutputRetryTest covering:

  • plain text -> forced generate_response retry -> structured result;
  • refusal through the retry limit -> exactly 1 initial call + 3 retries, then plain text;
  • voluntary first-round generate_response -> no retry;
  • no reminder or intermediate-answer leakage into a follow-up turn;
  • retry errors and Reactor cancellation also clean internal retry artifacts;
  • returned usage includes every model attempt, including discarded retry answers.

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 test
  • mvn -pl agentscope-core test — 2311 tests, 0 failures, 0 errors, 9 skipped
  • mvn spotless:check
  • mvn -pl agentscope-core -am verify

Copilot AI 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.

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 ReActAgentStructuredOutputRetryTest covering 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.

Comment on lines +2121 to +2123
state.contextMutable()
.add(createStructuredOutputReminder());
return reasoning(iter + 1, true);

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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);

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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.)

Comment on lines +3333 to +3336
return Msg.builder()
.name("system")
.role(MsgRole.USER)
.content(

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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.

Comment on lines +3362 to +3367
return metadata != null
&& StructuredOutputReminder.TOOL_CHOICE
.toString()
.equals(
metadata.get(
MessageMetadataKeys.STRUCTURED_OUTPUT_REMINDER_TYPE));

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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.)

@oss-maintainer

This comment was marked as abuse.

@AgentScopeJavaBot AgentScopeJavaBot added bug Something isn't working area/core/agent Agent runtime, pipeline, hooks, plan labels Jul 11, 2026

@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

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 —

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.

[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.

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.

✅ 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.

@zhangliyuangit
zhangliyuangit force-pushed the fix/structured-output-fallback-retry branch from e5d2b4a to 73d0e4c Compare July 12, 2026 12:56
@CLAassistant

CLAassistant commented Jul 12, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@zhangliyuangit
zhangliyuangit force-pushed the fix/structured-output-fallback-retry branch from 73d0e4c to a4457cb Compare July 12, 2026 12:58
@zhangliyuangit

Copy link
Copy Markdown
Author

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

All previously raised review comments have been addressed.

@zhangliyuangit
zhangliyuangit force-pushed the fix/structured-output-fallback-retry branch from 465b455 to 013d879 Compare August 30, 2026 09:34
@zhangliyuangit

Copy link
Copy Markdown
Author

Rebuilt this PR on the latest main with a clean two-commit history.

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: agentscope-core 2311 tests (0 failures, 0 errors, 9 skipped), Spotless, and mvn -pl agentscope-core -am verify. The previous review feedback is preserved.

@oss-maintainer, could you please take another look when convenient?

@zhangliyuangit
zhangliyuangit force-pushed the fix/structured-output-fallback-retry branch from 013d879 to 5e8674f Compare August 30, 2026 09:36

@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

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 / InboxMiddleware append 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 — doOnCancel mutates the shared context off the serialized pipeline and never persists the cleaned state, unlike the error path.
  • [Warning] ReActAgent.java:2347 — forced options win in mergeOptions, overriding a user/hook-provided ToolChoice.None; restrict forcing and log skips.
  • [Info] ReActAgent.java:227 — retry count is hard-coded and StructuredOutputReminder is 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

  1. Does agent.call(msgs, Class) on the fallback path have any existing e2e/integration coverage on a real provider (DashScope/OpenAI compatible) confirming providers accept tool_choice pointing at a tool that is injected per-call and is not in the shared toolkit schema list? Some providers validate tool_choice against tools[].
  2. Should a give-up after 3 retries surface anything to the caller (event/log at WARN, or a GenerateReason marker on the returned message)? Today it returns plain text with only a log.debug, which is hard to distinguish from "the model legitimately answered in prose" when debugging user reports.
  3. The PR description says reminders are removed "on both success and give-up" — is the multi-turn case intended (a later agent.call in 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())) {

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] 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);

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] 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))

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] 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:

  1. Can the cleanup be moved into the same Mono.defer/doFinally chain that already owns state persistence, so cancel, error and success all mutate the context on the same serialized path?
  2. On cancel, should the cleaned context be persisted at all, or should the session keep the pre-call context (current saveStateAfterCallFailure behaviour for errors)?

options =
GenerateOptions.mergeOptions(
GenerateOptions.builder()
.toolChoice(

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] 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;

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] 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();

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] 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.

This branch has not been deployed

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

Labels

area/core/agent Agent runtime, pipeline, hooks, plan bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]:在结构化输出时,总是输出失败,提示报错信息为No structured output in message metadata. Key '_structured_output' not found

5 participants