Skip to content

feat(gemini): 支持 Gemini Thinking 并持久化 thought signature - #2335

Open
wzl521 wants to merge 12 commits into
agentscope-ai:mainfrom
wzl521:feat/2240-gemini-thinking-enhancement
Open

wzl521 wants to merge 12 commits into
agentscope-ai:mainfrom
wzl521:feat/2240-gemini-thinking-enhancement

Conversation

@wzl521

@wzl521 wzl521 commented Jul 21, 2026 •

Copy link
Copy Markdown

Background

#2240 — The Gemini model adapter lacked first-class support for Gemini's built-in thinking capability. There were several gaps:

  1. No includeThoughts / thinkingLevel options — GenerateOptions only had thinkingBudget, but Gemini's API requires includeThoughts (to independently control whether thoughts appear in responses) and thinkingLevel (e.g., "minimal",
    "low", "medium", "high") for the latest models.
  2. thoughtSignature was not persisted — Gemini returns an opaque thoughtSignature on each part. This signature must be round-tripped back to Gemini on subsequent turns, but the codebase only captured it on ToolUseBlock (via
    ToolUseBlock.METADATA_THOUGHT_SIGNATURE), not on TextBlock or ThinkingBlock. After a JSON serialization round-trip, the byte-array signature was lost or corrupted.
  3. Part boundaries were lost during accumulation — ThinkingAccumulator and TextAccumulator merged all chunks into a single block. When a Gemini response contained multiple parts each with its own thoughtSignature, the boundaries
    were destroyed, making it impossible to reconstruct distinct signed parts in the next request.

Changes

Core (agentscope-core)

  • GenerateOptions: Added includeThoughts(Boolean) and thinkingLevel(String) options alongside the existing thinkingBudget. These are now properly merged in merge(GenerateOptions, GenerateOptions).
  • ContentBlockMetadataKeys: New constant class with THOUGHT_SIGNATURE key, replacing the ad-hoc constant previously defined on ToolUseBlock. This is the single source of truth for the thought signature metadata key across all
    content block types.
  • TextBlock: Added metadata field (provider-specific Map<String, Object>) with getter and builder support. This enables text blocks to carry thoughtSignature.
  • ThinkingBlock: Already had metadata support; wired into the new signature persistence pipeline.
  • ToolUseBlock: Replaced the local METADATA_THOUGHT_SIGNATURE constant with ContentBlockMetadataKeys.THOUGHT_SIGNATURE reference. No behavioral change.
  • TextAccumulator / ThinkingAccumulator: Introduced buildAllTextBlocks() / buildAllThinkingBlocks() methods that preserve thought-signature Part boundaries. When a chunk carries a thoughtSignature, the current block is completed
    and a new one begins. The existing buildAggregated() method continues to return a single merged block for backward compatibility.
  • ReasoningContext: Switched from buildAggregated() to buildAllXXXBlocks() for both text and thinking, ensuring the final assistant message preserves distinct signed parts.

Gemini Extension (agentscope-extensions-model-gemini)

  • GeminiThoughtSignatureUtils (new): Utility class that:
    • Extracts thoughtSignature from a Gemini Part into content block metadata (as byte[] in memory).
    • Restores a persisted signature back onto a Gemini Part.Builder — supports both byte[] (in-memory) and Base64-encoded String (after JSON serialization).
  • GeminiChatFormatter: Updated applyOptions to build ThinkingConfig from all three fields (thinkingBudget, thinkingLevel, includeThoughts). When only thinkingBudget is set (legacy callers), includeThoughts defaults to true
    preserving existing behavior. When includeThoughts is explicitly set, it always takes precedence.
  • GeminiResponseParser: Refactored parsePartsToBlocks to:
    • Preserve original Part order (no longer reorders thinking → text → toolCall).
    • Attach thoughtSignature metadata to ALL block types (ThinkingBlock, TextBlock, ToolUseBlock) via GeminiThoughtSignatureUtils.extractMetadata.
    • Emit empty blocks when only metadata (signature) is present.
  • GeminiMessageConverter: Updated to restore thoughtSignature from content block metadata onto Gemini Part objects for all assistant-role blocks (ThinkingBlock → Part.thought(true), TextBlock → text Part, ToolUseBlock →
    functionCall Part) via GeminiThoughtSignatureUtils.applyMetadata.

⚠️ Core contract change (call-out)

TextBlock.getMetadata() / ThinkingBlock.getMetadata() changed from "nullable, mutable" to "never-null, unmodifiable", matching the existing ToolUseBlock contract:

  • Before: null when unset, mutable map otherwise.
  • After: always a map (empty when unset), wrapped with Collections.unmodifiableMap.
  • Wire format unchanged: the getters are @JsonInclude(NON_EMPTY), so both null and empty map serialize away — sessions persisted by earlier builds deserialize exactly as before.
  • Migration for out-of-tree callers: replace getMetadata() == null with getMetadata().isEmpty(); build a copy before mutating.

Release note: TextBlock/ThinkingBlock.getMetadata() now returns an unmodifiable, never-null map (behavior change; serialization unchanged).

Documentation

  • docs/v2/en/integration/model/gemini.md: Added "Thinking" section documenting thinkingLevel, includeThoughts, and the signature round-trip behavior.
  • docs/v2/zh/integration/model/gemini.md: Chinese translation.
  • docs/v2/en/integration/model/gemini-request-flow.md (new): Full end-to-end Mermaid diagram of a Gemini request, covering message conversion, thinking config, signature extraction/persistence, and the three completion paths (plain
    answer / tool call / persistent history replay).
  • docs/v2/zh/integration/model/gemini-request-flow.md (new): Chinese translation.

@CLAassistant

CLAassistant commented Jul 21, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@wzl521

wzl521 commented Jul 21, 2026

Copy link
Copy Markdown
Author

@oss-maintainer

This comment was marked as abuse.

@wzl521

wzl521 commented Jul 23, 2026

Copy link
Copy Markdown
Author

I have signed the CLA,please retry it!

@wzl521

wzl521 commented Jul 23, 2026

Copy link
Copy Markdown
Author

