Skip to content

Gemini 3: round-trip thoughtSignature on functionCall parts - #154

Merged
FMXExpress merged 2 commits into
mainfrom
claude/gemini-thought-signature
Jun 6, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/gemini-thought-signature

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

The 400 this fixes

After PR #153's schema scrub landed, gemini-3.5-flash returns a new 400 on the second turn of any tool-using session:

Function call is missing a thought_signature in functionCall parts.
This is required for tools to work correctly, and missing
thought_signature may lead to degraded model performance.
Additional data, function call `default_api:fs_list`, position 2.

Ref: https://ai.google.dev/gemini-api/docs/thought-signatures

Gemini 3+ requires the client to echo back an opaque thoughtSignature blob the model returns on each functionCall part. The signature encodes the model's internal reasoning state; if we drop it, Gemini 3 rejects the next request. Gemini 2.x doesn't require it.

Wire shape

// Assistant turn the model returned:
{
  "role": "model",
  "parts": [{
    "functionCall": {"name": "fs_list", "args": {"path":"."}},
    "thoughtSignature": "<opaque blob A>"
  }]
}

// Follow-up request MUST echo the signature verbatim:
{
  "role": "model",
  "parts": [{
    "functionCall": {"name": "fs_list", "args": {"path":"."}},
    "thoughtSignature": "<opaque blob A>"   // mandatory on Gemini 3
  }]
}

Implementation

  • TToolCall.ProviderSignature — new opaque string field on the shared TToolCall record (PasClaw.Providers.Types). Provider-specific blob; empty for everything except Gemini 3+. Survives session save/load because it lives on the TToolCall the gateway already serialises.
  • PasClaw.Providers.Gemini.ParseResponse — reads the part-level thoughtSignature (sibling of functionCall, not inside it) and stashes it on the parsed TToolCall.
  • PasClaw.Providers.Gemini.BuildRequest — when emitting the assistant turn's part, writes thoughtSignature as a sibling of functionCall when ProviderSignature is non-empty. Empty signature stays silent — no empty "":"" field on the wire (would be invalid).

Test plan

Two cases added to make test-gemini-schema-strip:

  • TestThoughtSignatureRoundTrip — ProviderSignature = 'SIG_AAA_BBB_OPAQUE_BLOB' survives unmodified onto the wire; functionCall + name + args also preserved.
  • TestNoSignatureWhenEmpty — empty signature ⇒ no thoughtSignature key at all (so Gemini 2.x stays happy).
  • make smoke — all 11 commands OK
  • make — clean Linux+FPC build
  • Live exercise on gemini-3.5-flash with pasclaw agent -m "list pwd" — the 400 from PR Gemini: strip JSON-Schema fields the API rejects + bump default to 3.5-flash #153's follow-up should be gone.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

