Skip to content

fix(vertex_ai): reject client-mangled thought_signature embedded in tool_call_id - #38333

Open
libaojiang wants to merge 7 commits into
BerriAI:mainfrom
libaojiang:fix/vertex-thought-signature-mangled-id-37849
Open

libaojiang wants to merge 7 commits into
BerriAI:mainfrom
libaojiang:fix/vertex-thought-signature-mangled-id-37849

Conversation

@libaojiang

@libaojiang libaojiang commented Aug 26, 2026 •

Copy link
Copy Markdown

TLDR

Problem this solves:

  • Any client that normalizes ids mangles the __thought__ suffix in tool_call_id
  • Next turn forwards the corrupted base64 to Vertex, which returns a hard 400
  • Once in history the session is dead: every following turn 400s the same way

How it solves it:

  • Embed a SHA-256 checksum beside each signature in the beta tool-call ID envelope
  • Validate both strict base64 and the checksum, returning None when either fails
  • Gemini 3+ substitutes the documented skip-validator dummy; Gemini 2.x drops it

User Flow

Before: an operator using a Telegram assistant built on an OpenAI-compatible client (Claude Code, OpenClaw, some editor integrations) that normalizes call_id sees the assistant answer the first question, then every following turn fails and the conversation is dead

  1. The operator sends a Telegram message that requires a tool call to the assistant.
  2. The client sends POST https://litellm-domain/v1/responses with "model": "gemini-3.1-pro-preview" and a function tool.
  3. 200 comes back with a function_call item whose call_id is 1,223 characters long: call_2156408__thought__AY89a1/Iab3+RVjKCabD+h7qYLWIf2BWZ9CZDSDoMZpQytG... (id and call_id are identical).
  4. The client stores that call_id. Because it's an identifier, it normalizes it into something id-shaped: e.g. call_2156408__thought__AY89a1/_57b05e78dc.
  5. The client runs the tool locally and sends the next turn, echoing back the normalized call_id together with the function_call_output.
  6. The proxy answers 400: Invalid value at 'contents[1].parts[0].thought_signature' (TYPE_BYTES), Base64 decoding failed for "AY89a1/_57b05e78dc".
  7. The operator sees LLM request failed in the chat. Retrying doesn't help: the broken value is now part of the conversation history, so every following turn fails the same way.

After: the same conversation continues normally because the corrupted signature is treated as "no signature" and either falls back to the documented dummy (Gemini 3+) or is simply dropped (Gemini 2.x)

  1. The operator sends the same Telegram message.
  2. The client sends the same POST https://litellm-domain/v1/responses with "model": "gemini-3.1-pro-preview".
  3. 200 comes back with the same call_id shape as before, still carrying the raw signature after __thought__.
  4. The client stores and normalizes it into the same 41-character call_2156408__thought__AY89a1/_57b05e78dc.
  5. The client runs the tool and sends the next turn, echoing back the normalized call_id.
  6. The proxy answers 200 and the model produces the final message.
  7. The operator gets the answer and can keep asking follow-up questions in the same conversation.

Relevant issues

Fixes #37849

Linear ticket

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile will review once opened)

Screenshots / Proof of Fix

Reproducer (no live credentials needed; the corruption happens entirely inside _get_thought_signature_from_tool → convert_to_gemini_tool_call_invoke):

from litellm.litellm_core_utils.prompt_templates.factory import (
    THOUGHT_SIGNATURE_SEPARATOR,
    _get_dummy_thought_signature,
    _get_thought_signature_from_tool,
    convert_to_gemini_tool_call_invoke,
)

mangled_id = f"call_2156408{THOUGHT_SIGNATURE_SEPARATOR}AY89a1/_57b05e78dc"
tool = {"id": mangled_id, "type": "function"}

extracted = _get_thought_signature_from_tool(tool)

assistant_message = {
    "role": "assistant",
    "content": None,
    "tool_calls": [{
        "id": mangled_id,
        "type": "function",
        "function": {"name": "get_temperature", "arguments": '{"location": "Paris"}'},
    }],
}
parts = convert_to_gemini_tool_call_invoke(assistant_message, model="vertex_ai/gemini-3.1-pro-preview")
print("extracted:", extracted)
print("part[0] signature:", parts[0].get("thoughtSignature"))
print("is dummy:", parts[0].get("thoughtSignature") == _get_dummy_thought_signature())

Before (litellm_internal_staging tip prior to this PR)

  1. Command: run the reproducer above.

  2. Output:

    extracted: AY89a1/_57b05e78dc
    part[0] signature: AY89a1/_57b05e78dc
    is dummy: False
    

    Vertex rejects AY89a1/_57b05e78dc with Base64 decoding failed, so every turn that quotes this id 400s.

After (f62514f)

  1. Same command.

  2. Output:

    extracted: None
    part[0] signature: c2tpcF90aG91Z2h0X3NpZ25hdHVyZV92YWxpZGF0b3I=
    is dummy: True
    

    The signature is dropped and the Gemini 3+ code path substitutes the documented skip-validator dummy; the request goes through instead of 400-ing.

Targeted regression tests

  1. Command:

    pytest tests/test_litellm/llms/vertex_ai/gemini/test_thought_signature_in_tool_call_id.py -v
    
  2. Output:

    21 passed
    

    The broader Vertex slice passes 47 tests, and the Anthropic compatibility slice passes 6 tests

Type

🐛 Bug Fix

Caveats

