Repository navigation
fix(gemini): keep mid-conversation system messages in place so prompt caching survives (lts/1.108.x) - #53635
Conversation
… caching survives
…_keep_mid_conversation_system_inline_lts # Conflicts: # litellm/llms/vertex_ai/gemini/transformation.py # tests/unit/llms/vertex_ai/gemini/test_transformation.py
PR overviewThis PR changes Gemini message transformation to keep mid-conversation system messages in place, preserving prompt caching on the lts/1.108.x branch. One issue remains open: trusted guardrail warnings are converted into user messages and merged with flagged input, including when caching is disabled. This weakens the role separation used to resist prompt injection, though the reported issue does not establish a successful guardrail bypass. No issues have been addressed yet. Open issues (1)
Fixed/addressed: 0 · PR risk: 4/10 Reviews |
| system_content_blocks: Final = [part for _, part in parts_by_message if part is not None] | ||
| remaining_messages: Final = [ | ||
| *(message for message, part in parts_by_message if part is None), | ||
| *place_mid_conversation_system(rest, supports_mid_conversation_system=False), |
There was a problem hiding this comment.
Medium: Guardrail warnings lose their system role
Lakera's on_flagged="inject_system_message" appends a trusted warning through CustomGuardrail.inject_advisory_message(), but this conversion turns it into a user message that gemini_convert_messages_with_history() merges with the flagged input—even without caching. Preserve a system-level path for guardrail/policy messages in both this transformer and separate_cached_messages, or make demotion explicitly opt-in; the operator-note string does not preserve the system/user role separation used to resist prompt injection.
There was a problem hiding this comment.
Kept on purpose, same as #53623. Bedrock and Anthropic already send later system messages as user text. Hoisting them would miss the cache every turn
There was a problem hiding this comment.
Gemini has no system slot after the first turn. Keeping guardrail advisories privileged on Gemini, Bedrock and Anthropic is a separate follow-up
…plicit caching too Explicit caching turns later system messages into text-only user turns before the request is built, so a video_url in one of them was dropped without an error. The video check now runs on the whole message list before that split A model without system message support now gets its later system messages the same way with or without a cache, plain user text with no operator note (cherry picked from commit 9e32989)
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
[Medium impact] The changes since the previous review appear safe to merge
|
…icit cache A cached block that ended on a cached reminder, with more reminders and then a tool result after it, kept that reminder in the cache. The tool result then lost its call and Gemini answered 500. The block end now looks past every system message before the next turn The explicit cache path also answered 400 for a video in a later system message on models without system message support, which send that video through without a cache. The check now runs only for models with system message support (cherry picked from commit 4d76ae7)
…place A cache_control mark on a later reminder, such as cache_control_injection_points with index -1, put that reminder into the cache's system_instruction ahead of the turns it follows, so Gemini made a new cache every turn. A later system run that starts the cached block now stays out of it Also adds a test for a leading system message with no content (cherry picked from commit 25020eb, applied by hand because the LTS cache keeps the leading system run out of the cached block)
…ck out of the cache A marked block that starts after the first turn and ends on a marked reminder reached the cache only because the reminder became a user turn, and the cache then put that block ahead of the turns it follows. A later system run at the end of the block now stays out of the cache like one at its start, so that request goes out uncached and in order, as it did before this change (cherry picked from commit 050efcd, applied by hand because the LTS cache keeps the leading system run out of the cached block, so its docstring differs)
|
bugbot run |
…e block (cherry picked from commit a1a8d15)
|
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 5ceb9c2. Configure here.
Handwritten 1-3 sentence description
Gemini and Vertex AI prompt caching never hit for agents that send a system reminder every turn, because we moved every system message to the front of the prompt. Now only the leading system messages go there and later ones stay where they were sent, so the cache hits again from the second turn
Details
TLDR
Problem this solves:
systemInstructioncache_controlcaching answered 400 on this lineHow it solves it:
systemInstructionIntentional product change: later system messages reach Gemini as operator-noted user parts, like on Bedrock Converse and the Anthropic chat path
User Flow
Before: an agent that sends a system reminder after each user turn never reads from the Gemini prompt cache, so every turn pays full input price
role: systemreminderusage.prompt_tokens_details.cached_tokens0, which is normal for a first turncached_tokensis still 0cache_controlon the system prompt answers 400After: the same agent reads about 28,600 of its 31,000 prompt tokens from the cache after the first turn, like a direct Vertex AI call
cached_tokensis now 28,627, the same as the direct callcache_controlreuses one cache every turnRelevant issues
Fixes #42104 on the 1.108 LTS line. This is the same change as #53623, adapted to this line
Pre-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
QA ran on the tip 5ceb9c2 against its merge base lts/1.108.x 3c2fd0f. Each pick passed full QA on #53623, so this is one live before and after smoke per pick, through 2-worker proxies and the main PR's config and scripts. Before reuses runs at the same merge base. Direct sends the same conversation to the provider, and this gist has the raw output
Cached tokens on turns 2-4, unless the row says otherwise (rows)
cache_controlcache_control_injection_pointsThe chat, Responses, explicit cache and tool result rows cover the first pick, the video row the second, the cached reminder row the third, the marked reminder row the fourth, the marked reply row the fifth, and the TTL row the sixth. A marked reminder alone is below the minimum cache size, so neither leg makes an explicit cache there. Anthropic rejects Before's reminder between tool results. The TTL row marks the system prompt, since an unmarked one answers 400 on both legs
Before (3c2fd0f)
Chat completions, Vertex AI, a reminder after each user turn
Other cases
Responses API, Vertex AI, history resent, reminders
Explicit
cache_controlon the system prompt, Vertex AI, reminderscache_control_injection_pointsmarking the last reminder, Vertex AI, plain system promptA marked assistant turn and a marked reminder after the first question, Vertex AI (no change expected)
A marked system prompt and a marked reminder carrying the only TTL, Vertex AI (no change expected)
A cached reminder, then a reminder and a tool result
A reminder between two parallel tool results, Gemini
Three tool results with a reminder between each, Anthropic
A video in a later system message
A video in a later system message, with explicit caching
After (5ceb9c2)
Chat completions, Vertex AI, a reminder after each user turn
Other cases
Responses API, Vertex AI, history resent, reminders
Explicit
cache_controlon the system prompt, Vertex AI, reminderscache_control_injection_pointsmarking the last reminder, Vertex AI, plain system promptA marked assistant turn and a marked reminder after the first question, Vertex AI (no change expected)
A marked system prompt and a marked reminder carrying the only TTL, Vertex AI (no change expected)
A cached reminder, then a reminder and a tool result
A reminder between two parallel tool results, Gemini
Three tool results with a reminder between each, Anthropic
A video in a later system message
A video in a later system message, with explicit caching
Direct (the yardstick)
Direct calls
Chat, Vertex AI
Responses, history resent
Explicit cache
Explicit cache, last reminder marked
Differences from the main PR
string_fieldhelper, so a small_part_textreads the text of a content partcache_controlblock, since fix(openai): stop stripping cache_control from the caller's own messages and tools #35602 is not heresystem_instruction, as beforeEach branch then merges its own base. The main merge 4459641 and the LTS merge 7649c82 resolve the same conflict in
transform_system_messagewith the same code. The second pick had conflicts inseparate_cached_messagesand in nearby lines that differ on this line, like the imports andmodelin place oftarget.model, and keeps the same behavior. The third pick had conflicts in the_cached_block_enddocstring and in the cache entry points, where this line keeps its own skip logic and calls the new video helper in place ofreject_system_message_videos. The fourth pick has the same code, with the docstring wrapped to this line's text and its cache test sending a reminder large enough to cache, since this line caches only the marked block. The fifth pick has the same code, with its docstrings kept to this line's text, since this line keeps the leading system run out of the cached block. The sixth pick had conflicts where the fifth's split differs, and reads the TTL from the marked block alone, for the same reasonType
🐛 Bug Fix
Caveats (if any)
Medium
inject_system_messagewarning included, by typing the operator noteinstructionsfield still goes tosystemInstructionLow
cache_controlat either end of the cached block stays out of the cache, though its TTL appliesDecisions
userandmodelroles, so there is no native slot to keep it as systemmodelturn, since the model would read it as its own words, and dropping it would lose the agent's instructionfunctionCalland itsfunctionResponse, and on this line the model echoed a reminder placed therecache_controlblock in the cache, and later reminders go into the request as user turnssystem_instructionnext tocachedContent, which is the 400 Before showscache_control_injection_pointsmarks with index -1, stays out of the cache too, since the cache would put it ahead of the turns it follows, or the block would end on a model turn and go out of orderdrop_paramsis on, as on lts/1.108.x today, and now on the explicit cache path too, since a later system message becomes a user turn that carries only its textinject_system_messagemode, now reaches Gemini as an operator-noted user turn, the same as on Bedrock and on Anthropic without the betasystemInstructionwould keep it there, but a reminder after the last user turn would then change the prompt head every turn, which is the bug this PR fixesFinal Attestation
Bugbot summary