The 400 the user hit on gemini-3.5-flash after PR #153's schema scrub
landed:

  Function call is missing a thought_signature in functionCall parts.
  This is required for tools to work correctly, and missing
  thought_signature may lead to degraded model performance.
  Additional data, function call \`default_api:fs_list\`, position 2.

Gemini 3+ requires the client to echo back an opaque
\`thoughtSignature\` blob that the model returns on each functionCall
part. The signature encodes the model's internal reasoning state; if
we drop it, Gemini 3 rejects the next request with a 400. Gemini 2.x
doesn't require it. Ref:
  https://ai.google.dev/gemini-api/docs/thought-signatures

Wire shape (Gemini 3):

  // Assistant turn the model returned:
  {
    "role": "model",
    "parts": [{
      "functionCall": {"name": "fs_list", "args": {"path":"."}},
      "thoughtSignature": "<opaque blob A>"
    }]
  }

  // Follow-up request must echo the signature verbatim:
  {
    "role": "model",
    "parts": [{
      "functionCall": {"name": "fs_list", "args": {"path":"."}},
      "thoughtSignature": "<opaque blob A>"   <-- mandatory
    }]
  }

Implementation:

  TToolCall.ProviderSignature — new opaque string field on the
    shared TToolCall record (PasClaw.Providers.Types). Provider-
    specific blob; empty for everything except Gemini 3+. Survives
    history persistence through session save/load because it lives
    on the TToolCall the gateway already serialises.

  ParseResponse — reads the part-level \`thoughtSignature\` (sibling
    of functionCall, NOT inside it) and stashes it on the parsed
    TToolCall.

  BuildRequest — when emitting the assistant turn's part, if the
    TToolCall has a non-empty ProviderSignature, write it as a
    sibling of functionCall on the part. Empty signature stays
    silent — no empty "":"" field on the wire.

Tests added to gemini_schema_strip_tests:

  TestThoughtSignatureRoundTrip — assistant message carrying
    ProviderSignature = 'SIG_AAA_BBB_OPAQUE_BLOB' makes BuildRequest
    emit \`"thoughtSignature": "SIG_AAA_BBB_OPAQUE_BLOB"\` on the
    part, alongside the functionCall. Plus the function name and
    args survive.

  TestNoSignatureWhenEmpty — Gemini 2 path: empty ProviderSignature
    means no \`thoughtSignature\` key emitted at all. An empty
    string field would be invalid wire shape.

Verified:
  - make / make smoke clean
  - make test-gemini-schema-strip — all 5 tests OK

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 16452effa6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

parts) — Gemini 3 rejects the follow-up request with a 400
"Function call is missing a thought_signature" if it's
dropped. Empty for other providers and for Gemini 2.x. }
ProviderSignature: string;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Expose ProviderSignature through gateway tool-call round trips

When /v1/responses is used in passthrough mode with client-supplied tools, Gemini's parsed ProviderSignature is copied into OutToolCalls, but BuildResponsesObject serializes only id/call_id/name/arguments via FunctionCallItemJSON, and the next request's AppendAssistantToolCall has no way to restore the signature. In that gateway context, a Gemini 3 tool call returned to the client will still come back with an empty ProviderSignature, so BuildRequest omits thoughtSignature and the second provider request hits the same 400 this change is meant to fix.

Useful? React with 👍 / 👎.

parts) — Gemini 3 rejects the follow-up request with a 400
"Function call is missing a thought_signature" if it's
dropped. Empty for other providers and for Gemini 2.x. }
ProviderSignature: string;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Persist ProviderSignature in saved tool calls

This field is required for any historical Gemini 3 functionCall parts that are replayed, but the session serializer still writes only id, type, and function in ToolCallToJSON and reads only those fields in ToolCallFromJSON. After a completed tool-using session is saved and later resumed, the assistant tool-call history reloads with an empty ProviderSignature, so the next Gemini request omits thoughtSignature for the prior function call and can be rejected.

Useful? React with 👍 / 👎.

Two Codex findings on PR #154 — both legit, both blocking Gemini 3+
tool loops in surfaces other than the direct provider call.

Codex P1: gateway /v1/responses passthrough drops the signature.

  When /v1/responses is used as a passthrough for a non-OpenAI
  backend (Codex calling PasClaw calling Gemini), the gateway
  parses ProviderSignature into Resp.ToolCalls but
  FunctionCallItemJSON only emits id/call_id/name/arguments. The
  client then echoes the function_call_output back without the
  signature, AppendAssistantToolCall reconstructs the assistant
  turn with an empty ProviderSignature, and Gemini 3 400s on the
  next request with the same "missing thought_signature" error
  PR #154 was supposed to fix.

  Fix:
   - FunctionCallItemJSON gets a Signature parameter, emits a
     "provider_signature" extension field when non-empty. OpenAI
     Responses spec permits unknown fields; PasClaw-aware clients
     (its own Codex) echo it back on the input function_call item.
     Empty signature -> field omitted (stock /v1/responses traffic
     stays clean and identical to before).
   - All 5 call sites updated to pass ToolCalls[i].ProviderSignature
     (BuildResponsesObject + the SSE in_progress/completed pair on
     both the chat-style and the responses-style streamer).
   - AppendAssistantToolCall gets a Signature parameter; reads
     provider_signature from the input item and writes to
     Tc.ProviderSignature.

Codex P2: session save/load drops the signature.

  ToolCallToJSON / ToolCallFromJSON (the persistence path
  TSession.Save / Load go through) only wrote id, type, function.
  A session saved mid-Gemini-3-tool-loop and resumed loses the
  signature on the assistant turn, and the next request 400s.

  Fix:
   - ToolCallToJSON emits "provider_signature" when non-empty.
   - ToolCallFromJSON reads it on the way back in.
   - Empty stays empty so stock session files don't accumulate
     the field.
   - Both functions exposed in PasClaw.Session.Store interface so
     tests can hit them directly.

Tests added to gemini_schema_strip_tests:
  - TestSessionPersistenceRoundTrip: TToolCall with
    ProviderSignature = 'SIG_PERSIST_THIS_BLOB' survives
    ToolCallToJSON -> JSON string -> Parse -> ToolCallFromJSON.
  - TestSessionPersistenceEmpty: empty signature -> field omitted
    on disk, round-trips back to empty.

  make test-gemini-schema-strip -> all 7 cases OK
  make smoke                    -> all 11 commands OK
@FMXExpress
FMXExpress merged commit e874f33 into main Jun 6, 2026
FMXExpress pushed a commit that referenced this pull request Jun 9, 2026
PR #154 added a `provider_signature` extension field on /v1/responses
function_call output items so PasClaw could round-trip Gemini 3+'s
thoughtSignature across turns. That works for PasClaw-aware clients
(Codex configured with the extension). Stock OpenAI-Responses
clients (Codex CLI, etc.) JSON-validate input items and drop
unknown fields, so the signature is gone by the next turn and
Gemini 3 rejects with:

    400 Function call is missing a thought_signature in functionCall
        parts. ... function call `default_api:mcp__Kai__getProjectInfo`,
        position 4.

Belt-and-suspenders: also keep a process-wide call_id -> signature
map. Two new helpers near the top of the impl section:

  RememberProviderSignature(CallId, Signature)
      Called from FunctionCallItemJSON whenever we emit a
      function_call output item with a non-empty signature.

  LookupProviderSignature(CallId) -> Signature
      Called from the function_call input parser in HandleResponses
      when provider_signature is missing on the input item but
      we recognise the call_id.

Either path now yields a non-empty signature whenever Gemini's
original tool call carried one, so the "missing thought_signature"
400 stops triggering even when the client strips our extension.

Bounded to 1024 entries (PROVIDER_SIGNATURE_CACHE_MAX). Eviction
is real FIFO -- TStringList is intentionally unsorted so Delete(0)
removes the oldest insertion, not the lowest-call_id-alphabetically.
A sorted+dupIgnore list would drop whichever conversation
happened to draw the smallest call_id and break active turns
unpredictably. IndexOfName is linear on unsorted lists but
PROVIDER_SIGNATURE_CACHE_MAX is small and we only touch the
cache on tool-call boundaries; sub-millisecond and rare.

Per-process, in-memory only -- restart drops the cache, consistent
with the rest of /v1/responses (no durable session). Crit-section
protected; HandleResponses can be reentered by concurrent
requests on the gateway's Indy thread pool.
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.

2 participants