Skip to content

fix(gemini): keep thoughtSignature on replayed tool calls - #668

Merged
yumosx merged 2 commits into
pulseaiclub:mainfrom
noahkhomer18:fix/665-gemini-thought-signature
Nov 26, 2026
Merged

yumosx merged 2 commits into
pulseaiclub:mainfrom
noahkhomer18:fix/665-gemini-thought-signature

Conversation

@noahkhomer18

Copy link
Copy Markdown
Contributor

Closes #665

Problem

Gemini 3+ returns a thoughtSignature beside a signed functionCall part. The adapter dropped it when the response was decoded (part had no field for it), so the next request replayed the call unsigned, and Gemini can reject that with 400 INVALID_ARGUMENT.

Changes

  • gemini.part decodes thoughtSignature and emits it with omitempty, so a request with no signatures is unchanged on the wire.
  • llm.ToolCall gets an optional ThoughtSignature (json:"thought_signature,omitempty"). toLLMToolCall sets it, and toAssistantMessage writes it back on the same functionCall part. Each signature stays on the call it arrived with, so in a parallel batch where only the first call is signed, the others stay unsigned.
  • The OpenAI-compatible adapter marshals llm.ToolCall verbatim (apiMessage.ToolCalls), so toAPIMessage now drops the field before sending. Without that, a session that switches from Gemini to an OpenAI-compatible model would send an unknown field on every replayed call. The session's own copy keeps the signature.

I put it on llm.ToolCall rather than in ProviderState because compaction clears ProviderState on retained messages (agent/session.go), and these signatures have to survive that to keep the retained calls valid.

Tests

Test Covers
TestProcessStreamKeepsThoughtSignaturePerCall stream deltas and the final message keep the signature on the signed call only
TestBuildRequestReplaysThoughtSignature the signature goes back on the same part, exactly once
TestBuildRequestWithoutThoughtSignatureOmitsField no thoughtSignature key when there is none
TestThoughtSignatureSurvivesSessionRoundTrip stream, then JSON save and load as the session does, then rebuild
TestBuildRequestDropsThoughtSignature (openai) the field never reaches the OpenAI wire, and the caller's slice is not mutated

To check the tests catch the bug, I removed each part of the fix in turn and reran them:

Removed Failing tests
signature set in toLLMToolCall ...PerCall, ...SessionRoundTrip
signature written in toAssistantMessage ...ReplaysThoughtSignature, ...SessionRoundTrip
JSON tag on llm.ToolCall (set to -) ...SessionRoundTrip
wireToolCalls in the OpenAI adapter TestBuildRequestDropsThoughtSignature

make check (fmt-check, golangci-lint v2.13.0, deadcode, generate-check) and make test pass.

Not in this PR

  • Signatures on plain text parts. Gemini doesn't enforce those, and the issue is about tool calls.
  • Gemini through its OpenAI-compatible endpoint, which carries the signature in extra_content.google.thought_signature. Happy to follow up if that route is used.

Gemini 3+ returns a thoughtSignature beside each signed functionCall
part and rejects the follow-up request when the replayed call lost it.
Decode it onto llm.ToolCall, persist it with the session, and write it
back on the same functionCall part. The OpenAI-compatible wire marshals
llm.ToolCall verbatim, so it drops the field before sending.

Signed-off-by: Noah Khomer <108771853+noahkhomer18@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • Fixed Gemini 3+ tool-call follow-ups that could fail with 400 INVALID_ARGUMENT errors. Required tool-call information is now retained across responses, streamed calls, and saved conversations.
    • Ensured Gemini tool-call signatures are included where needed for the current turn, without adding placeholder signatures to earlier turns or subsequent parallel calls.
    • Ensured this Gemini-specific information is omitted from OpenAI requests, while preserving the tool call itself.

The change adds optional thought-signature storage to shared tool calls. Gemini conversion preserves signatures across responses, session history, and follow-up requests. OpenAI request conversion removes the field from tool calls.

Changes: Tool-call signature handling

Layer / File(s) Summary
Shared signature field
internal/llm/types.go
ToolCall gains an optional ThoughtSignature field for Gemini signature data.
Gemini signature round trip
internal/llm/gemini/client.go, internal/llm/gemini/client_test.go, CHANGELOG.md
Gemini conversion copies signatures from response function-call parts into tool calls and back onto matching request parts. Request construction assigns the placeholder to the first unsigned function call in the current step. Tests cover parallel calls, previous turns, and session persistence. The changelog documents the behavior.
OpenAI request filtering
internal/llm/openai/client.go, internal/llm/openai/client_test.go
OpenAI request conversion clears thought signatures from a cloned tool-call slice when signatures are present. A test checks that the serialized request omits the field and the original call remains unchanged.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant GeminiResponse
  participant ToolCall
  participant SessionHistory
  participant BuildRequest
  participant GeminiRequest
  GeminiResponse->>ToolCall: Convert function call and thoughtSignature
  ToolCall->>SessionHistory: Store signed tool call
  SessionHistory->>BuildRequest: Supply conversation history
  BuildRequest->>GeminiRequest: Replay signature or add placeholder