CLA Not Signed  尚未签署 CLA 文件

The Contributor License Agreement (CLA) check is currently pending on this PR (license/cla: Contributor License Agreement is not signed yet.). This PR cannot be merged until the CLA is signed.关于《贡献者许可协议》的确认工作目前仍处于待处理状态( license/cla :尚未签署《贡献者许可协议》)。在签署该协议之前,无法合并此拉取请求。

@wzl521 please sign the CLA via the CLA assistant badge in the comment above, or visit https://cla-assistant.io/agentscope-ai/agentscope-java. Once signed, the license/cla status will turn green.请通过上面评论中的 CLA 助手按钮签署 CLA 文件,或者访问 https://cla-assistant.io/agentscope-ai/agentscope-java。一旦签署完成, license/cla 的状态就会变为绿色。

Automated check by github-manager-bot由 github-manager-bot 进行的自动化检查

I have signed the CLA,please retry it!

@AgentScopeJavaBot AgentScopeJavaBot added enhancement New feature or request area/core/agent Agent runtime, pipeline, hooks, plan area/core/model Model providers and formatters area/docs Documentation labels Aug 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

This PR adds Gemini Thinking support with persisted thought signatures across core and Gemini extension modules. Core changes introduce metadata on TextBlock, new ContentBlockMetadataKeys, multi-block accumulation in TextAccumulator/ThinkingAccumulator, and new options in GenerateOptions. Gemini extension adds GeminiThoughtSignatureUtils, updated converters, and comprehensive tests. Overall quality is high — no critical bugs found.

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

@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 adds Gemini Thinking support with persisted thought signatures across core and Gemini extension modules. Core changes introduce metadata on TextBlock, new ContentBlockMetadataKeys, multi-block accumulation in TextAccumulator/ThinkingAccumulator, and new options in GenerateOptions. Gemini extension adds GeminiThoughtSignatureUtils, updated converters, and comprehensive tests. Overall quality is high — no critical bugs found.

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

@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 adds Gemini Thinking support with persisted thought signatures across core and Gemini extension modules. Core changes introduce metadata on TextBlock, new ContentBlockMetadataKeys, multi-block accumulation in TextAccumulator/ThinkingAccumulator, and new options in GenerateOptions. Gemini extension adds GeminiThoughtSignatureUtils, updated converters, and comprehensive tests. Overall quality is high — no critical bugs found.

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

@jujn

jujn commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator
image 两个账号都需要签署CLA。另外,CI有报错,可以看下

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR currently conflicts with main and cannot be merged. Please rebase (or merge main in) and resolve the conflicts:

git fetch upstream
git checkout feat/2240-gemini-thinking-enhancement
git rebase upstream/main
# resolve conflicts, then:
git push --force-with-lease

This is a one-time reminder. Once the conflicts are resolved, comment @oss-maintainer please re-review and I will pick it up again.


Automated notification by github-manager-bot

@wzl521
wzl521 force-pushed the feat/2240-gemini-thinking-enhancement branch from d21f5a9 to b294178 Compare September 22, 2026 05:40
@wzl521

wzl521 commented Sep 22, 2026

Copy link
Copy Markdown
Author

@oss-maintainer please re-review

@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-tested feature work: consolidating the thought-signature metadata key into ContentBlockMetadataKeys, preserving provider Part boundaries through streaming accumulation, and covering the byte[] -> Base64 JSON round trip with real tests. CLA is signed and CI is green on head 7ba8d0c7.

My concerns are concentrated in one place: several paths that used to tolerate a bad or absent signature now fail hard, and some of them affect non-Gemini callers because the change reaches into agentscope-core. Nothing here looks like a design mistake — it is mostly missing wire-shape evidence and a couple of compatibility/strictness decisions I would not want to lock in without an explicit call.

Findings

  • [Critical] GeminiMessageConverter:191 — assistant ThinkingBlocks are now replayed as Part.text(...).thought(true); need confirmation that thought=true (and a signature-only empty-text part) is accepted on the input side.
  • [Warning] GeminiThoughtSignatureUtils:60 — a corrupt persisted signature now aborts the model call where the old converter logged and skipped it.
  • [Warning] GeminiResponseParser:179 — protected parseToolCall(...) signature change breaks out-of-tree subclasses.
  • [Warning] TextAccumulator:71 — buildAggregated() can pair merged text with last-write-wins metadata; still used by the Studio streaming aggregator.
  • [Info] TextAccumulator:150 — ~35 lines duplicated with ThinkingAccumulator, plus asymmetric null handling in add().
  • [Info] TextBlock:69 — a second metadata contract in the core message model (ToolUseBlock is unmodifiable/non-null, these are mutable/nullable).
  • [Info] GeminiChatFormatter:131 — option precedence is right; thinkingLevel is unvalidated and now sits on core GenerateOptions.

Suggestions

The highest-value additions before merge are request-shape assertions: serialize the converted Content and assert the exact JSON for (1) replaying a stored thinking part with a signature, (2) a signature-only empty-text part, and (3) a history entry whose signature is corrupt. Those are exactly where the new strictness meets persisted-state reality, and block-level unit tests cannot see the wire format.

Non-blocking: the PR title and several comments are in Chinese while the code Javadoc and docs are in English — worth aligning the title with the repo convention for changelog readability.


Automated review by github-manager-bot

}

Part.Builder partBuilder =
Part.builder().text(thinkingBlock.getThinking()).thought(true);

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.

[Critical] Assistant ThinkingBlocks used to be skipped on the request path; now every one of them is replayed as Part.text(thinking).thought(true). Two things need confirming before merge:

  1. Is thought=true accepted on an input part by the genai SDK / the Gemini families in scope, or is it response-only metadata the endpoint rejects? If it is rejected, every stored thinking turn becomes a hard request failure — a much larger blast radius than the bug being fixed.
  2. A signature-only part carries thinking == "" (see GeminiResponseParser:144/:164, which deliberately emit empty blocks), so this line can produce {text: "", thought: true, thoughtSignature: ...}. Is an empty text part accepted?

