Repository navigation
feat(anthropic): support extended thinking round trips - #2233
dailingtao wants to merge 14 commits into
Conversation
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
🤖 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
left a comment
There was a problem hiding this comment.
🤖 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.
|
Hi @jujn, it looks like AgentScopeJavaBot may be stuck on this PR. The bot submitted the same review summary twice for commit The latest head is now Could you please help re-trigger the AI review or check whether the bot All current CI checks are passing. Thanks! |
|
Thanks for your contribution. I'll review it later when I have time. |
|
为什么关闭了?因为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
This comment was marked as abuse.
This comment was marked as abuse.
oss-maintainer
left a comment
There was a problem hiding this comment.
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—hasNativeThinkingBlockscallstoContentBlockParams, which throws on malformed metadata; with the same throw insideconvertMessageContent, one corruptedanthropicThinkingBlock:*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 inconvertMessageContent; a key-presence check (or converting once and reusing) avoids duplicated parsing/allocation on long histories. - [Warning]
AnthropicResponseParser.java:230—StreamState.thinkingByIndexis a plainHashMapmutated from the reactivemapoperator and never pruned oncontent_block_stop: the full thinking text is retained for the rest of the stream, and the correctness of the emitted signature depends onsignature_deltaalways arriving after everythinking_deltafor that index. - [Info]
AnthropicToolsHelper.java:275—thinkingBudgetis forwarded toenabledThinking(...)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_stopis a natural place to dropthinkingByIndexonce the signature has been emitted, and anConcurrentHashMap/documentation of single-subscriber confinement would make the threading contract explicit. A test for asignature_deltaarriving before anythinking_deltafor the same index would pin the assumption down.- For
thinkingBudget, either pre-check againstmaxTokens/1024 locally with an actionable message, or document that the value is passed through unvalidated.
Two more questions worth answering before merge:
applyThinkingpicksoptionswhen it has any thinking config, otherwisedefaultOptions. If per-call options set an explicitthinkingbody param while defaults setthinkingBudget, the default budget is dropped silently — intended?convertParallelToolCallsWithThinkingmapsToolUseBlock.id -> resultsById.get(id)without re-checkingshouldSplitParallelToolCalls, unlike the non-thinking branch. Is the guarantee enforced at the call site for every path that reaches this branch? A defensiveObjects.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) { |
There was a problem hiding this comment.
[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?
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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())) |
There was a problem hiding this comment.
[Warning] StreamState.thinkingByIndex is a plain HashMap mutated from the reactive map operator and never cleared on content_block_stop. Two consequences worth confirming:
- 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.
- Ordering:
signature_deltais assumed to always arrive after everythinking_deltafor 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.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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.
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
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.
|
@oss-maintainer The branch is updated at 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 The follow-up review also found and fixed content reordering through Local validation on this head:
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. |
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. Localclean 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.
GenerateOptions.thinkingBudgetto manual thinking, rejecting budgets below 1024 locally. An explicitthinkingbody parameter supports other modes. Per-call thinking configuration replaces the entire default configuration; specifying both forms in one options object fails locally.ThinkingBlockmetadata. Accumulate initial thinking content and all signature fragments, emit completed metadata atcontent_block_stop, and release temporary state. Stream subscriptions keep independent state.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.ToolChoice.SpecificandToolChoice.RequiredtoAuto, 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.The branch includes
mainthrough07c5f3078; merge conflicts are resolved.Validation
Local validation on 2026-10-24 for
a204cf1f0:mvn -B -T1C clean verifymvn -B -T1C -pl agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic -am -Dtest=ReasoningContextTest,ToolCallsAccumulatorTest,ServerToolResultAccumulatorTest,ReActAgentStructuredOutputTest,AnthropicChatModelThinkingRoundTripTest,AnthropicResponseParserTest,AnthropicToolsHelperTest -Dsurefire.failIfNoSpecifiedTests=false testReasoningContextaggregation, including signed and redacted thinking and server-tool results.ReActAgent.call(..., Weather.class)through an initial plain-text answer and a successful structured-output retry, asserting unchanged thinking configuration and compatible tool choice.docs/:npm test(13 passed),npm run validate, andnpm run broken-linksall passed.git diff --checkpassed.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
clean verify