Skip to content

feat(anthropic): support extended thinking round trips - #2233

Open
dailingtao wants to merge 14 commits into
agentscope-ai:mainfrom
dailingtao:codex/issue-2219-anthropic-thinking
Open

dailingtao wants to merge 14 commits into
agentscope-ai:mainfrom
dailingtao:codex/issue-2219-anthropic-thinking

Conversation

@dailingtao

@dailingtao dailingtao commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.1.0-SNAPSHOT

Description

Fixes #2219.

Validated head: a204cf1f0 (2026-10-24). Interleaved thinking order and manual-thinking structured-output retries are fixed, with 18 additional regression cases. Local clean verify: 99 modules succeeded; 11,344 tests reported, 0 failures, 0 errors, 244 skipped. Documentation tests, validation, and link checks passed.

Anthropic extended-thinking responses contain signed or redacted blocks that must survive history serialization and tool-result continuations. This PR preserves them through JSON and SSE round trips and supports explicit manual/adaptive thinking configuration.

  • Map GenerateOptions.thinkingBudget to manual thinking, rejecting budgets below 1024 locally. An explicit thinking body parameter supports other modes. Per-call thinking configuration replaces the entire default configuration; specifying both forms in one options object fails locally.
  • Store signed and redacted thinking blocks in ThinkingBlock metadata. Accumulate initial thinking content and all signature fragments, emit completed metadata at content_block_stop, and release temporary state. Stream subscriptions keep independent state.
  • Preserve interleaved thinking, text, server-tool calls/results, and local-tool calls through ReasoningContext. Adjacent text/thinking fragments share a segment; tool fragments and result updates retain their original position. No-op middleware text reconciliation preserves segments, while whole-text edits replace superseded text at its first position. Core remains independent of Anthropic.
  • With manual thinking enabled, convert ToolChoice.Specific and ToolChoice.Required to Auto, including automatic structured-output retries. Resolve this against the effective thinking configuration without changing thinking or parallel-tool settings. Disabled/adaptive overrides retain their existing tool-choice behavior.
  • Serialize non-streaming tool input as valid JSON so structured-output argument validation accepts the same payload as the streaming path.
  • Preserve signed assistant content during parallel-tool continuations and group matching client results in one user message. Exclude server tools from client-result matching.
  • Fail explicitly on malformed Anthropic-owned thinking metadata with recovery guidance. Preserve existing unsigned-thinking fallback and prompt-cache usage accounting. Update English and Chinese documentation.

The branch includes main through 07c5f3078; merge conflicts are resolved.

Validation

Local validation on 2026-10-24 for a204cf1f0:

  • Full repository: mvn -B -T1C clean verify
    • All 99 reactor modules succeeded; 11,344 tests reported, 0 failures, 0 errors, 244 skipped.
    • Core: 2,778 tests (9 skipped); Anthropic: 247 tests (1 skipped). Both had 0 failures and 0 errors.
    • Spotless, packaging, sources, and Javadoc checks passed.
  • Focused regressions: mvn -B -T1C -pl agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic -am -Dtest=ReasoningContextTest,ToolCallsAccumulatorTest,ServerToolResultAccumulatorTest,ReActAgentStructuredOutputTest,AnthropicChatModelThinkingRoundTripTest,AnthropicResponseParserTest,AnthropicToolsHelperTest -Dsurefire.failIfNoSpecifiedTests=false test
    • Core: 60 tests (1 skipped); Anthropic: 88 tests. No failures or errors.
    • JSON and SSE HTTP tests compare the complete interleaved content array in the continuation request after ReasoningContext aggregation, including signed and redacted thinking and server-tool results.
    • JSON and SSE tests run a real ReActAgent.call(..., Weather.class) through an initial plain-text answer and a successful structured-output retry, asserting unchanged thinking configuration and compatible tool choice.
    • Configuration cases cover default/per-call manual thinking, explicit enabled thinking, disabled/adaptive overrides, and parallel-tool settings. Core regressions cover fragment/result updates, per-segment thinking metadata, and middleware text replacement.
    • HTTP fixtures use the Anthropic SDK and local MockWebServer without cloud credentials.
  • Documentation, from docs/: npm test (13 passed), npm run validate, and npm run broken-links all passed.
  • git diff --check passed.

Skipped tests remain subject to the repository's existing disabled-test and external-service conditions. These are local results; GitHub Actions results are reported separately by the PR checks.