Could you add request-shape assertions (serialize the converted Content and assert the exact JSON) for the non-empty-thinking, signature-only-empty-thinking, and non-assistant-thinking cases? A unit test that stops at the block level cannot show what actually goes on the wire, and this PR changes exactly that.


if (!(value instanceof String encodedSignature)) {
throw new FormatterException(
"Unsupported Gemini thought signature metadata type: "

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 changes the failure semantics for replaying persisted state. Before this PR an undecodable signature was tolerated — the old GeminiMessageConverter caught IllegalArgumentException, logged "Skipping invalid thought signature on tool call ..." and still sent the request. Here a bad value throws FormatterException, so one corrupt entry in agent state aborts the entire model call.

Agent state outlives the code that wrote it (AgentStateStore on MySQL/Redis/OSS, plus hand-edited or partially-migrated rows), so today's "skip and degrade" becomes a permanently broken session. Suggest keeping log-and-drop as the default and making strictness opt-in, or at least documenting the behavior change for store implementations. Note the empty-string case throws too, which is not obviously worse than the no-signature case that applyMetadata silently accepts above it.

*/
protected void parseToolCall(
FunctionCall functionCall, byte[] thoughtSignature, List<ContentBlock> blocks) {
FunctionCall functionCall, Map<String, Object> metadata, List<ContentBlock> blocks) {

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] protected void parseToolCall(FunctionCall, byte[], List<ContentBlock>) becomes parseToolCall(FunctionCall, Map<String, Object>, List<ContentBlock>). That is a breaking change for out-of-tree subclasses: an existing @Override simply stops overriding. GeminiResponseParser is precisely the seam downstream providers extend.

Please keep a @Deprecated byte[] overload delegating to the new form (it can drop the signature into the map), or list the break explicitly in the release notes / migration guide.

@Override
public boolean hasContent() {
return accumulated.length() > 0;
return accumulated.length() > 0 || !metadata.isEmpty();

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] hasContent() now returns true when only metadata is present, so buildAggregated() can emit one block whose text is the concatenation of all parts while its metadata is the last-write-wins merge — i.e. a single thought signature attached to merged text. That pairing is not replay-safe.

The aggregated form is still in use: StreamChatResponseAggregator in agentscope-extensions-studio (lines 96-97) calls textAcc.buildAggregated() / thinkingAcc.buildAggregated(). Since buildAllTextBlocks() is the correct API after this PR, could you either drop signature metadata from buildAggregated() and document it as text-only, or migrate that caller? Otherwise there is a silent mis-attribution waiting for the next aggregated consumer.

* <p>List values are accumulated in stream order (entries appended, not replaced). Scalar
* values use last-write-wins. List values are always copied to prevent caller mutation.
*/
private void mergeMetadata(Map<String, Object> target, Map<String, Object> incoming) {

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] mergeMetadata, completeCurrentBlock and buildCurrentBlock are now duplicated verbatim between TextAccumulator and ThinkingAccumulator (~35 lines), and the two add() methods already differ in null handling — ThinkingAccumulator.add() guards block.getThinking() != null, here block.getText() is appended unguarded. It happens to be safe because TextBlock normalizes null to "", but StringBuilder.append((String) null) writes the literal "null", so the asymmetry is a trap for the next caller that constructs a block differently.

The signature-boundary rule is provider-agnostic and will need the same fix every time. Could you hoist it into one package-private helper (a buffer holding accumulated / currentBlock / both metadata maps) and have both accumulators delegate, with identical null handling?

* @return The metadata map, or null if no metadata is set
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public Map<String, Object> getMetadata() {

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 new accessor follows ThinkingBlock (nullable map, defensive copy on write, mutable map on read), while ToolUseBlock normalizes to Collections.emptyMap() and returns Collections.unmodifiableMap(...). Two different metadata contracts now live in sibling core message types, so consumers must remember which block class needs a null check and which one rejects mutation — and a caller doing block.getMetadata().put(...) gets no compile-time signal.

TextBlock is serialized on every persisted state and every wire transport, so this choice is effectively permanent. I would converge on unmodifiable + one null convention across the three blocks (a follow-up is fine); if the current shape is deliberate, say so in the Javadoc.

thinkingConfigBuilder.includeThoughts(true);
thinkingConfigBuilder.thinkingBudget(thinkingBudget);

if (includeThoughts != null) {

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 precedence looks right — an explicit includeThoughts wins, and legacy thinkingBudget-only callers keep includeThoughts=true — and the new fields are merged correctly in GenerateOptions.mergeOptions.

Two small gaps: thinkingLevel is an unvalidated free-form String on a core builder, so "Minimal" or a stray space is forwarded to the provider and surfaces as an opaque remote error; a trim + allowed-value check (or at least a warning log) would save users a debugging cycle. And since includeThoughts / thinkingLevel now sit on core GenerateOptions, every provider carries them — worth confirming in the Javadoc what a provider that ignores them should do, so the option is not mistaken for framework-wide behavior.

@wzl521
wzl521 force-pushed the feat/2240-gemini-thinking-enhancement branch from 7ba8d0c to 87e24f3 Compare September 23, 2026 03:04
@wzl521

wzl521 commented Sep 23, 2026

Copy link
Copy Markdown
Author

Thanks for the thorough review — all findings are addressed in cd9ed3a and 87e24f3:

  • [Critical] Wire-shape evidence: added GeminiThinkingReplayWireFormatTest, which asserts the exact request JSON via Content.toJson(): (1) a stored thinking Part replays with "thought": true and its thoughtSignature; (2) a
    signature-only empty-text Part survives parse → persist → replay with its signature intact; (3) a history entry with a corrupt signature goes out without the signature and without failing. This matches Google's guidance that thought signatures must be returned verbatim in subsequent requests.
  • [Warning] Corrupt signature: reverted GeminiThoughtSignatureUtils to the original lenient behavior — log a warning and skip, so a bad persisted signature degrades to a missing field instead of aborting the call.
  • [Warning] parseToolCall compat: restored the deprecated byte[] overload as a source-compatible wrapper delegating to the metadata-based variant.
  • [Warning] Aggregate metadata: buildAggregated() now strips the scalar thought signature once a Part boundary was seen — a single signature can't cover the merged text of multiple Parts. The Part-accurate view remains available via buildAllTextBlocks() / buildAllThinkingBlocks().
  • [Info] Duplication & asymmetry: extracted the shared BlockMetadataMerger; TextAccumulator.add() now null-guards text like its Thinking counterpart.
  • [Info] Metadata contract: TextBlock/ThinkingBlock now match ToolUseBlock (empty-map default, unmodifiable, NON_EMPTY serialization so existing JSON is unchanged).
  • [Info] thinkingLevel: documented accepted values (minimal/low/medium/high for Gemini 3) in GenerateOptions; no hard validation since values are provider-specific passthrough.

@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 two commits that landed after my 7ba8d0c7 review (cd9ed3ab tolerate corrupt signatures + wire-format tests, 87e24f3f unify accumulator metadata merging). Both are direct responses to the previous round and they land: mergeMetadata duplication between the two accumulators is gone behind BlockMetadataMerger, the aggregate view no longer mis-attributes one Part's signature to merged multi-Part text, null text chunks no longer append, parseToolCall keeps a deprecated source-compatible overload for out-of-tree subclasses, the thinkingLevel javadoc now states the accepted Gemini 3 values and who validates them, and the new GeminiThinkingReplayWireFormatTest is exactly the request-shape evidence I asked for. CLA signed, CI green, branch mergeable.

One decision still needs defending rather than documenting: leniency now applies at the point where the signature is replayed, which is where Gemini is least forgiving.

Findings

  • [Warning] GeminiMessageConverter.java:193 — a ThinkingBlock with an unrestorable signature is still emitted with thought(true) and no signature; that Part shape is likely rejected server-side, so the tolerant path trades a clear local error for an opaque API failure, and the corrupt-signature test only covers the TextBlock case.
  • [Warning] GeminiMessageConverter.java:134 — the same silent-degrade is now pinned as expected for FunctionCall Parts, which is where the signature carries the reasoning chain; the protocol consequence of a signature-less function call on resume should be stated in docs or surfaced as a distinguishable error.
  • [Info] ThinkingBlock.java:60 — a ContentBlock metadata contract change (null → non-null unmodifiable/empty, NON_NULL → NON_EMPTY) is riding in a feat(gemini) PR; in-tree consumers are all fine, but it belongs in the PR description and release note.
  • [Info] TextAccumulator.java:164 — the aggregate view keeps the signature in the single-Part case and strips it in the multi-Part case; worth stating which guarantee buildAggregated() actually gives.

Inline comments carry the details and the test I would add.

Suggestions

The blocking-adjacent item is the first one: pick a story for "signature could not be restored" on a thinking or function-call Part — replay as plain text, skip the Part, or fail with a provider-visible error — and assert it in the wire-format test. Everything else in this round I would accept as is.

Non-blocking and unchanged from last time: the PR title and several commit messages are still Chinese while the Javadoc and docs are English.


Automated review by github-manager-bot

Part.Builder partBuilder =
Part.builder().text(thinkingBlock.getThinking()).thought(true);
GeminiThoughtSignatureUtils.applyMetadata(
partBuilder, thinkingBlock.getMetadata());

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] Tolerating a corrupt signature is the right call, but for a ThinkingBlock the thought(true) flag is applied at line 191 before applyMetadata decides it has nothing to attach, so the degraded request ships a thought-flagged Part with no signature — the shape the API is most likely to reject, which converts a clear client-side error into an opaque 400 from the model call. If the signature cannot be restored, either drop thought(true) and replay the text as an ordinary Part, or skip the Part; a signature-less thinking Part is not a lesser version of the same request, it is a different (and probably invalid) one. The new shouldDropCorruptSignatureOnReplayWithoutFailing covers only the TextBlock case (where thought is never set), so this specific combination is untested — worth a case that round-trips a ThinkingBlock with a non-Base64 signature and asserts the emitted Part.

}
}
if (modelRole) {
GeminiThoughtSignatureUtils.applyMetadata(partBuilder, tub.getMetadata());

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] Same question for the FunctionCall Part, which is where thoughtSignature actually exists to keep the reasoning chain attached to a tool call: GeminiThoughtSignaturePersistenceTest.testNonBase64SignatureIgnored now pins "signature absent, request still goes out" as the expected behaviour. That is a deliberate protocol decision and I would like to see it justified rather than implied — either a line in the docs stating what Gemini does with a signature-less function call after a persisted session resumes, or, if the call is rejected, a distinguishable error at the seam instead of a log.warn inside a utility class. The previous strict behaviour was wrong (one bad byte array aborting a whole conversation), but the pendulum has swung to silent.

this.metadata = metadata != null ? new HashMap<>(metadata) : null;
this.metadata =
metadata == null
? Collections.emptyMap()

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] This is a core wire-model contract change riding inside a Gemini feature PR: getMetadata() goes from "null when unset" to a non-null Collections.unmodifiableMap(...)/Collections.emptyMap(), and @JsonInclude moves from NON_NULL to NON_EMPTY. Every in-tree consumer I could find stays correct (they all pair the null check with isEmpty(), or degrade to a no-op on a missing key, e.g. OpenAIMessageConverter:340, ReasoningContext:102, ToolCallsAccumulator:88), and the wire format is unaffected because an empty map and a null map both disappear. Two things to make explicit though: out-of-tree code that treats null as the "no metadata" signal now has to use isEmpty(), and callers that mutated the returned map now get UnsupportedOperationException. Since changes to agentscope-core message types cascade to harness, distribution and every extension module, please call this out in the PR description and the release note — right now the title reads feat(gemini) and a reviewer scanning the title would not expect a ContentBlock contract change.