Low

  • The checksum updates the beta ID envelope. Pre-update unsigned embedded signatures use the existing dummy-or-drop fallback instead of being forwarded without an integrity check
  • Emitting and reading tool_calls[].thought_signature remains additive follow-up work outside this focused bug fix
  • One existing test used "signature_for_first_call" as a placeholder signature that isn't valid base64. Real Gemini signatures always are, so the test now uses base64.b64encode(b"signature_for_first_call") to keep coverage identical under the stricter extraction.

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

@CLAassistant

CLAassistant commented Aug 26, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codecov

codecov Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.77419% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...llm/litellm_core_utils/prompt_templates/factory.py 96.77% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR validates thought signatures extracted from Vertex/Gemini tool-call IDs and falls back to the existing dummy-or-drop behavior when strict base64 decoding fails.

  • Adds strict, padding-tolerant base64 validation for ID-embedded signatures.
  • Adds regression coverage for normalized IDs and Gemini 2.x versus Gemini 3+ fallback behavior.
  • Updates an existing parallel-tool-call fixture to use valid base64.

Confidence Score: 4/5

The PR should not merge until decodable but client-mangled signatures are prevented from bypassing the existing fallback.

The validator distinguishes malformed base64 from valid base64 but cannot establish signature integrity, so a normalized suffix that remains decodable is still forwarded and rejected by Vertex.

Files Needing Attention: litellm/litellm_core_utils/prompt_templates/factory.py; tests/test_litellm/llms/vertex_ai/gemini/test_thought_signature_in_tool_call_id.py

Important Files Changed

Filename Overview
litellm/litellm_core_utils/prompt_templates/factory.py Adds syntactic base64 validation, but decodable client corruption can still bypass the fallback and reach Vertex.
tests/test_litellm/llms/vertex_ai/gemini/test_thought_signature_in_tool_call_id.py Adds targeted fallback tests, but all corrupted fixtures contain _ and therefore omit the decodable-but-semantically-invalid case.

Reviews (1): Last reviewed commit: "fix(vertex_ai): reject client-mangled th..." | Re-trigger Greptile

@codspeed

codspeed Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 31 untouched benchmarks


Comparing libaojiang:fix/vertex-thought-signature-mangled-id-37849 (2403fa9) with main (ac98cab)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (7efce7f) during the generation of this report, so ac98cab was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@libaojiang
libaojiang force-pushed the fix/vertex-thought-signature-mangled-id-37849 branch from 16d8cff to a60da7e Compare August 31, 2026 02:21
@libaojiang
libaojiang force-pushed the fix/vertex-thought-signature-mangled-id-37849 branch from a60da7e to 91789da Compare August 31, 2026 02:27
@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:45
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 14:54
@devin-ai-integration
devin-ai-integration Bot requested a review from a team September 23, 2026 14:54
libaojiang and others added 4 commits October 12, 2026 22:26
…ool_call_id

A Gemini `thoughtSignature` is standard-alphabet base64 bytes, but LiteLLM
appends it to `tool_calls[].id` after a `__thought__` marker. Any client that
normalizes ids (Claude Code, OpenClaw, editor integrations that shorten +
hash the id) mangles the base64 and replays it verbatim on the next turn.
`_get_thought_signature_from_tool` used to extract that mangled tail as-is,
so `convert_to_gemini_tool_call_invoke` forwarded it to Vertex, which rejects
the request with `Base64 decoding failed for "..."` or
`Invalid thought signature`. Once a corrupted value entered the history,
every following turn failed the same way and the session was dead.

Validate the extracted tail against Vertex's strict base64 decoder (padding
tolerant) and return None when it fails. Callers already handle the
"no signature" case correctly: on Gemini 3+ the first function call falls
back to the documented skip-validator dummy signature; on Gemini 2.x the
signature is simply omitted. Either way the hard 400 becomes a graceful
degradation, and clients that keep the signature in
`provider_specific_fields` (LiteLLM SDK) are unaffected because that path
is checked first.

Fixes BerriAI#37849
The strict-rule gate hard-failed PR BerriAI#38333 because the new
`_is_valid_thought_signature` returned inside the ``try`` body (TRY300).
Move the success return into a trailing statement so ruff sees the
canonical shape and the budget stays base-neutral.

Also add a regression test that pins what the ID-embedded fallback
actually guarantees: it rejects wire-encoding damage, not semantic
integrity. Documents Greptile's observation on the PR that a client
normalizer preserving standard base64 characters can still produce a
value Vertex will reject as an unauthenticated signature; callers that
need semantic verification must compare against the provider-issued
signature.

Co-authored-by: Cursor <cursoragent@cursor.com>
@libaojiang
libaojiang force-pushed the fix/vertex-thought-signature-mangled-id-37849 branch from 91789da to 8a5d679 Compare October 12, 2026 14:30
Rework onto main renamed the helpers to public names and upstream added
factory tests pinning the pre-checksum wire format, so update those
expectations to the checksummed layout and use a valid base64 signature
for the embedded-id round trip.
The type discipline gate now counts LIT010 against the merge-base
ceiling and the rebase carried one un-annotated assignment over.
basedpyright counts the str isinstance as reportUnnecessaryIsInstance
now that the id carries a str cast, and the type gate rejects any
growth over the merge-base count.

Copy link
Copy Markdown
Author

@greptileai Please review the current head again. Both previous findings are resolved, including checksum validation and removal of redundant comments.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Gemini thought signature is embedded in the tool call id, so any client that normalizes ids breaks the next turn

3 participants