Checklist

  • Code formatting verified by Spotless during clean verify
  • All relevant tests are passing
  • Javadoc generation passed
  • Related English and Chinese documentation has been updated
  • Code is ready for review

@codecov

codecov Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

@AgentScopeJavaBot AgentScopeJavaBot added enhancement New feature or request area/core/model Model providers and formatters area/ext/integration External protocols & middleware integrations labels Jul 16, 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

Aspect Count
🟢 Nitpick (信息性建议,不阻塞合并) 3
🟡 Recommended (建议修复,但不阻塞合并) 2

Overall Assessment: COMMENT — Well-designed extended thinking round-trip support; two defensive-programming improvements recommended before merge.

@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

Aspect Count
🟢 Nitpick (信息性建议,不阻塞合并) 3
🟡 Recommended (建议修复,但不阻塞合并) 2

Overall Assessment: COMMENT — Well-designed extended thinking round-trip support; two defensive-programming improvements recommended before merge.

@dailingtao

Copy link
Copy Markdown
Contributor Author

Hi @jujn, it looks like AgentScopeJavaBot may be stuck on this PR.

The bot submitted the same review summary twice for commit d7f6dea4,
reporting 3 nitpicks and 2 recommendations, but no inline comments or
review threads were created, so I couldn't see the specific findings.

The latest head is now 1bcd3d7c, and the new review request is still
pending. I also don't have permission to re-request reviewers.

Could you please help re-trigger the AI review or check whether the bot
service is working correctly?

All current CI checks are passing. Thanks!

@jujn

jujn commented Jul 18, 2026

Copy link
Copy Markdown
Collaborator

Thanks for your contribution. I'll review it later when I have time.

@dailingtao dailingtao closed this Aug 22, 2026
@jujn jujn reopened this Aug 22, 2026
@jujn

jujn commented Aug 22, 2026

Copy link
Copy Markdown
Collaborator

为什么关闭了?因为PR比较大,之前一直抽不出完整的时间去审。预计 2.0.4 会合入

@jujn jujn self-assigned this Aug 22, 2026
@dailingtao

Copy link
Copy Markdown
Contributor Author

为什么关闭了?因为PR比较大,之前一直抽不出完整的时间去审。预计 2.0.4 会合入

好的 thanks ,以为不合入了 看到dingding群里的一个哥们说 可以抽空把自己没合入的PR 清一下 减小review的压力

…ropic-thinking

# Conflicts:
#	agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic/src/main/java/io/agentscope/extensions/model/anthropic/formatter/AnthropicResponseParser.java
#	agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic/src/test/java/io/agentscope/extensions/model/anthropic/formatter/AnthropicResponseParserTest.java
@oss-maintainer

This comment was marked as abuse.

@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

Solid, well-scoped feature work: the Anthropic-specific signed/redacted thinking payload is kept out of the generic message model by parking it in ThinkingBlock metadata under indexed keys, ordering is recovered via the numeric index, and the round-trip is covered by an SDK + MockWebServer test rather than a mocked unit test — which is the right level for this bug class. The refactor of StreamUsageState into StreamState also keeps the prompt-caching token accounting intact. I have four concerns, all about failure modes rather than the design.

Findings

  • [Warning] AnthropicMessageConverter.java:205 — hasNativeThinkingBlocks calls toContentBlockParams, which throws on malformed metadata; with the same throw inside convertMessageContent, one corrupted anthropicThinkingBlock:* entry in history fails every later request on that session (metadata persists with the conversation), so the session cannot recover.
  • [Info] AnthropicMessageConverter.java:207 — the probe re-parses every Anthropic-owned thinking payload and the same work is repeated in convertMessageContent; a key-presence check (or converting once and reusing) avoids duplicated parsing/allocation on long histories.
  • [Warning] AnthropicResponseParser.java:230 — StreamState.thinkingByIndex is a plain HashMap mutated from the reactive map operator and never pruned on content_block_stop: the full thinking text is retained for the rest of the stream, and the correctness of the emitted signature depends on signature_delta always arriving after every thinking_delta for that index.
  • [Info] AnthropicToolsHelper.java:275 — thinkingBudget is forwarded to enabledThinking(...) without the provider's own constraints (budget_tokens >= 1024, budget_tokens < max_tokens), so misconfiguration surfaces as an opaque upstream 400.

Suggestions