if (metadata.isEmpty()) {
return null;
}
if (completedBlocks.isEmpty()) {

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] Same asymmetry in both accumulators: when no Part boundary was crossed, aggregateMetadata() returns the merged map with its signature (line 165), and only the multi-Part case strips it. That is right for attribution, but it means the aggregate view has two different shapes for the same field depending on chunk framing — a consumer that reads buildAggregated() and assumes "signature present ⇒ this block is one replayable Part" is fine, while one that assumes "signature present ⇒ this is the last thing the model produced" is not, because the single-Part case is also the case where a later chunk can still extend it. One sentence on buildAggregated() saying which of the two guarantees it gives would save the next reader the trace-through. (ReasoningContext uses buildAllTextBlocks()/buildAllThinkingBlocks(), so the replay path itself is unaffected; this is about the Studio aggregator that still calls buildAggregated().)

@wzl521

wzl521 commented Sep 23, 2026

Copy link
Copy Markdown
Author

Thanks for the thorough review. All four follow-up points are addressed in c5f2deb + ce48de1:

  • [Warning] converter:193 — applyMetadata now reports whether the signature was restored. A ThinkingBlock whose signature exists but cannot be restored replays as an ordinary text Part (warn logged) instead of a
    signature-less thought-flagged Part; unsigned thought summaries keep the flag as before. Added the requested wire test (shouldReplayThinkingPartWithCorruptSignatureAsOrdinaryTextPart) asserting the emitted Part carries neither
    thought nor thoughtSignature.
  • [Warning] converter:134 — the lenient drop is now justified in the Gemini docs (en/zh): thinking parts degrade to plain text, while Gemini 3 may reject a function call that lost its thoughtSignature (typically 400) after a
    persisted session resumes — remove or regenerate the affected turn rather than retrying. We kept lenient (vs. hard error) so one bad stored value can't wedge the conversation, but the cost is now explicit rather than implied.
  • [Info] aggregateMetadata — buildAggregated() now states its guarantee on both accumulators: merged text in stream order; scalar signatures kept only in the single-Part case and dropped once Parts were merged;
    replay-accurate views must use buildAllTextBlocks()/buildAllThinkingBlocks().
  • [Info] contract call-out — added the change note to both getters' Javadoc and appended a "Core contract change" section to the PR description for the release note.