Loading

Suggested reviewers: yumosx, mixyang

Merge Risk: Minimal · up to 7806e

This change keeps Gemini thought signatures on replayed tool calls and adds a documented placeholder for unsigned calls in the current turn. It strips the field from OpenAI requests. No actionable merge-blocking risk is evident from the supplied material.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "fix(gemini): keep thoughtSignature on replayed tool calls" names the main change. The changeset stores Gemini thoughtSignature on llm.ToolCall, restores it on the matching functionCall part…
Description check Passed The description states the problem (Gemini 3+ thoughtSignature dropped on decode, causing 400 INVALID_ARGUMENT on replay). It lists the changes across gemini.part, llm.ToolCall, toLLMToolCall, toAssis…
Linked Issues check Passed Directly linked issue #665 requires: (1) decode thoughtSignature from the Gemini response part, (2) keep it on the llm.ToolCall, (3) write it back on the same functionCall part in the next reque…
Out of Scope Changes check Passed All changed areas connect to #665 or to its replay path. part, toLLMToolCall, and toAssistantMessage implement the decode-and-replay requirement. llm.ToolCall.ThoughtSignature in `internal/llm…
Full details: Title check

Explanation

The title "fix(gemini): keep thoughtSignature on replayed tool calls" names the main change. The changeset stores Gemini thoughtSignature on llm.ToolCall, restores it on the matching functionCall part, and adds a placeholder fallback for unsigned current-turn calls. The title covers the primary fix, though it does not mention the placeholder fallback or the OpenAI-compatible adapter change.

Full details: Description check

Explanation

The description states the problem (Gemini 3+ thoughtSignature dropped on decode, causing 400 INVALID_ARGUMENT on replay). It lists the changes across gemini.part, llm.ToolCall, toLLMToolCall, toAssistantMessage, and the OpenAI adapter's toAPIMessage. It also lists tests and out-of-scope items. It matches the changeset closely.

Full details: Linked Issues check

Explanation

Directly linked issue #665 requires: (1) decode thoughtSignature from the Gemini response part, (2) keep it on the llm.ToolCall, (3) write it back on the same functionCall part in the next request, and (4) keep parallel-call signatures on their original calls. The reviewed head (internal/llm/gemini/client.go) implements each one. part.ThoughtSignature (json:"thoughtSignature,omitempty") decodes the field beside functionCall. toLLMToolCall copies p.ThoughtSignature onto each call, so each signature stays with its own call. toAssistantMessage writes tc.ThoughtSignature onto the matching functionCall part only. The llm.ToolCall.ThoughtSignature field carries the value between these steps. Automated tests named in the PR description cover stream retention, replay, omission when absent, and session round trip. I did not read the test bodies. The later commit adds signCurrentTurn, which places the placeholder skip_thought_signature_validator only on unsigned first calls. It does not replace real signatures. This extra behavior does not remove any #665 requirement. Plain-text signatures and the OpenAI-compatible Gemini endpoint are outside #665 and are not required. The current PR description does not mention the placeholder fallback, so the description is stale for this behavior. Live API results in the objectives are author reports and were not verified here.

Full details: Out of Scope Changes check

Explanation

All changed areas connect to #665 or to its replay path. part, toLLMToolCall, and toAssistantMessage implement the decode-and-replay requirement. llm.ToolCall.ThoughtSignature in internal/llm/types.go is the carrier the issue suggests. wireToolCalls in the OpenAI adapter prevents the new field from reaching OpenAI-compatible endpoints after a provider switch. It clones the slice and does not mutate the caller's calls. signCurrentTurn (the later commit) is beyond the literal text of #665. It still addresses the same failure: Gemini 3+ rejects replayed unsigned functionCall steps with 400 INVALID_ARGUMENT. It changes only the built wire request, because toAssistantMessage creates new part values, so session ToolCalls are not modified. It leaves previous turns and later parallel calls unchanged. The CHANGELOG entry documents it. I found no unrelated change. The mismatch with the current PR description is a documentation gap, not an unrelated change.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between bd858aa and 7806eff.

Files selected for processing: 3

  • CHANGELOG.md
  • internal/llm/gemini/client.go
  • internal/llm/gemini/client_test.go
Files skipped from review as they are similar to previous changes: 1

  • CHANGELOG.md

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

libinops

This comment was marked as off-topic.

@libinops libinops left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The core fix is correct: the signature is decoded with its functionCall part, persisted on the tool call, replayed on the same part, and parallel calls don't bleed into each other. It is also stripped before the OpenAI-compatible wire. No issues there.

One gap needs filling before merge: unsigned functionCall parts have no fallback.

Problem