// AnthropicMessageConverter: cheap presence check instead of a throwing parse
private boolean hasNativeThinkingBlocks(Msg msg) {
    return msg.getContentBlocks(ThinkingBlock.class).stream()
            .anyMatch(AnthropicThinkingMetadata::hasAnthropicBlock);
}
  • Consider logging and skipping an unreadable Anthropic-owned entry during history conversion (hard failure only for a block produced in the current turn), or exposing an explicit validation entry point so a persisted conversation cannot become unsendable.
  • content_block_stop is a natural place to drop thinkingByIndex once the signature has been emitted, and an ConcurrentHashMap/documentation of single-subscriber confinement would make the threading contract explicit. A test for a signature_delta arriving before any thinking_delta for the same index would pin the assumption down.
  • For thinkingBudget, either pre-check against maxTokens/1024 locally with an actionable message, or document that the value is passed through unvalidated.

Two more questions worth answering before merge:

  1. applyThinking picks options when it has any thinking config, otherwise defaultOptions. If per-call options set an explicit thinking body param while defaults set thinkingBudget, the default budget is dropped silently — intended?
  2. convertParallelToolCallsWithThinking maps ToolUseBlock.id -> resultsById.get(id) without re-checking shouldSplitParallelToolCalls, unlike the non-thinking branch. Is the guarantee enforced at the call site for every path that reaches this branch? A defensive Objects.requireNonNull-style check (or a test for the missing-result case) would keep it honest.

Nice detail: rejecting malformed Anthropic owned metadata instead of silently downgrading it to plain text, and keeping the text fallback for non-Anthropic thinking blocks.


Automated review by github-manager-bot

return msg.getContent().stream().anyMatch(block -> !(block instanceof ToolResultBlock));
}

private boolean hasNativeThinkingBlocks(Msg 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] This validity probe runs toContentBlockParams(...), which can throw IllegalArgumentException on malformed Anthropic-owned metadata. Combined with the same throw inside convertMessageContent, a single corrupted/foreign anthropicThinkingBlock:* entry in history makes every subsequent request on that session fail (metadata persists with the conversation), with no way for the caller to recover.

Could the strict check be scoped to the block that is actually being sent — e.g. skip/pass-through entries that fail validation and emit a warning log, reserving the hard failure for a validation entry point the caller invokes once — so history conversion degrades gracefully instead of bricking the session?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated in 3f9f406. The presence probe now uses AnthropicThinkingMetadata.hasNativeBlocks, which only checks owned metadata keys and cannot fail by parsing their payloads. Validation happens when the block is actually converted.

Strict validation remains for malformed Anthropic-owned signed/redacted blocks: Anthropic requires these blocks to be returned complete and unmodified, so skipping a damaged block or converting it to text would not repair the signed tool-use history. The exception now identifies the affected content index/key and gives recovery instructions: restore the original signed block, or remove the affected turn together with its tool results. This behavior is documented in both languages and covered by testRejectsMalformedAnthropicThinkingMetadata; unrelated/unsigned thinking keeps its existing text fallback.


private boolean hasNativeThinkingBlocks(Msg msg) {
return msg.getContentBlocks(ThinkingBlock.class).stream()
.anyMatch(

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 anyMatch predicate re-parses every Anthropic-owned thinking payload to decide "is there a native block?", and the same work is repeated later in convertMessageContent for the same message. For long histories with big signed thinking blobs this is redundant CPU plus allocation. Either extract List<ContentBlockParam> once per ThinkingBlock and reuse it, or gate on a cheap key-presence check (metadata.keySet().stream().anyMatch(k -> k.startsWith("anthropicThinkingBlock:"))) and let the real conversion do validation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 3f9f406. hasNativeThinkingBlocks now calls AnthropicThinkingMetadata.hasNativeBlocks, a cheap prefix/key-presence check. The payload is parsed and validated only during convertMessageContent, removing the duplicate conversion/allocation. The signed-thinking history and parallel-tool round-trip tests pass on the latest head, a204cf1.

deltaEvent.index(),
streamState.getThinking(
deltaEvent.index()),
signatureDelta.signature()))

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] StreamState.thinkingByIndex is a plain HashMap mutated from the reactive map operator and never cleared on content_block_stop. Two consequences worth confirming:

  1. Memory: the accumulated reasoning text per index is retained for the whole stream lifetime (even after the block is finished), which for long agentic streams duplicates the full thinking text in heap alongside the emitted blocks.
  2. Ordering: signature_delta is assumed to always arrive after every thinking_delta for that index. If Anthropic ever emits a signature first (or a redacted/thinking block reuses an index), getThinking(index) yields an empty/partial string and the stored signature becomes unusable for the round trip — silently, because the metadata looks valid.