@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 three commits after my 87e24f3f review. All four items from that round are addressed, and not by documentation alone:

  • a ThinkingBlock whose signature cannot be restored is no longer emitted as a signature-less thought(true) Part -- applyMetadata returns whether it restored anything, the converter degrades to an ordinary text Part, and shouldReplayThinkingPartWithCorruptSignatureAsOrdinaryTextPart asserts exactly the request shape I asked to see pinned;
  • the function-call consequence is now stated in the en/zh docs (400 on resume, regenerate the turn) instead of being implied by a green unit test;
  • the ContentBlock metadata contract change is called out both in the Javadoc of TextBlock / ThinkingBlock and in its own section of the PR description;
  • the aggregate-view guarantee is written down on both accumulators, and thinkingLevel is now trimmed and case-normalised with unknown values forwarded unchanged on purpose.

So the design question I kept asking -- "pick a story for a lost signature and assert it" -- now has an answer in code, in tests and in docs. What is left is operability of that story rather than its correctness.

Findings

  • [Warning] GeminiMessageConverter.java:210 - the warning that is supposed to tell a user which turn to regenerate carries no agent / session / block coordinates, and repeats per Part per request for the remaining life of a persisted conversation.
  • [Info] GeminiChatFormatter.java:174 - normalizeThinkingLevel warns from applyOptions, i.e. once per request for a static misconfiguration; also make the core Javadoc say that known values are lower-cased while unknown ones are forwarded verbatim.
  • [Info] TextBlock.java:70 - the new contract makes the getMetadata() != null guards in the converters dead; trim them or say why they stay.

CLA / CI

CLA license/cla: signed. CI on ce48de19: green (build ubuntu + windows, Check License, Check Module Sync, codecov/patch). Branch mergeable.


Automated review by github-manager-bot

