Skip to content

fix(gemini): keep mid-conversation system messages in place so prompt caching survives (lts/1.108.x) - #53635

Merged
mateo-berri merged 7 commits into
BerriAI:lts/1.108.xfrom
izzybn:litellm_gemini_keep_mid_conversation_system_inline_lts
Nov 23, 2026
Merged

mateo-berri merged 7 commits into
BerriAI:lts/1.108.xfrom
izzybn:litellm_gemini_keep_mid_conversation_system_inline_lts

Conversation

@izzybn

@izzybn izzybn commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Mid-conversation system messages were moved into Gemini's systemInstruction
  • So the prompt head changed every turn and implicit caching never hit
  • Explicit cache_control caching answered 400 on this line

How it solves it:

  • Only the leading system messages become systemInstruction
  • Later system messages become user turns in place, with an operator note
  • A reminder next to tool results goes after the function responses
  • The explicit cache leaves later reminders out of the cached block

Intentional 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

  1. The agent sends POST http://localhost:4000/v1/chat/completions with a 31k-token prompt, a question, and a role: system reminder
  2. It gets 200 back with usage.prompt_tokens_details.cached_tokens 0, which is normal for a first turn
  3. It appends the reply, the next question and another reminder, then sends again. cached_tokens is still 0
  4. Every later turn also shows 0, on POST /v1/responses too, and cache_control on the system prompt answers 400

After: 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

  1. Steps 1 and 2 are the same as Before
  2. It appends the reply, the next question and another reminder, then sends again. cached_tokens is now 28,627, the same as the direct call
  3. Later turns hit the cache too, on POST /v1/responses as well, and cache_control reuses one cache every turn

Relevant 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

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • 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
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays 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)

Case Before After Direct
Chat, Vertex 0 28.6k 28.6k
Responses, history resent 0 28.6k on 2 of 3 28.6k
Explicit cache_control 400 30.8k 30.8k
Last reminder marked by cache_control_injection_points 0 28.9k 30.8k
Marked reply and reminder, caches made 0 0 n/a
Reminder carrying the only TTL, cache lifetime 300s 300s n/a
Cached reminder, then a tool result 200 200 n/a
Reminder between parallel tool results, Gemini 200 200 n/a
Three tool results, Anthropic 400 200 n/a
Video in a later system message, with or without explicit caching 400 400 n/a

The 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

$ NONCE=ltsbase5-c01-chat-system-reminders-1795397607 ./turns.sh 20924 chat gemini-3.8-flash B 4
[turn 1] prompt_tokens=30824 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30872 cached_tokens=0 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=30920 cached_tokens=0 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=30968 cached_tokens=0 reply=Fact 0004 ships cedar crates.  error=
Other cases

Responses API, Vertex AI, history resent, reminders

$ NONCE=ltsbase5-c03-responses-resent-reminders-1795397607 ./responses_turns.sh 20924 gemini-3.8-flash B 4
[turn 1] input_tokens=30824 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] input_tokens=30872 cached_tokens=0 reply=Fact 0002 ships linen sheets.  error=
[turn 3] input_tokens=30920 cached_tokens=0 reply=Fact 0003 ships brass gears.  error=
[turn 4] input_tokens=30968 cached_tokens=0 reply=Fact 0004 ships cedar crates.  error=

Explicit cache_control on the system prompt, Vertex AI, reminders

$ ./explicit_cache.sh 20924 gemini-3.8-flash 4 ltsbase5-c07-explicit-cache-1795397607
[turn 1] prompt_tokens=null cached_tokens=0 reply=(no text)  error="litellm.BadRequestError: Vertex_aiException BadRequestError - {\n  \"error\": {\n    \"code\": 400,\n    \"message\": \"Tool config, tools and system instruction should not be set in therequest when
[turn 2] prompt_tokens=null cached_tokens=0 reply=(no text)  error="litellm.BadRequestError: Vertex_aiException BadRequestError - {\n  \"error\": {\n    \"code\": 400,\n    \"message\": \"Tool config, tools and system instruction should not be set in therequest when
[turn 3] prompt_tokens=null cached_tokens=0 reply=(no text)  error="litellm.BadRequestError: Vertex_aiException BadRequestError - {\n  \"error\": {\n    \"code\": 400,\n    \"message\": \"Tool config, tools and system instruction should not be set in therequest when
[turn 4] prompt_tokens=null cached_tokens=0 reply=(no text)  error="litellm.BadRequestError: Vertex_aiException BadRequestError - {\n  \"error\": {\n    \"code\": 400,\n    \"message\": \"Tool config, tools and system instruction should not be set in therequest when
cachedContents listed: 11 over 1 page(s)
cachedContents created during this run: 1
  created 2026-11-23T01:35:41.476111Z tokens 30779

