Repository navigation
Conversation
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
This comment was marked as abuse.
This comment was marked as abuse.
|
I have signed the CLA,please retry it! |
I have signed the CLA,please retry it! |
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
🤖 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
left a comment
There was a problem hiding this comment.
🤖 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
left a comment
There was a problem hiding this comment.
🤖 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.)
4b1bb86 to
011c7e9
Compare
|
This PR currently conflicts with git fetch upstream
git checkout feat/2240-gemini-thinking-enhancement
git rebase upstream/main
# resolve conflicts, then:
git push --force-with-leaseThis is a one-time reminder. Once the conflicts are resolved, comment Automated notification by github-manager-bot |
d21f5a9 to
b294178
Compare
|
@oss-maintainer please re-review |
oss-maintainer
left a comment
There was a problem hiding this comment.
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— assistantThinkingBlocks are now replayed asPart.text(...).thought(true); need confirmation thatthought=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 withThinkingAccumulator, plus asymmetric null handling inadd(). - [Info]
TextBlock:69— a second metadata contract in the core message model (ToolUseBlockis unmodifiable/non-null, these are mutable/nullable). - [Info]
GeminiChatFormatter:131— option precedence is right;thinkingLevelis unvalidated and now sits on coreGenerateOptions.
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); |
There was a problem hiding this comment.
[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:
- Is
thought=trueaccepted 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. - A signature-only part carries
thinking == ""(seeGeminiResponseParser: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: " |
There was a problem hiding this comment.
[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) { |
There was a problem hiding this comment.
[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(); |
There was a problem hiding this comment.
[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) { |
There was a problem hiding this comment.
[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() { |
There was a problem hiding this comment.
[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) { |
There was a problem hiding this comment.
[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.
7ba8d0c to
87e24f3
Compare
|
Thanks for the thorough review — all findings are addressed in cd9ed3a and 87e24f3:
|
oss-maintainer
left a comment
There was a problem hiding this comment.
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— aThinkingBlockwith an unrestorable signature is still emitted withthought(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 theTextBlockcase. - [Warning]
GeminiMessageConverter.java:134— the same silent-degrade is now pinned as expected forFunctionCallParts, 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— aContentBlockmetadata contract change (null → non-null unmodifiable/empty,NON_NULL→NON_EMPTY) is riding in afeat(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 guaranteebuildAggregated()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()); |
There was a problem hiding this comment.
[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()); |
There was a problem hiding this comment.
[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() |
There was a problem hiding this comment.
[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()) { |
There was a problem hiding this comment.
[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().)
|
Thanks for the thorough review. All four follow-up points are addressed in c5f2deb + ce48de1:
|
oss-maintainer
left a comment
There was a problem hiding this comment.
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
ThinkingBlockwhose signature cannot be restored is no longer emitted as a signature-lessthought(true)Part --applyMetadatareturns whether it restored anything, the converter degrades to an ordinary text Part, andshouldReplayThinkingPartWithCorruptSignatureAsOrdinaryTextPartasserts 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
ContentBlockmetadata contract change is called out both in the Javadoc ofTextBlock/ThinkingBlockand in its own section of the PR description; - the aggregate-view guarantee is written down on both accumulators, and
thinkingLevelis 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-normalizeThinkingLevelwarns fromapplyOptions, 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 thegetMetadata() != nullguards 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( |
There was a problem hiding this comment.
[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) { |
There was a problem hiding this comment.
[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 |
There was a problem hiding this comment.
[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.
|
This PR is git fetch upstream
git rebase upstream/main
# resolve conflicts, then:
git push --force-with-leaseNo further code review is expected unless the conflict resolution changes behaviour — a re-review can be requested with Automated notification by github-manager-bot |
ce48de1 to
2a5aa29
Compare
oss-maintainer
left a comment
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
[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()); |
There was a problem hiding this comment.
[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.
- 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]>
2a5aa29 to
7fe8ec9
Compare
oss-maintainer
left a comment
There was a problem hiding this comment.
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
TextBlocksignature withoutthought(true)— unresolved (assistant text still replays its signature without the thought flag; backend acceptance was not verifiable offline)- Signature-only empty
TextBlockemission — resolved (it is intentionally preserved for replay and covered by an exact wire-format round-trip test) ThinkingBlockmarked thought before unrecoverable signature detection — resolved (an unrecoverable signature now produces an ordinary text Part without either field)- Duplicated
TextAccumulator/ThinkingAccumulatormetadata merge logic — resolved (both useBlockMetadataMerger) 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
includeThoughtstakes precedence, and budget-only callers retain the previousincludeThoughts=truebehavior. - Invalid persisted signatures are skipped; corrupt
ThinkingBlocksignatures replay as ordinary text withoutthoughtorthoughtSignature. - 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
@apiNotetag.
Automated review by github-manager-bot
| if (metadata.isEmpty()) { | ||
| return null; | ||
| } | ||
| if (completedBlocks.isEmpty()) { |
There was a problem hiding this comment.
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()) { |
There was a problem hiding this comment.
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 = |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.parsePartsToBlockskept both sides: this PR'sGeminiThoughtSignatureUtils.extractMetadata(part)feedingThinkingBlock.builder().metadata(...), and main'spendingCodeExecutionId/ToolCallState/ server-tool path. Themetadata != nullcondition on the empty-thinking branch is preserved, which is what keeps signature-only parts replaying.ReasoningContext,ToolUseBlockand 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 | |||
| } | |||
|
|
|||
| /** | |||
There was a problem hiding this comment.
[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.

Background
#2240 — The Gemini model adapter lacked first-class support for Gemini's built-in thinking capability. There were several gaps:
"low", "medium", "high") for the latest models.
ToolUseBlock.METADATA_THOUGHT_SIGNATURE), not on TextBlock or ThinkingBlock. After a JSON serialization round-trip, the byte-array signature was lost or corrupted.
were destroyed, making it impossible to reconstruct distinct signed parts in the next request.
Changes
Core (agentscope-core)
content block types.
and a new one begins. The existing buildAggregated() method continues to return a single merged block for backward compatibility.
Gemini Extension (agentscope-extensions-model-gemini)
preserving existing behavior. When includeThoughts is explicitly set, it always takes precedence.
functionCall Part) via GeminiThoughtSignatureUtils.applyMetadata.
TextBlock.getMetadata()/ThinkingBlock.getMetadata()changed from "nullable, mutable" to "never-null, unmodifiable", matching the existingToolUseBlockcontract:nullwhen unset, mutable map otherwise.Collections.unmodifiableMap.@JsonInclude(NON_EMPTY), so bothnulland empty map serialize away — sessions persisted by earlier builds deserialize exactly as before.getMetadata() == nullwithgetMetadata().isEmpty(); build a copy before mutating.Release note:
TextBlock/ThinkingBlock.getMetadata()now returns an unmodifiable, never-null map (behavior change; serialization unchanged).Documentation
answer / tool call / persistent history replay).