The public Gemini 3 API (https://generativelanguage.googleapis.com/v1beta, phi's default endpoint) requires a signature on every functionCall part. The PR's own fixture [sig-a, bare] is the real shape of a Gemini 3 parallel turn: the second call arrives unsigned. phi replays it bare, and the public API answers 400.

Three paths hit this:

  1. Parallel calls — Gemini 3 signs only the first call of a parallel turn. The rest go back unsigned.
  2. Model switch — switching from another provider to Gemini 3. None of the history has a signature.
  3. Old sessions — sessions saved before this PR already lost their signatures. They stay broken until compaction rotates those messages out.

Suggested fix

In toAssistantMessage (internal/llm/gemini/client.go:264), when tc.ThoughtSignature == "", substitute the bypass sentinel skip_thought_signature_validator that Google documents for Gemini 3. The policy differs by endpoint:

  • Public API: every unsigned call gets the sentinel.
  • Vertex AI (aiplatform.googleapis.com): only when the first call of the turn is unsigned. A signed-first parallel turn leaves secondary calls bare.

getURL (internal/llm/gemini/client.go:291) already tells the two endpoints apart, so the predicate is available. BuildRequest currently has no ModelConfig, so this needs either a parameter or a post-pass in Stream — your call.

Verification

  • Unconfirmed: the public API returns 400 on an unsigned parallel call. To confirm, send one replay with two unsigned calls using a Gemini 3 key.
  • Verified: the PR's core path (decode → persist → replay → strip on non-Gemini wires) is covered by tests and make check.

Consider

Gate replay on same-model signatures. phi currently sends a gemini-3-pro signature to gemini-3-flash after a /model switch. Whether the API rejects a foreign signature is unconfirmed; if it does, this folds into the sentinel fix.

Gemini 3+ rejects a step whose first functionCall has no thoughtSignature.
That happens for history from another provider and for sessions saved
before signatures were kept. Give that call Google's documented
skip_thought_signature_validator placeholder. Later calls of a parallel
step stay bare, as Gemini returns them, and earlier turns are not
validated, so they are left as they are.

Signed-off-by: Noah Khomer <108771853+noahkhomer18@users.noreply.github.com>
@noahkhomer18

Copy link
Copy Markdown
Contributor Author

Thanks @libinops, good catch on the unsigned history. Fixed in 7806eff, with one difference from the suggestion: the placeholder goes only on the first functionCall of each step in the current turn. I checked each case against the live public API (generativelanguage.googleapis.com/v1beta) before deciding.

Parallel calls are accepted bare after a signed first call. I let each model make three parallel get_weather calls (it signed only the first), then replayed the step four ways:

Replayed step gemini-3-flash-preview gemini-3.8-flash gemini-4-neon gemini-2.5-flash
real, bare, bare (what #668 sends) 200 200 200 200
bare, bare, bare 400 400 400 200
placeholder, bare, bare 200 200 200 200
placeholder on all three 200 200 200 200

That matches Google's docs ("only the first functionCall part will contain the thought_signature"; omitting it "for the first functionCall part in any step of the current turn results in a 400"), and the docs read the same for Vertex, so I didn't split the policy by endpoint. Gemini CLI's ensureActiveLoopHasThoughtSignatures also fills the first call only. Placeholders on every call are accepted, but Google calls the placeholder a last resort, and BerriAI/litellm#37541 reports Google's own testing found it on parallel siblings made gemini-3.5 return empty text. So the PR adds it only where the API would otherwise 400.

Your paths 2 and 3 were real. A session switched from another provider builds a step with no signatures at all. I dumped the request phi itself builds for that (two unsigned read calls plus their results) on the previous head and on this one:

Model bd858aa 7806eff
gemini-3-flash-preview 400 "Function call is missing a thought_signature" 200
gemini-3.8-flash 400 200
gemini-4-neon 400 200
gemini-2.5-flash 200 200

Changes

  • signCurrentTurn runs at the end of BuildRequest. It finds the start of the current turn (the last user content that isn't only tool results) and gives the first functionCall of each model step after it skip_thought_signature_validator when it has no signature. Real signatures are never replaced, later parallel calls stay bare, and earlier turns are left as they are since the API doesn't validate them. Only the wire request changes. The session's ToolCalls are not modified.
  • No endpoint split and no ModelConfig needed, since the same rule applies to both endpoints and 2.5 accepts the placeholder.
  • New tests: an unsigned multi-step turn (the first call of each step is signed, the text part and the second parallel call are not), a real signature kept on a parallel step with the session slice unmodified, and previous turns left bare. I replaced my earlier "no signature, no field" test with the previous-turn case, because an unsigned current turn now correctly gets the placeholder.
  • To check the tests bite, I removed each part of the fallback in turn (no fallback, placeholder on every call, placeholder overwriting a real signature, every turn signed): each is caught by at least one test.
  • make check and make test pass. The CHANGELOG entry mentions the placeholder.

On your "Consider": I replayed a gemini-3-flash-preview signature to gemini-4-neon, and a gemini-4-neon one to gemini-3.8-flash. Both returned 200 with the real signature in place, so a /model switch within Gemini doesn't need gating.

@libinops libinops left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thank you very much for your contribution.

@yumosx
yumosx merged commit 5d161dd into pulseaiclub:main Nov 26, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix Gemini thoughtSignature preservation across tool-call turns

3 participants