Consider ConcurrentHashMap (or documenting/confining the state to the single subscriber), removing the entry once the signature has been emitted, and adding an explicit test for a signature_delta that arrives before any thinking_delta for that index.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 3f9f406. Thinking text and all signature fragments are accumulated until content_block_stop; the complete signed block is emitted there and its thinkingByIndex entry is removed. This also handles a signature delta arriving before the first thinking delta, and preserves nonempty start content/signatures.

Flux.defer creates a separate StreamState per subscription; the code documents that upstream signals are serialized, so the map is confined to that subscriber. testThinkingStartContentAndSignatureFragmentsArePreservedAtBlockStop covers early/fragmented signatures and repeated subscriptions; testThinkingStateIsReleasedAfterBlockStop covers cleanup. Both pass on a204cf1.

}

if (thinkingBudget != null) {
builder.enabledThinking(thinkingBudget);

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] Manual thinking is forwarded as builder.enabledThinking(thinkingBudget) without validating the provider constraints (Anthropic requires budget_tokens >= 1024 and budget_tokens < max_tokens). A too-small budget or a thinkingBudget >= maxTokens currently surfaces as an opaque 400 from the API. A local pre-check with a clear message — or at least a note in the javadoc/docs — would make misconfiguration easier to diagnose.

Also, in applyThinking, when defaultOptions supplies the thinking body param the value is forwarded verbatim; please confirm the continue in applyAdditionalBodyParams means the per-call additionalBodyParams can never partially overwrite the default thinking object (merged rather than replaced), since the docs describe the opposite expectation for other options.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 3f9f406 and a204cf1. A manual budget below 1024 now fails locally with a clear error. The EN/ZH docs explain that ordinary manual thinking requires maxTokens above the budget; the upper-bound relationship remains API/model-dependent because interleaved thinking can allow a budget above maxTokens.

Whole-object replacement is intentional: a per-call explicit thinking object replaces a default thinkingBudget, and a per-call budget replaces a default explicit object. applyThinking selects one source, while the generic additional-body pass skips thinking, so the default object cannot partially overwrite the selected one. Tests cover both directions, enabled/disabled/adaptive overrides, conflicting configuration, and the minimum budget. Tool-choice compatibility now uses the same effective source, so a disabled/adaptive override does not accidentally inherit the default manual-thinking restriction.

@mintlify

mintlify Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit a204cf1.

Approve preview

Keep reasoning content in arrival order while accumulating tool fragments and
server-result updates in their original positions. Preserve unchanged text
segments during middleware reconciliation.

Resolve tool choice against the effective thinking configuration and use auto
for forced choices with manual thinking. Serialize non-streaming tool input as
JSON so structured-output validation receives valid arguments.

Add JSON/SSE round-trip, structured-output retry, option precedence, and core
accumulation regressions, and update both language versions of the docs.
@dailingtao

Copy link
Copy Markdown
Contributor Author

@oss-maintainer The branch is updated at a204cf1f0. I merged main through 07c5f3078 and resolved the conflicts; GitHub now reports the branch as mergeable.

I have replied to all four inline review threads with the implementation and test details:

To answer the additional parallel-tool question in the review summary: both signed and unsigned branches are entered only after shouldSplitParallelToolCalls confirms that every client tool ID has a result. The signed branch now uses the same clientToolUses set as that guard, so server-tool IDs are excluded from result lookup. testSignedThinkingWithServerToolsAndParallelClientTools covers the mixed case.

The follow-up review also found and fixed content reordering through ReasoningContext and incompatible forced tool choice during manual-thinking structured-output retries. JSON/SSE end-to-end tests now cover both, including successful typed structured output. The latter exposed a non-streaming tool-input serialization issue, which is also fixed.

Local validation on this head:

  • mvn -B -T1C clean verify: all 99 modules succeeded; 11,344 tests reported, 0 failures, 0 errors, 244 skipped under existing test conditions.
  • Core: 2,778 tests (9 skipped); Anthropic: 247 tests (1 skipped). Both had 0 failures/errors.
  • Documentation: 13 tests passed; build validation and broken-link checks passed.
  • 18 additional regression cases; independent follow-up review found no further actionable issues.

The PR description contains the updated scope and detailed test commands. GitHub's license, module-sync, and documentation validation checks have passed; Windows/Ubuntu builds were still running when checked. Thanks for taking another look.

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/model Model providers and formatters area/ext/integration External protocols & middleware integrations enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Anthropic 推理增强

4 participants