Repository navigation
fix(gemini): keep mid-conversation system messages in place so prompt caching survives - #53623
Conversation
… caching survives
…id_conversation_system_inline # Conflicts: # tests/unit/llms/vertex_ai/gemini/test_transformation.py
…id_conversation_system_inline # Conflicts: # litellm/llms/vertex_ai/gemini/transformation.py # tests/unit/llms/vertex_ai/gemini/test_transformation.py
PR overviewThe PR changes Gemini message conversion to keep mid-conversation system messages in place rather than moving them into system instructions, preserving prompt caching behavior. One issue remains open after one was addressed: guardrail warnings can be converted into user content alongside attacker input, weakening their privileged instruction boundary. This affects both standard and context-caching conversions and could make configured guardrails easier to override, though the impact depends on their use. Open issues (1)
Fixed/addressed: 1 · 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: Preserve privileged guardrail instructions
CustomGuardrail.inject_advisory_message() appends security warnings—for example, Lakera's inject_system_message mode—but this conversion now sends those warnings as user content alongside attacker input instead of in system_instruction; the operator-note prefix does not preserve the privileged instruction boundary. Keep guardrail/policy instructions in the privileged channel, or make this lossy reminder conversion explicitly opt-in, and apply the same distinction to the conversion in context_caching/transformation.py:157.
There was a problem hiding this comment.
Kept on purpose. Bedrock and Anthropic already send later system messages as user text. Hoisting them into systemInstruction 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
[Medium impact] The latest TTL changes appear safe to merge, with no new blocking finding.
|
…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
…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
…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
…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
|
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 a1a8d15. 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 made a new cachedContent every turnHow it solves it:
systemInstructionIntentional product change: later system messages reach Gemini as operator-noted user parts, like on Bedrock Converse
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 0gemini/modelsAfter: the same agent reads about 28,800 of its 31,000 prompt tokens from the cache after the first turn, like a direct Vertex AI call
cached_tokensis now 28,781, where the direct call reads 28,762gemini/modelsRelevant issues
Fixes #42104 for chat completions and the Responses API. Its Claude Code case on /v1/messages already caches since #41493
This builds on #42126 by @Pawan-Shahane and adds the operator note, tool result ordering and explicit cache handling
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 a1a8d15 and the merge base c345f50, each a 2-worker proxy calling real Vertex AI, Gemini API and Anthropic. 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)
previous_response_iddeveloperrolecache_control, caches madecache_control_injection_points, caches madeAnthropic rejects Before's reminder between tool results. The previous tip made the TTL case's cache live 3600s (output)
config.yaml, env vars and proxy command
Env var names are
LITELLM_MASTER_KEY,VERTEXAI_PROJECT,GOOGLE_APPLICATION_CREDENTIALS,GEMINI_API_KEYandANTHROPIC_API_KEY. The run used a 31k-token prefix, since a 34k-token body is over Linux's 128 KiB limit for one command-line argument. The Claude Code case runs the real TUI in tmux withANTHROPIC_BASE_URLset to the proxy and every model alias set togemini-3.8-flash(cc_leg.shin the gist). Theprevious_response_idcase runs on its own proxies with a database per leg andstore_prompts_in_spend_logs: true(config-db3.yamlin the gist)Before (c345f50)
Chat completions, Vertex AI, a reminder after each user turn
Other cases
Chat completions with
"stream": true, Vertex AI, remindersResponses API, Vertex AI, history resent, reminders
Responses API,
previous_response_id, prompts stored in spend logsChat completions, Gemini API, reminders
Chat completions, Vertex AI,
developerrole remindersChat completions, Vertex AI gemini-4-neon, 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 reminder carrying the only TTL, Vertex AI (no change expected)
Chat completions, Vertex AI, no reminders (control)
Claude Code TUI on /v1/messages, four turns, then /cost (no change expected)
A cached reminder, then a reminder and a tool result
A reminder between a tool call and its result, Gemini
A reminder between two parallel tool results, Gemini
Three tool results with a reminder between each, Anthropic
Three tool results with a reminder between each, Vertex AI Claude
A video in a later system message
A video in a later system message, with explicit caching
After (a1a8d15)
Chat completions, Vertex AI, a reminder after each user turn
Other cases
Chat completions with
"stream": true, Vertex AI, remindersResponses API, Vertex AI, history resent, reminders
Responses API,
previous_response_id, prompts stored in spend logsChat completions, Gemini API, reminders
Chat completions, Vertex AI,
developerrole remindersChat completions, Vertex AI gemini-4-neon, 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 reminder carrying the only TTL, Vertex AI (no change expected)
Chat completions, Vertex AI, no reminders (control)
Claude Code TUI on /v1/messages, four turns, then /cost (no change expected)
A cached reminder, then a reminder and a tool result
A reminder between a tool call and its result, Gemini
A reminder between two parallel tool results, Gemini
Three tool results with a reminder between each, Anthropic
Three tool results with a reminder between each, Vertex AI Claude
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
Stream
Responses, history resent
previous_response_idGemini API
developerrolegemini-4-neon
Explicit cache
Explicit cache, last reminder marked
No reminders
Type
🐛 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 itsfunctionResponsecache_controlblock in the cache, and later reminders go into the requestsystem_instructionnext tocachedContent, so a reminder in the cache would change the cache key every turncache_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 fix(gemini): send video_url content parts to Gemini instead of dropping them #53406 made it, 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