Repository navigation
fix(gemini): replay each assistant image's thought signature on its own part - #53446
Conversation
…wn part Gemini image models sign every final image part and only accept a signature replayed inside its original part. Each generated image now carries its own signature in images[].provider_specific_fields.thought_signature, and the history converter sends it back on that image part. History from before this change falls back to the message-level list, right-aligned onto the images, and the text part keeps the first signature no image or tool call claimed
…pt unsigned image fields A streamed reply saved before per-image signatures lists only the text's signature, and the history fallback moved it onto the image. The text now keeps the first unused message signature as before, and saved images take only what is left, matched from the end thought_signature is optional inside an image's provider_specific_fields, so a response whose image carries other provider fields, or none, parses again
The shared response type no longer declares an image's provider_specific_fields, so an upstream response whose image carries other keys there, or a non-string signature, validates exactly as it did before. Gemini's own image items still type the signature
[Medium impact] The PR appears safe to merge, with no new actionable issues or outstanding previous findings
|
…ension (cherry picked from commit 22cb375)
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
…p list text signatures off images (cherry picked from commit 9a2db67)
| entries: Final = (as_object_list(fields.get("thought_signatures")) if fields is not None else None) or () | ||
| signatures: Final = tuple(entry for entry in entries if isinstance(entry, str)) | ||
| if len(signatures) < len(entries) and not drop_params: | ||
| raise _malformed_assistant_history("provider_specific_fields.thought_signatures entries must be strings", model) |
There was a problem hiding this comment.
Parsing helpers raise errors directly
These helpers raise BadRequestError directly, including the image URL check below. The repository requires failure values and one error boundary. Return failures and raise at that boundary before merging
Context Used: AGENTS.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Every check in this converter raises BadRequestError, its existing error contract. Returning failure values would just re-raise one frame up with no behavior change
There was a problem hiding this comment.
You're right — if the converter already has an established pattern of raising BadRequestError directly, and the alternative would just add a wrapper layer that immediately re-raises, then the current approach is the correct one for consistency.
I see now that _malformed_assistant_history is a helper specifically for creating these errors in this converter's context, which reinforces that this is the intended error-handling pattern here.
Thanks for the clarification. Would you like me to remember that direct BadRequestError raises are the preferred pattern for this module going forward?
…_image_history_thought_signature_lts # Conflicts: # litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py # tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
… empty string (cherry picked from commit acdf68a)
…rejects a replayed signature lts/1.108.x lacks main's BerriAI#49697, so a Vertex image-only reply replayed to AI Studio answered 400 "Corrupted thought signature." once the image carried its own signature. This ports BerriAI#49697's chat completions resend: on a 400 naming a thought signature, swap every replayed signature for Google's skip-validator placeholder and post once more. The context cache inline resend and the native generateContent resend stay main-only.
…_params in batch Text models reject an image model's signature on a replayed image with a 400 that the placeholder resend does not catch, so images go unsigned unless the target outputs images. An empty assistant reply keeps its text signature, Vertex batch lines honor drop_params, and the malformed history error names the right provider. (cherry picked from commit d7574b3)
…rop_params for malformed images (cherry picked from commit ba001d4)
…rs an image model
…_image_history_thought_signature_lts # Conflicts: # litellm/llms/vertex_ai/files/transformation.py # litellm/llms/vertex_ai/gemini/transformation.py
| parts: Final = _signed_text_and_image_parts( | ||
| assistant_msg, target, vertex_project, vertex_credentials, drop_params=drop_params | ||
| ) | ||
| if isinstance(parts, _MalformedHistory): | ||
| raise BadRequestError( | ||
| message=f"Invalid assistant message: {parts.message}", | ||
| model=target.model, | ||
| llm_provider=target.custom_llm_provider or "vertex_ai", | ||
| ) |
There was a problem hiding this comment.
Live proxy proof stops at 31f4ad07ed5, before c54941613d changed the malformed-history error path. The repository requires after-proof at the latest product commit before merging. Rerun the malformed-history cases and include commands and outputs
Rule Used: Apply this rule only to PRs that fix LLM translation bugs or add LLM translation features. LLM translation means converting requests, responses, streaming events, tool calls, and errors between the API a caller uses on LiteLLM (any endpoint or SDK fu... (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Reran the 12 malformed history and SDK cells at c549416, all matching earlier results. The Last updated line now links the commands and outputs
…_image_history_thought_signature_lts # Conflicts: # tests/unit/llms/vertex_ai/gemini/test_vertex_and_google_ai_studio_gemini.py
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit d1aa0fb. Configure here.
Handwritten 1-3 sentence description
Gemini image models on Vertex now keep the picture when a chat asks for an edit in the next turn. LiteLLM used to drop the signature Google puts on each generated image when the chat history came back, so Vertex ignored the old picture and drew a new one, and a third turn failed with a 400
Details
TLDR
Problem this solves:
How it solves it:
thought_signatureThis is the lts/1.108.x twin of the main fix. It also ports the chat completions resend from #49697, since an image's Vertex signature sent to AI Studio would otherwise answer 400
Design decisions
message.imagesgetsprovider_specific_fields.thought_signature, and the message-levelprovider_specific_fields.thought_signatureslist stays as it is. Moving signatures off the list was the alternative, but clients already read it. Matching the list to images by position alone was the other, and saved history already works that way (1481 prompt tokens). The per-image copy is still needed for streamed replies, which list only the text's signature, and for clients that drop or reorder images. The cost is that an image's signature (1.5 to 2.7 MB in these runs) appears twice in the response, so a text plus image reply grew from 4.32 MB to 6.05 MBcontentis a list. A saved reply with images whosecontentis""or[]counts as image only, so its image takes the signature instead of an empty text part. Without images, the empty text part keeps its signature as before. Dropping the list was the alternative, which keeps the bug for every saved chatdrop_paramsrule, on any assistant message, with or without images. An image entry orimage_urlthat is not an object, an image URL that is not a string, an image's own signature that is not a string, or athought_signaturesentry that is not a string, answers 400 "Invalid assistant message", and withdrop_paramsthe bad entry is dropped and the rest is sent. A stringimage_urlis read as the URL, where base skipped the image. Base ignored a bad signature entry and answered 500 for a number as the URL. An empty URL is skipped as before. Vertex batch lines honor the line's or the deployment'sdrop_params. Silently dropping both was the alternative, which hides a broken clientmessage.images, and merged first, so its test now expects the final image with its own signatureprovider_specific_fields.thought_signature. The shared response type leaves it undeclared, so a response whose image carries other keys there, or a non-string signature, validates exactly as before. Declaring it on the shared type was the alternative, and it made those responses fail validationvertex_ai/andgemini/deployments, a Vertex image signature replayed to AI Studio gets a 400, and the resend with Google's placeholder signature from fix(gemini): resend once with the placeholder signature when the other backend rejects a replayed thought signature #49697 turns that into a 200 after one more call. Sending each image's signature to both backends keeps every same-backend edit working, which is the case this fixes. Leaving images unsigned forgemini/was the alternative, and Google's Gemini 3 docs say image signatures are validated strictly there too. The lts/1.108.x twin ports only that chat completions resend, since the line does not have fix(gemini): resend once with the placeholder signature when the other backend rejects a replayed thought signature #49697modeimage_generationorimageinsupported_output_modalities). Text models such asgemini-3.8-flashanswer 400 "Request contains an invalid argument" to an image model's signature, which the fix(gemini): resend once with the placeholder signature when the other backend rejects a replayed thought signature #49697 resend does not catch. Models the cost map lacks get unsigned images, as on base, andmodel_info: {mode: image_generation}on the deployment turns signing on. On this line a deployment'smodel_info.modeoverwrites the model's shared cost map entry, so the gate also reads litellm's bundled cost map, and an image model deployed asmode: chatstill gets its images signed. Signing for every target was the alternative, and it broke asking a text model about a drawn pictureprovider_specific_fields, the same way the message-level field was already stripped for them. FriendliAI strips them only on main, since that came with fix(friendliai): drop litellm-internal message fields before sending #45092, which this line lacks. Keeping it was the alternative, and it sent them a 1.9 MB signature they cannot useUser Flow
Before: a developer edits a Vertex Gemini picture over chat, and every edit comes back as an unrelated new picture
gemini-3.1-flash-imageasking for a cartoon cat on a chair, and get text plus one imageAfter: the same steps edit the same picture
provider_specific_fields.thought_signatureRelevant issues
Fixes #52543
LTS pick table
cf6b102213288e14ee63913073f40358e5a2dd668b43a54f9b5a99894a0de92ba1fd28ce46cece8c20699817c09acd1dc09a11cfa37d6d80eba9c40340e236b185153ee4de5a8a417c60a157110366fbcad8b63c484af6c49b3de134299fdeed0e1448b8518c4fccfa1bc806aab7ab7b1418663b08cea18922cb375898a49087f96bf2a27756c7b3a2903b097d896964264103e531bb100e0a5348f4e16aeceb9a2db6706d3ef6bd6fbf3e141dd16a6753f350515b248ff620239f88e6605dc524b1d7f616a19cc5acdf68aaa3a74d4e109062f22de0857d9341b51c597b27b17820285ab64e8b374b2a9952a9d574b9d7574b348346ecdfdb3cde8b0259944edde88fe11172684ef793696362beafe6cc007ab8b3765751ba001d436e3ef6540b10494c9b32c65bce13f73d1cb4f050e2755fba3df52493574a7219b2ac9ac1670cad99ddb7045e9a51fc563864dc6f0ba5c550c54941613d1ced65fce0eed7b7aaa2a6cafe51a1The fifth pick names the image source
_AssistantImageSource, since lts/1.108.x has noGeminiMediaSource, and adds theitertools.chainimport its test needs, which main already had. The ninth is the same refactor applied by hand, since on the line the helpers sit aftergemini_convert_messages_with_history4d024df merges lts/1.108.x after #53441, which moved image extraction into
_inline_image. The merge resolution has_inline_imagereturn the image with its own signature through_generated_image_item, and adds the signature to #53441's expected final image, as main did after #5070947ebb08 is not a pick. It ports only the chat completions part of #49697, which resends once with Google's placeholder signature when a backend rejects a replayed one. Without it, a Vertex image-only reply replayed to AI Studio answered 400 on this branch where base answered 200, because the image now carries its Vertex signature. The context cache resend and native
generateContentparts of #49697 stay main-onlyThe seventh pick also points 47ebb08's image resend test at an image model, since a text model now gets the image unsigned
The eighth pick keeps this line's imports and
_AssistantImageSource, adds the test imports main already had, and drops apart_typeparametrize decorator the conflict carried over from main31f4ad0 is not a pick. On this line the router writes a deployment's
model_info.modeonto the model's shared cost map entry, so an image model deployed withmode: chatread as a text model and lost its image signatures. The gate now also reads the bundled cost map, which main does not needPre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Each leg boots one 2-worker proxy from the commit under test and calls real Vertex AI and Google AI Studio. Each cell is the edit turn's
usage.prompt_tokens, which shows whether the model read the earlier picture. "Direct to Google" replays the same turns straight togenerateContent. "History saved before this fix" sends turn 1 through the before proxy and the edit through the after proxy. Commands are as the shell printed them, with master keys shown as<master key>At 31f4ad0 a sentence-first Nano Banana prompt ran 3 times per side. Vertex read the picture in every after run, no before run, and both edits of such a reply saved before this fix
Nano Banana image tokens
Each cell is the edit turn's
prompt_tokens_details.image_tokens. Commands and outputsSetup: proxy start, config.yaml, case script, SDK client, direct script
Env var names:
VERTEXAI_PROJECT,GOOGLE_APPLICATION_CREDENTIALS,GEMINI_API_KEY,LITELLM_MASTER_KEY,LITELLM_LOCAL_MODEL_COST_MAP=True,PYTHON_DOTENV_DISABLED=1,LITELLM_DANGEROUSLY_PERMIT_WEAK_OR_UNSET_MASTER_KEY=truePorts: before 26998, after 22935
cell.sh <case> <port> <out dir> [<turn 1 port>]is in the proof gistsdk_client.py <port>, run with openai 3.57.0direct.py <vertex|studio> <model> <text|image> <out dir>is in the proof gistLast updated: d1aa0fb. QA ran on 1172684, before leg on c36e1cf. Later commits change only malformed history, strict providers,
modeoverrides and the line's own fixes, which no case sends. Unit tests, Live PR risk and Nano Banana passed at 31f4ad0. 17 risk cells matched it at 1cdc99a6873 and d1aa0fb36f5, and the 12 malformed history and SDK cells matched again at c549416Before (c36e1cf, lts/1.108.x merge base)
Vertex flash, text + image
Vertex flash, image only
Vertex flash, streamed first turn
Vertex flash, three turns
OpenAI Python SDK
Vertex Nano Banana, run 1
Vertex Nano Banana, run 2
Vertex Nano Banana, run 3
AI Studio flash, text + image
Vertex text-only model
After (1172684)
Vertex flash, text + image
Vertex flash, image only
Vertex flash, streamed first turn
Vertex flash, three turns
OpenAI Python SDK
Vertex Nano Banana, run 1
Vertex Nano Banana, run 2
Vertex Nano Banana, run 3
AI Studio flash, text + image
Vertex text-only model
History saved before this fix
Direct to Google
Vertex flash text + image, Vertex flash image only, Vertex Nano Banana, AI Studio flash text + image
Surprises
Type
🐛 Bug Fix
Caveats (if any)
Medium
log_pre_api_calltwice for one such requestLow
drop_paramsrule (design decision 5). In a Vertex batch file, one bad line fails the whole file unlessdrop_paramsis setLive PR risk
Blast radius, base vs head, run at 518c4fc, 5b248ff, 47ebb08, 1172684 and 31f4ad0, head side at 1cdc99a, c549416 and d1aa0fb
No dependent path breaks. Each side ran from its own worktree (base 7ab941f, head 518c4fc) with 2 workers, the same config, its own Postgres database and Redis, and a recording forwarder in front of Vertex AI and AI Studio, so the requests litellm sent to Google were compared too. Cells covered text plus image, saved histories from before this fix (text signature only, a streamed reply, a Nano Banana draft and final), malformed per-image signatures (empty, number, list, 5 KB string, one image listed twice), Vertex to AI Studio and back, the response cache,
/v1/responses,/v1/messages, text streaming, key create and delete, health and spend logsAt 5b248ff these cells ran again on both sides: text plus image (1490 prompt tokens, base 53), list content with only the text's signature (53 on both, no signature sent on either side), a streamed reply and a Nano Banana draft and final saved before this fix (48 and 2532, base 48 and 2449), a number as the image's own signature (1490, base 53), an object in
thought_signaturesand a number as the image URLAt 47ebb08 these cells ran again on both sides, with base c36e1cf, each replaying a saved first turn with one change. Each number is the edit turn's prompt tokens on a 200. Commands and outputs are in
cells13-lts.logandcells13-ltsbase.logThe other cells of that run (empty content, list content, text + image,
thought_signatures, image only to AI Studio) gave the same numbers as the 1172684 table belowBoth Vertex to AI Studio cells made two AI Studio calls on head, a 400 "Corrupted thought signature" and then the placeholder resend, and one on base. Before 47ebb08 the image-only cell answered 400 on head (
cells11-lts.log)At 1172684 these cells ran on both sides (base c36e1cf). Each number is the last turn's prompt tokens on a 200. Commands and outputs
thought_signaturesdrop_paramsWith a text model as the target, both sides send the image unsigned. Each Vertex image-only to AI Studio cell made two AI Studio calls on head and one on base, streamed and sync SDK included
At 31f4ad0 these cells ran on both sides (base c36e1cf), with recording forwarders in front of Fireworks and Mistral too. Each number is the edit turn's prompt tokens, or the status for Fireworks and Mistral. Commands and outputs are in
cells15-lts.logandcells15-ltsbase.logimage_urlimage_urldrop_paramsdrop_paramsdrop_paramsmode: chatdeploymentthought_signaturesdrop_paramsFireworks got 4,597,164 bytes with the image's signature on base and 2,708,785 bytes without it on head. Mistral answers 422
extra_forbiddenonimageson both sides, a pre-existing bug filed separately. Themode: chatdeployment registersgemini-3.1-flash-imagewithmodel_info: {mode: chat}. Before 31f4ad0 that deployment sent the image unsigned on head too. The two cross-backend rows give the status and the calls Google got, and are incells16-lts.logandcells16-ltsbase.log. The SDK rows calllitellm.completionfrom each tree with the saved first turn, and their output is at the end of each log. The batch row converts a saved text + image turn with each tree's Vertex batch line converter and sends the row togenerateContent(script, output)Breaking
None for well-formed history. Every other cell answered the same status on both sides, apart from a Vertex reply replayed to AI Studio and an AI Studio tool call replayed to Vertex, which answered 400 on base and now answer 200. The requests to Google differ only where this PR says they should, since a replayed image part now carries its signature. Saved histories from before this fix send the same parts as base, apart from the Nano Banana final image, which now gets its own signature
Backward incompatible
Malformed assistant history now answers 400 "Invalid assistant message" instead of going through, on any assistant message with or without images. An object in
thought_signaturesgot 200 on base and 400 on head, and withdrop_paramsit is dropped and the edit keeps the picture (1490 prompt tokens, base 53). A number as the image URL got a 500 TypeError on base and a 400 on head. An image entry orimage_urlthat is not an object, or an image's own signature that is not a string, was skipped on base (53 prompt tokens) and now answers 400 unlessdrop_paramsis set. This follows litellm'sdrop_paramsruleNo existing field changed. Each image in a response gains
provider_specific_fields.thought_signature, and the same signature stays in the message'sthought_signatureslist, so a text plus image response grew from 4.32 MB to 6.05 MB. This is design decision 2, kept on purpose and open for the reviewerImage
provider_specific_fieldsvalidates exactly as on base, since only Gemini's own image type declares the signature. An OpenAI-compatible upstream that sends other keys there, or a non-string signature, still passes throughRegression risk
A replayed text plus image turn sent to Google grew from 2.71 MB to 4.60 MB, because the image's signature now goes with it. That is the fix. A replayed image whose own signature is a wrong string is sent with it, and Vertex then ignores the picture, which is what base does for every replayed image (53 prompt tokens on both sides). A Vertex reply replayed to AI Studio answers 400 "Corrupted thought signature" on base, which lacks #49697. Head ports its chat completions resend, so both Vertex to AI Studio cells, a Vertex text reply sent to AI Studio and an AI Studio tool call sent to Vertex answer 200 after one extra call
Dependency graph
drop_paramsmode: chat/v1/responsesimage output/v1/messagesadapterNot verified
No Vertex batch job (
/v1/batches) ran, since the QA account gets 403 from the batch bucket, so each tree's converted batch line went togenerateContentinstead. Vertex context caching could not run, since Vertex answers 400 "does not support explicit context caching" forgemini-3.1-flash-imageon both sidesFinal Attestation
Bugbot summary