cache_control_injection_points marking the last reminder, Vertex AI, plain system prompt

$ ./explicit_cache_injection.sh 31707 gemini-3.8-flash 4 ltsbase6-c18-explicit-cache-injection-last-reminder-1795400549
[turn 1] prompt_tokens=30822 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30870 cached_tokens=0 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=30918 cached_tokens=0 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=30966 cached_tokens=0 reply=Fact 0004 ships cedar crates.  error=
cachedContents listed: 13 over 1 page(s)
cachedContents created during this run: 0

A marked assistant turn and a marked reminder after the first question, Vertex AI (no change expected)

$ ./explicit_cache_later_block.sh 28500 gemini-3.8-flash ltsbase7-c19-explicit-cache-later-block-ending-on-reminder-1795404633
[request 1] prompt_tokens=30841 cached_tokens=0 reply=Fact 0002 ships linen sheets.  error=
[request 2] prompt_tokens=30841 cached_tokens=28794 reply=According to Fact 0002, the Cebu depot ships linen sheets.  error=
cachedContents listed: 3 over 1 page(s)
cachedContents created during this run: 0

A marked system prompt and a marked reminder carrying the only TTL, Vertex AI (no change expected)

$ ./explicit_cache_reminder_ttl_marked_system.sh 26655 gemini-3.8-flash ltsbase8-c21-explicit-cache-reminder-ttl-marked-system-1795410082
[request 1] prompt_tokens=61652 cached_tokens=30819 reply=Fact 0002 ships linen sheets.  error=
[request 2] prompt_tokens=30833 cached_tokens=30819 reply=According to Fact 0002, the Cebu depot ships linen sheets.  error=
cachedContents listed: 4 over 1 page(s)
cachedContents created during this run: 1
  created 2026-11-23T05:01:24.746921Z tokens 30819 lives 300s

A cached reminder, then a reminder and a tool result

$ ./toolcall_cached.sh 20924 gemini-3.8-flash ltsbase5-c16-explicit-cache-reminders-before-tool-result-1795397607
[call 1] tool_calls=1 error=
[call 2] roles sent: ["system","user","assistant","system","system","tool"] cached: [true,true,true,true,false,false]
[call 2] http=200 prompt_tokens=30870 reply=The weather in Paris right now is 18°C and sunny.  error=

A reminder between two parallel tool results, Gemini

$ ./toolcall.sh 20924 gemini-3.8-flash parallel
[call 1] tool_calls=2 cities=["Paris","Tokyo"] error=
[call 2] roles sent: ["system","user","assistant","tool","system","tool"]
[call 2] http=200 reply=* **Paris:** 18°C and sunny * **Tokyo:** 18°C and sunny  error=

Three tool results with a reminder between each, Anthropic

$ ./toolcall3.sh 20924 claude-sonnet-4-6
[call 1] tool_calls=3 cities=["Paris","Tokyo","Lima"] error=
[call 2] roles sent: ["system","user","assistant","tool","system","tool","system","tool"]
[call 2] http=400 reply= error="litellm.BadRequestError: AnthropicException - {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"messages.2: `tool_use` ids were found without `tool_result` blocks immediately after: toolu_01TBH9iRXy7kW42uajqcEDaB. Each `tool_use` block must have a corresponding `tool_r

A video in a later system message

$ ./sysvideo.sh 20924 gemini-3.8-flash
http=400 error=litellm.BadRequestError: Gemini system instructions take text only. Move the video to a user message or set drop_params=True.

LiteLLM: model group 'gemini-3.8-flash' failed with the error above. No fallback was attempted. reply=

A video in a later system message, with explicit caching

$ ./sysvideo_cached.sh 20924 gemini-3.8-flash ltsbase5-c14-explicit-cache-system-video-400-1795397607
http=400 error=litellm.BadRequestError: Gemini system instructions take text only. Move the video to a user message or set drop_params=True.

LiteLLM: model group 'gemini-3.8-flash' failed with the error above. No fallback was attempted. reply=

After (5ceb9c2)

Chat completions, Vertex AI, a reminder after each user turn

$ NONCE=ltshead8-c01-chat-system-reminders-1795409388 ./turns.sh 31977 chat gemini-3.8-flash B 4
[turn 1] prompt_tokens=30845 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30914 cached_tokens=28627 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=30983 cached_tokens=28618 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=31052 cached_tokens=28609 reply=Fact 0004 ships cedar crates.  error=
Other cases

Responses API, Vertex AI, history resent, reminders

$ NONCE=ltshead8-c03-responses-resent-reminders-1795409388 ./responses_turns.sh 31977 gemini-3.8-flash B 4
[turn 1] input_tokens=30845 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] input_tokens=30914 cached_tokens=28627 reply=Fact 0002 ships linen sheets.  error=
[turn 3] input_tokens=30983 cached_tokens=28618 reply=Fact 0003 ships brass gears.  error=
[turn 4] input_tokens=31052 cached_tokens=0 reply=Fact 0004 ships cedar crates.  error=

Explicit cache_control on the system prompt, Vertex AI, reminders

$ ./explicit_cache.sh 31977 gemini-3.8-flash 4 ltshead8-c07-explicit-cache-1795409388
[turn 1] prompt_tokens=61616 cached_tokens=30779 reply=According to Fact 0001, the Kobe depot ships brass gears.  error=
[turn 2] prompt_tokens=30912 cached_tokens=30779 reply=According to Fact 0002, the Cebu depot ships linen sheets.  error=
[turn 3] prompt_tokens=30987 cached_tokens=30779 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=31056 cached_tokens=30779 reply=Fact 0004 ships cedar crates.  error=
cachedContents listed: 6 over 1 page(s)
cachedContents created during this run: 1
  created 2026-11-23T04:50:48.028365Z tokens 30779

cache_control_injection_points marking the last reminder, Vertex AI, plain system prompt

$ ./explicit_cache_injection.sh 31977 gemini-3.8-flash 4 ltshead8-c18-explicit-cache-injection-last-reminder-1795409388
[turn 1] prompt_tokens=30842 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30911 cached_tokens=28785 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=30980 cached_tokens=28854 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=31049 cached_tokens=28924 reply=Fact 0004 ships cedar crates.  error=
cachedContents listed: 5 over 1 page(s)
cachedContents created during this run: 0

A marked assistant turn and a marked reminder after the first question, Vertex AI (no change expected)

$ ./explicit_cache_later_block.sh 31977 gemini-3.8-flash ltshead8-c19-explicit-cache-later-block-ending-on-reminder-1795409388
[request 1] prompt_tokens=30862 cached_tokens=0 reply=Fact 0002 ships linen sheets.  error=
[request 2] prompt_tokens=30862 cached_tokens=28627 reply=Fact 0002 ships linen sheets.  error=
cachedContents listed: 5 over 1 page(s)
cachedContents created during this run: 0

A marked system prompt and a marked reminder carrying the only TTL, Vertex AI (no change expected)

$ ./explicit_cache_reminder_ttl_marked_system.sh 31977 gemini-3.8-flash ltshead8-c21-explicit-cache-reminder-ttl-marked-system-1795410082
[request 1] prompt_tokens=61654 cached_tokens=30800 reply=Fact 0002 ships linen sheets.  error=
[request 2] prompt_tokens=30854 cached_tokens=30800 reply=Fact 0002 ships linen sheets.  error=
cachedContents listed: 5 over 1 page(s)
cachedContents created during this run: 1
  created 2026-11-23T05:01:42.627077Z tokens 30800 lives 300s

A cached reminder, then a reminder and a tool result

$ ./toolcall_cached.sh 31977 gemini-3.8-flash ltshead8-c16-explicit-cache-reminders-before-tool-result-1795409388
[call 1] tool_calls=1 error=
[call 2] roles sent: ["system","user","assistant","system","system","tool"] cached: [true,true,true,true,false,false]
[call 2] http=200 prompt_tokens=30949 reply=The weather in Paris right now is 18°C and sunny.  error=

A reminder between two parallel tool results, Gemini

$ ./toolcall.sh 31977 gemini-3.8-flash parallel
[call 1] tool_calls=2 cities=["Paris","Tokyo"] error=
[call 2] roles sent: ["system","user","assistant","tool","system","tool"]
[call 2] http=200 reply=It is currently 18°C and sunny in both Paris and Tokyo.  error=

Three tool results with a reminder between each, Anthropic

$ ./toolcall3.sh 31977 claude-sonnet-4-6
[call 1] tool_calls=3 cities=["Paris","Tokyo","Lima"] error=
[call 2] roles sent: ["system","user","assistant","tool","system","tool","system","tool"]
[call 2] http=200 reply=Here's the current weather in all three cities:  | City | Temperature | Conditions | |-------|------------|------------| | **Paris** | 18°C | Sunny ☀️ | |  error=

A video in a later system message

$ ./sysvideo.sh 31977 gemini-3.8-flash
http=400 error=litellm.BadRequestError: Gemini system instructions take text only. Move the video to a user message or set drop_params=True.

LiteLLM: model group 'gemini-3.8-flash' failed with the error above. No fallback was attempted. reply=

A video in a later system message, with explicit caching

$ ./sysvideo_cached.sh 31977 gemini-3.8-flash ltshead8-c14-explicit-cache-system-video-400-1795409388
http=400 error=litellm.BadRequestError: Gemini system instructions take text only. Move the video to a user message or set drop_params=True.

LiteLLM: model group 'gemini-3.8-flash' failed with the error above. No fallback was attempted. reply=

Direct (the yardstick)

Direct calls

Chat, Vertex AI

$ NONCE=direct-lts5-c01-chat-system-reminders-1795397607 ./direct.sh vertex gemini-3.8-flash B 4
[turn 1] direct promptTokenCount=30825 cachedContentTokenCount=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] direct promptTokenCount=30873 cachedContentTokenCount=28627 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct promptTokenCount=30921 cachedContentTokenCount=28618 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct promptTokenCount=30969 cachedContentTokenCount=28609 reply=Fact 0004 ships cedar crates.  error=

Responses, history resent

$ NONCE=direct-lts5-c03-responses-resent-reminders-1795397607 ./direct.sh vertex gemini-3.8-flash B 4
[turn 1] direct promptTokenCount=30825 cachedContentTokenCount=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] direct promptTokenCount=30873 cachedContentTokenCount=28627 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct promptTokenCount=30921 cachedContentTokenCount=28618 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct promptTokenCount=30969 cachedContentTokenCount=28609 reply=Fact 0004 ships cedar crates.  error=

Explicit cache

$ ./direct_explicit.sh gemini-3.8-flash 4 direct-lts5-c07-explicit-cache-1795397607
[create] cachedContent createTime=2026-11-23T01:36:21.958346Z tokens=30779 error=
[turn 1] direct promptTokenCount=30816 cachedContentTokenCount=30779 reply=Fact 0001 ships brass gears.  error=
[turn 2] direct promptTokenCount=30864 cachedContentTokenCount=30779 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct promptTokenCount=30912 cachedContentTokenCount=30779 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct promptTokenCount=30960 cachedContentTokenCount=30779 reply=Fact 0004 ships cedar crates.  error=
cachedContents listed: 13 over 1 page(s)
cachedContents created during this run: 1
  created 2026-11-23T01:36:21.958346Z tokens 30779

Explicit cache, last reminder marked

$ ./direct_explicit.sh gemini-3.8-flash 4 direct-lts6-c18-explicit-cache-injection-last-reminder-1795400549
[create] cachedContent createTime=2026-11-23T02:23:17.070574Z tokens=30785 error=
[turn 1] direct promptTokenCount=30822 cachedContentTokenCount=30785 reply=Fact 0001 ships brass gears.  error=
[turn 2] direct promptTokenCount=30870 cachedContentTokenCount=30785 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct promptTokenCount=30918 cachedContentTokenCount=30785 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct promptTokenCount=30966 cachedContentTokenCount=30785 reply=Fact 0004 ships cedar crates.  error=
cachedContents listed: 14 over 1 page(s)
cachedContents created during this run: 1
  created 2026-11-23T02:23:17.070574Z tokens 30785
Differences from the main PR
  • This line has no string_field helper, so a small _part_text reads the text of a content part
  • This line caches only the first continuous cache_control block, since fix(openai): stop stripping cache_control from the caller's own messages and tools #35602 is not here
    • So a leading system message outside that block stays the system_instruction, as before
    • The second pick skips the operator note for models without system message support on the later messages only, since the leading run is never converted on this line
Main commit LTS commit
f5faf84 5f4656d
9e32989 f8baf03
4d76ae7 255b426
25020eb 3424ee5
050efcd 474197a
a1a8d15 5ceb9c2

Each branch then merges its own base. The main merge 4459641 and the LTS merge 7649c82 resolve the same conflict in transform_system_message with the same code. The second pick had conflicts in separate_cached_messages and in nearby lines that differ on this line, like the imports and model in place of target.model, and keeps the same behavior. The third pick had conflicts in the _cached_block_end docstring and in the cache entry points, where this line keeps its own skip logic and calls the new video helper in place of reject_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 reason

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • A user can imitate any later system message, Lakera's inject_system_message warning included, by typing the operator note
    • Bedrock and Anthropic without the beta already send later system messages this way
    • The Responses API instructions field still goes to systemInstruction

Low

  • The operator note adds about 21 input tokens per converted message
  • An image, file or audio part in a later system message is still dropped silently
  • A later reminder marked with cache_control at either end of the cached block stays out of the cache, though its TTL applies
  • The operator note calls a lone late system prompt a reminder too
  • A follow-up adds the Gemini row to the docs
Decisions
  • A later system message becomes a user turn in place, prefixed with the operator note
    • Gemini contents only take user and model roles, so there is no native slot to keep it as system
    • This is the existing litellm convention for Bedrock Converse and Anthropic models without the mid-conversation system beta, so there is no new flag
    • I did not send it as a model turn, since the model would read it as its own words, and dropping it would lose the agent's instruction
    • The note adds about 21 input tokens per converted message
  • A reminder between a tool call and its results goes after the last function response
    • Gemini rejects a user turn between a functionCall and its functionResponse, and on this line the model echoed a reminder placed there
    • The fix lives in the shared helper, so Anthropic models without the beta get the same ordering when a reminder sits between parallel tool results
  • Explicit caching keeps the first continuous cache_control block in the cache, and later reminders go into the request as user turns
    • generateContent rejects system_instruction next to cachedContent, which is the 400 Before shows
    • A later system run that starts or ends the cached block, like a reminder cache_control_injection_points marks 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 order
  • The cache TTL is read before later reminders are trimmed off the marked block, and the cache key gets a TTL suffix only when the cached messages lack it, so existing keys stay the same
  • A leading system message with no content used to raise a KeyError and is now left out of the request
  • For models with system message support, a video_url in any system message still answers 400 unless drop_params is 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 text
  • An empty mid-conversation system message is dropped, since Gemini rejects an empty part
  • Models without system message support get their later system messages as plain user text with or without explicit caching, so the cache path does not add the operator note there, and a video still goes through
  • A guardrail advisory appended as a system message, like Lakera's inject_system_message mode, now reaches Gemini as an operator-noted user turn, the same as on Bedrock and on Anthropic without the beta
    • Hoisting trailing system messages into systemInstruction would 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 fixes

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
Bugbot summary

[!NOTE]
Medium Risk
Changes core Gemini/Vertex message shaping and explicit cache boundaries; mid-conversation system content now reaches the model as operator-noted user parts, which is an intentional behavior change with caching and ordering implications.

Overview
Gemini/Vertex no longer hoist every system message into system_instruction. Only the leading system run becomes system_instruction; later reminders are converted to user turns in place (with the operator note), so the prompt prefix stays stable and implicit/explicit caching can hit on multi-turn agents.

Explicit cache_control splitting is reworked: later system messages are trimmed from the cached block, converted for the live request via place_mid_conversation_system, and TTL is read via cached_block_ttl before trimming so reminder-only TTLs still apply. Cache keys now vary when TTL differs.

Tool-turn ordering: system messages mixed among one tool call’s results are placed after the last tool_result, including parallel tool calls (shared mid_conversation_system helper change).

Validation: reject_system_message_videos is centralized and run on the context-caching path before cache creation.

Reviewed by Cursor Bugbot for commit 5ceb9c2. Bugbot is set up for automated code reviews on this repo. Configure here.

…_keep_mid_conversation_system_inline_lts

# Conflicts:
#	litellm/llms/vertex_ai/gemini/transformation.py
#	tests/unit/llms/vertex_ai/gemini/test_transformation.py
@izzybn
izzybn requested a review from a team November 22, 2026 23:22
@veria-ai

veria-ai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

This 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),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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)
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
...m/llms/vertex_ai/context_caching/transformation.py 96.87% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The changes since the previous review appear safe to merge

Summary

Gemini and Vertex AI keep later system reminders in the conversation instead of moving them into system_instruction

The latest update preserves ttl when a reminder is trimmed from the cached block. Both sync and async requests pass that value into cache creation, and different effective lifetimes get different cache keys

No new actionable issues were found in the changes since the previous review

  • Gemini keeps later system reminders in their place in the conversation.
  • Explicit Gemini caches leave later reminders in the live request.
  • Tool reminders wait until all results in that call arrive.

Reviews (5) · Last reviewed commit: "fix(gemini): keep the ttl of a reminder ..." · Reviewed by Greptile

…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)
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…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)
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…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)
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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.

@mateo-berri mateo-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@mateo-berri
mateo-berri merged commit f69cbe5 into BerriAI:lts/1.108.x Nov 23, 2026
62 checks passed
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