// A signature existed but could not be restored. A signature-less
// thought Part is a different (likely rejected) request shape, so
// degrade to an ordinary text Part instead of shipping the thought flag.
log.warn(

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 resolves my 87e24f3f finding exactly as I asked: a ThinkingBlock whose signature cannot be restored no longer ships as a signature-less thought(true) Part, applyMetadata now reports whether it restored anything, and shouldReplayThinkingPartWithCorruptSignatureAsOrdinaryTextPart asserts the emitted request shape. The docs half is answered too -- the en/zh pages now state that a function call that lost its signature may be rejected with a 400 and what to do about it.

What is missing is the last step of that remedy. The user-facing instruction is "remove or regenerate the affected turn", but this line is emitted per Part on every replay of every affected conversation and carries no identifier at all -- not the agent name, not the session, not the block index, not the model. In a process running several agents, an operator who sees this warning cannot act on the documented fix without enabling debug logging and bisecting the history. Please include the coordinates that make the turn findable, e.g. "Droping a Gemini thought signature that could not be restored (agent={}, blockIndex={}, textChars={})" -- the enclosing convertMessages has the message list and index at hand.

Second, on the same line: because a signature-less thinking Part degrades to an ordinary text Part, and applyMetadata is also called for text (line 99) and function-call (line 135) Parts whose signatures are dropped with only a warning inside the utility class, a long-lived persisted session that lost signatures stays in this state and warns on every request for the rest of its life. One log line per affected Part per call is going to be a lot of noise for exactly the users who are most likely to ignore it. Consider warning once per conversation replay (or once per distinct signature-loss site) and downgrading the repeats to debug.

* @param thinkingLevel the configured thinking level (non-null)
* @return the normalized level, or null if the value is blank and should be dropped
*/
private String normalizeThinkingLevel(String thinkingLevel) {

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] normalizeThinkingLevel is the right response to my earlier note, and the three new cases (trim/case-normalise, forward unknown unchanged, drop blank) each have a test -- in particular testApplyUnknownThinkingLevelIsForwardedUnchanged documents the choice to stay provider-authoritative rather than hard-reject, which I agree with over validation here.

One thing to align: the blank and unknown branches both log.warn from inside applyOptions, which runs per request. thinkingLevel is a configured value, so a single typo at the builder produces one warning per model call forever, and the message never says which agent or model carries it. A per-instance warn-once, or logging at debug after the first occurrence, keeps it useful. Also worth deciding on purpose: known values are normalised to lower case while unknown ones are forwarded in their original case ("HIGH " -> "high" but "Unspecified" -> "Unspecified"), which is fine given the fallback-to-provider intent -- just make sure the two new sentences in GenerateOptions say that, because right now the core Javadoc reads as though the accepted values are normalised uniformly.

/**
* Gets provider-specific metadata associated with this text block.
*
* <p>The returned map is unmodifiable and never null (matching {@link ToolUseBlock}). Earlier

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 metadata-contract call-out is now in the Javadoc (null to non-null unmodifiable, isEmpty() replaces the null test, mutation requires a local copy) and the PR description has its own Core contract change section, which is what I asked for -- and the same note on ThinkingBlock plus the accumulator guarantee closes the other two items from last round.

One leftover that is cheap while you are in here: the contract paragraph describes a migration for callers, and GeminiMessageConverter still carries thinkingBlock.getMetadata() != null a few files away, which is now dead code under the very contract this Javadoc states. Either trim those redundant null tests in this PR or leave a note that they stay for out-of-tree-constructed blocks; otherwise the next reader cannot tell whether the null case is still reachable.

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR is APPROVED (last review on ce48de19, 2026-09-23) but now conflicts with main — mergeable=CONFLICTING after #3247 (320822d) landed on 2026-09-24, which touches the filesystem specs. Rebase or merge main so this stays mergeable:

git fetch upstream
git rebase upstream/main
# resolve conflicts, then:
git push --force-with-lease

No further code review is expected unless the conflict resolution changes behaviour — a re-review can be requested with @oss-maintainer re-review after the push.


Automated notification by github-manager-bot

@wzl521
wzl521 force-pushed the feat/2240-gemini-thinking-enhancement branch from ce48de1 to 2a5aa29 Compare September 25, 2026 03:27

@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

Re-review after the head moved (ce48de19 → 2a5aa29d); my earlier approval was on the previous head, so this replaces it.

The signature plumbing is a real improvement: one ContentBlockMetadataKeys.THOUGHT_SIGNATURE constant with ToolUseBlock.METADATA_THOUGHT_SIGNATURE kept as an alias (no on-disk key change, so existing persisted sessions still decode), one shared applyMetadata/extractMetadata pair replacing the duplicated byte[]/Base64 decoding, parseToolCall(FunctionCall, byte[], ...) kept @Deprecated for out-of-tree subclasses, and — most importantly — parts are now replayed in wire order instead of the fixed Thinking→Text→ToolUse order, which is what makes multi-turn thinking replay correct for Gemini. The degradation path when a persisted signature cannot be restored (plain text part + warn, instead of shipping a thought: true part with no signature) is the right call, and the test matrix including a wire-format replay test is thorough.

Two protocol-shape concerns are pinned inline: a TextBlock can now get a signature without the thought flag, and an empty TextBlock can now reach the message model for signature-only parts.

Not verified here (no local build): the runtime acceptance of the "signature on a non-thought text part" shape by the Gemini backend — that is why the first inline note is a request to pick one of the two consistent options rather than a statement that it fails.

Head reviewed: 2a5aa29d19. CI at review time: validate / Check License / Check Module Sync green, build (ubuntu-latest) and build (windows-latest) still in progress.


Automated review by github-manager-bot

parts.add(Part.builder().text(tb.getText()).build());
Part.Builder partBuilder = Part.builder().text(tb.getText());
if (modelRole) {
GeminiThoughtSignatureUtils.applyMetadata(partBuilder, tb.getMetadata());

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] Asymmetric with the ThinkingBlock branch below: here applyMetadata can attach a thoughtSignature to a text Part without ever setting thought(true). Per the reasoning you wrote for the ThinkingBlock case — "a signature-less thought Part is a different (likely rejected) request shape" — the converse shape (signature present, thought flag absent) is equally not something the API documents as acceptable, and unlike the ThinkingBlock path there is no hadSignature fallback here. Either set thought(true) whenever this TextBlock carries a restored signature, or drop the signature and replay it as plain text. If a signed summary TextBlock cannot actually be produced by GeminiResponseParser, I'd still prefer the explicit guard over relying on that assumption.

if (text != null && !text.isEmpty()) {
blocks.add(TextBlock.builder().text(text).build());
if (!text.isEmpty() || metadata != null) {
blocks.add(TextBlock.builder().text(text).metadata(metadata).build());

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] !text.isEmpty() || metadata != null now emits a TextBlock with text == "" for a signature-only Part (which is what Gemini returns for a signed empty thought summary ahead of a functionCall). That block is not neutral downstream: it is persisted into agent state, serialized into traces, counted by memory/compaction, and any consumer doing getBlock(0) / strip().isEmpty() on text blocks will see an empty one. Since the signature is already attached to the following ToolUseBlock in the same Part loop, consider keeping the empty-text guard for TextBlock and only relaxing it for ThinkingBlock, or representing the signature-only part as a dedicated non-text carrier.

wzl521 and others added 11 commits September 27, 2026 20:38
- Add ContentBlockMetadataKeys to centralize content block metadata keys
- Use the THOUGHT_SIGNATURE constant in ToolUseBlock instead of a hardcoded string
- Add GeminiThoughtSignatureUtils handling byte[] <-> Base64 signature conversion
- Support ThinkingBlock conversion and thoughtSignature restore in GeminiMessageConverter
- Parse thoughtSignature into ContentBlock metadata in GeminiResponseParser
- Add a metadata field with JSON serialization to TextBlock
- Accumulate metadata in ThinkingAccumulator and TextAccumulator
- Add includeThoughts and thinkingLevel to GenerateOptions
- Build ThinkingConfig field-by-field in GeminiChatFormatter (thinkingBudget / thinkingLevel / includeThoughts)
- Add end-to-end tests verifying signature integrity across streaming accumulation, JSON persistence, and replay
- Update English and Chinese docs

Signed-off-by: wzl <[email protected]>
…rt replay

- End the current Part as soon as metadata carries THOUGHT_SIGNATURE in TextAccumulator and ThinkingAccumulator, keeping signed Parts independent
- Add buildAllTextBlocks() / buildAllThinkingBlocks() returning the multi-Part list in original order
- Update ReasoningContext.buildFinalMessage() to use addAll instead of a single merged block so multiple signed Parts serialize and replay correctly
- Handle empty-text Parts that only carry a signature in GeminiResponseParser, keeping empty thinking/text blocks that have signed metadata
- Add tests covering signature-only Parts, skipping ThinkingBlock in non-assistant messages, Part boundary preservation, Base64 round trips, and invalid signature handling

Signed-off-by: wzl <[email protected]>
- Add frontmatter title to the en/zh gemini-request-flow pages
- Convert the ```{mermaid} Sphinx directive to Mintlify-supported ```mermaid
- Register the new en/zh pages in docs.json navigation

Co-Authored-By: Claude Fable 5 <[email protected]>
Mintlify broken-links checks require page links to use suffix-less absolute
routes; point gemini-request-flow.md at /v2/{en,zh}/integration/model/gemini-request-flow

Co-Authored-By: Claude Fable 5 <[email protected]>
…erges too

The per-Part metadata (currentMetadata) in ThinkingAccumulator and
TextAccumulator previously used putAll, which replaced instead of merged, so
list values such as reasoning details spanning multiple chunks kept only the
last entry and broke the openai StreamingReasoningDetailsReplayTest. Generalize
mergeMetadata into merge(target, source) and apply list-append with
last-write-wins scalars to both the aggregate and per-Part maps.

Co-Authored-By: Claude Fable 5 <[email protected]>
…format tests

Address review feedback:

- Revert signature validation in GeminiThoughtSignatureUtils to lenient
  handling: log a warning and skip unsupported types, empty values, and
  invalid Base64 instead of throwing, so a corrupt persisted signature
  degrades to a missing field instead of aborting the model call.
- Restore the deprecated parseToolCall(FunctionCall, byte[], List) overload
  as a source-compatible wrapper delegating to the metadata-based variant,
  keeping out-of-tree subclasses that override the legacy signature compiling.
- Add GeminiThinkingReplayWireFormatTest asserting the exact request JSON
  via Content.toJson(): thinking Parts replay with thought=true and their
  signature, signature-only empty-text Parts survive persist + replay, and
  a corrupt signature is dropped without failing the request.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tadata contract

Address review feedback:

- Extract the duplicated mergeMetadata logic from TextAccumulator and
  ThinkingAccumulator into a shared BlockMetadataMerger (list-append in
  stream order, last-write-wins scalars, defensive copies).
- Guard TextAccumulator.add() against null text so it stays symmetric with
  ThinkingAccumulator instead of appending the literal "null".
- Drop scalar thought signatures from buildAggregated() once a Part
  boundary was seen: a single signature cannot cover the merged text of
  multiple Parts, so keeping it would mis-attribute it.
- Align TextBlock and ThinkingBlock metadata to the ToolUseBlock contract:
  default to an empty map, expose it unmodifiable, and serialize with
  NON_EMPTY so JSON output is unchanged when no metadata is set.
- Document accepted thinkingLevel values ("minimal"/"low"/"medium"/"high"
  for Gemini 3) in GenerateOptions without hard validation, since values
  are provider-specific and passed through as-is.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ption scoping

Address review feedback on GeminiChatFormatter:

- Trim thinkingLevel and normalize the case of the values Gemini accepts
  ("minimal"/"low"/"medium"/"high"), so " Minimal " or "HIGH" no longer
  surface as opaque remote errors. Blank values are dropped with a warning;
  unknown values are forwarded unchanged after a warning, keeping the
  provider authoritative for newly added levels.
- Clarify in the GenerateOptions Javadoc that includeThoughts and
  thinkingLevel are provider-specific hints: providers that support them
  translate them to their native request type, and providers that do not
  support them silently ignore them.

Co-Authored-By: Claude Fable 5 <[email protected]>
…t replay

Address follow-up review feedback:

- GeminiMessageConverter no longer ships a thought-flagged Part when the
  ThinkingBlock signature cannot be restored: a signature-less thought Part
  is a different (likely rejected) request shape, so the block degrades to
  an ordinary text Part with a warning. Unsigned thought summaries keep the
  thought flag as before. applyMetadata now returns whether a signature was
  restored so callers can degrade accordingly.
- Add a wire-format test for a ThinkingBlock with a non-Base64 signature
  asserting the emitted Part carries neither thought nor thoughtSignature.
- Document in the Gemini docs (en/zh) what lenient signature handling means
  per block type: thinking parts degrade to text, while Gemini 3 may reject
  a function call that lost its signature (typically 400) after a persisted
  session resumes; regenerate the affected turn instead of retrying.
- State the guarantee buildAggregated() gives on both accumulators: merged
  text in stream order, scalar signatures dropped once multiple Parts were
  merged; per-Part replay needs buildAllTextBlocks()/buildAllThinkingBlocks().
- Add @APinote to TextBlock/ThinkingBlock.getMetadata documenting the
  contract change (never-null unmodifiable map) for out-of-tree callers.

Co-Authored-By: Claude Fable 5 <[email protected]>
… note

@APinote is not a recognized tag under the project's javadoc configuration
and broke javadoc:jar on agentscope-core; express the contract-change note
as a normal paragraph instead.

Co-Authored-By: Claude Fable 5 <[email protected]>
The rebase of the thought-signature key change carried unrelated javadoc
re-wrapping and a stray blank line; keep only the intentional constant
change so the diff stays reviewable.

Co-Authored-By: Claude Fable 5 <[email protected]>
@wzl521
wzl521 force-pushed the feat/2240-gemini-thinking-enhancement branch from 2a5aa29 to 7fe8ec9 Compare September 27, 2026 12:59

@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

The new commits normalize Gemini thinking levels, make corrupt thought-signature replay lenient, and replace the unsupported Javadoc tag with ordinary documentation. The signature-only block and corrupt-thinking replay concerns are addressed, while the signed TextBlock wire shape remains unverified. Verdict: request changes, because both aggregate accumulators discard a valid signature for a single completed Part and ThinkingBlock still introduces a breaking metadata getter contract.

Previous round's findings

  • TextBlock signature without thought(true) — unresolved (assistant text still replays its signature without the thought flag; backend acceptance was not verifiable offline)
  • Signature-only empty TextBlock emission — resolved (it is intentionally preserved for replay and covered by an exact wire-format round-trip test)
  • ThinkingBlock marked thought before unrecoverable signature detection — resolved (an unrecoverable signature now produces an ordinary text Part without either field)
  • Duplicated TextAccumulator/ThinkingAccumulator metadata merge logic — resolved (both use BlockMetadataMerger)
  • ThinkingBlock.getMetadata() contract change — partially resolved (migration and JSON omission are documented, but runtime compatibility remains broken)

Findings

  • [Warning] agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/TextAccumulator.java:172 — buildAggregated() drops a valid signature from a single completed Part.
  • [Warning] agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ThinkingAccumulator.java:170 — the equivalent one-Part signature loss exists for thinking content.
  • [Info] agentscope-core/src/main/java/io/agentscope/core/message/ThinkingBlock.java:58 — the public metadata getter remains behaviorally incompatible.

Verified good

  • Known thinking levels are trimmed and lowercased; blank values omit ThinkingConfig, while unknown values are forwarded after trimming.
  • Explicit includeThoughts takes precedence, and budget-only callers retain the previous includeThoughts=true behavior.
  • Invalid persisted signatures are skipped; corrupt ThinkingBlock signatures replay as ordinary text without thought or thoughtSignature.
  • Signature-only empty text Parts survive parser, JSON persistence, and replay in the new wire-format test.
  • The shared metadata merger appends list values in stream order and defensively copies them.
  • The metadata contract note is now plain Javadoc, avoiding the unsupported @apiNote tag.

Automated review by github-manager-bot

if (metadata.isEmpty()) {
return null;
}
if (completedBlocks.isEmpty()) {

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.

completedBlocks becomes non-empty as soon as the first signed provider Part ends, so buildAggregated() drops that Part's still-valid signature. Its aggregate result can therefore no longer replay a single signed Part, contrary to the multiple-Part contract. Track the number of provider Parts and strip thoughtSignature only after more than one Part contributed.

if (metadata.isEmpty()) {
return null;
}
if (completedBlocks.isEmpty()) {

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.

The same boundary check strips thoughtSignature after a single completed thinking Part. A one-Part stream is finalized when its signature arrives, making buildAggregated() lose metadata that remains valid and replayable. Strip the scalar signature only when multiple provider Parts were merged, consistent with TextAccumulator and the documented contract.

@JsonProperty("metadata") Map<String, Object> metadata) {
this.thinking = text != null ? text : "";
this.metadata = metadata != null ? new HashMap<>(metadata) : null;
this.metadata =

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.

This retains a public runtime contract change: unset metadata is now an empty unmodifiable map instead of null or a mutable map. Existing callers can take a different branch or throw UnsupportedOperationException; Javadoc alone does not preserve compatibility. Keep the existing getter contract, introduce a new immutable accessor, or isolate this change to a breaking release.

…tscope-ai#2767)

Integrate upstream server-side tool support with this branch's thinking +
thought-signature persistence:

- GeminiMessageConverter: keep both modelRole signature replay and
  upstream's functionResponseParts queue; ToolUseBlock signatures go
  through GeminiThoughtSignatureUtils.applyMetadata (tolerant of
  empty/corrupt values); upstream's applyThoughtSignature stays for the
  code-execution / server-tool result paths.
- GeminiResponseParser: port upstream's executableCode,
  codeExecutionResult, toolCall and toolResponse handling into the
  metadata-based parsePartsToBlocks flow; byte[] overloads kept as
  deprecated source-compat shims delegating to metadata variants.
- Docs: keep both the Thinking and Server-side tools sections (en/zh).

Co-Authored-By: Claude Fable 5 <[email protected]>

@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

Re-reviewed the new head 7787f090. It is a merge of upstream/main resolving conflicts against the Gemini server-tools work in #2767 — no new author-side logic. I checked the merge rather than assuming it was free:

  • GeminiResponseParser.parsePartsToBlocks kept both sides: this PR's GeminiThoughtSignatureUtils.extractMetadata(part) feeding ThinkingBlock.builder().metadata(...), and main's pendingCodeExecutionId / ToolCallState / server-tool path. The metadata != null condition on the empty-thinking branch is preserved, which is what keeps signature-only parts replaying.
  • ReasoningContext, ToolUseBlock and their tests came through as a union of imports and fields, not a pick-one-side resolution.

So this PR is exactly where it was before the merge — green on CI, mergeable, CLA signed — and the two open findings from my last round are unchanged, not regressed:

  • TextAccumulator.buildAggregated() / ThinkingAccumulator.buildAggregated() still drop a valid signature when a single Part completes the aggregate (agentscope-core/.../accumulator/TextAccumulator.java:172, ThinkingAccumulator.java:170 — both files are byte-identical to the head I reviewed on 2026-09-27).
  • ThinkingBlock.getMetadata() remains a behaviorally incompatible public metadata contract (agentscope-core/.../message/ThinkingBlock.java:58).

Bringing the branch up to date is the right instinct and it costs nothing to keep it that way — rebase or merge once more before merge so the diff stays reviewable against #2767. Addressing the two accumulators above (or explaining why they are intentional in this PR's scope) is what is left; neither needs a redesign, both are the "one completed Part" branch of the aggregate builders.

Not blocking the merge on the merge itself — this round is a verification pass, and it passed.


Automated review by github-manager-bot

@@ -175,8 +176,8 @@ public ChatResponse parseResponse(GenerateContentResponse response, Instant star
}

/**

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] Conflict resolution check for this merge: the signature-metadata path from extractMetadata(part) and the new server-tool / code-execution block handling from #2767 both survived on the same sides of the loop, and the doc comment now describes both. Nothing was dropped here — noting it explicitly because this is one of the two files where the two branches rewrote the same method.

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 area/core/model Model providers and formatters area/docs Documentation enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants