Skip to content

fix(gemini): keep mid-conversation system messages in place so prompt caching survives - #53623

Merged
mateo-berri merged 8 commits into
BerriAI:mainfrom
owen-hj:litellm_gemini_keep_mid_conversation_system_inline
Nov 23, 2026
Merged

mateo-berri merged 8 commits into
BerriAI:mainfrom
owen-hj:litellm_gemini_keep_mid_conversation_system_inline

Conversation

@owen-hj

@owen-hj owen-hj 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 made a new cachedContent every turn

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

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. Later turns show 0 too, also with streaming, on /v1/responses and on gemini/ models

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

  1. Steps 1 and 2 are the same as Before
  2. On the next turn cached_tokens is now 28,781, where the direct call reads 28,762
  3. Later turns hit the cache too, also with streaming, on /v1/responses and on gemini/ models

Relevant 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

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

Case Before After Direct
Chat, Vertex 0 28.9k 28.8k
Chat stream, Vertex 0 28.6k on 2 of 3 28.8k on 2 of 3
Responses, history resent 0 28.9k 28.6k
Responses, previous_response_id 0 28.6k 28.8k
Chat, Gemini API 0 28.9k on 2 of 3 28.9k on 2 of 3
Chat, developer role 0 28.6k 28.8k
Chat, Vertex gemini-4-neon 0 28.9k on 2 of 3 29k on 2 of 3
Explicit cache_control, caches made 4 1 1
Explicit, prompt tokens 61.8k 31k 30.9k
Last reminder marked by cache_control_injection_points, caches made 4 1 1
Marked reply and reminder, caches made 0 0 n/a
Reminder carrying the only TTL, cache lifetime 300s 300s n/a
Chat, no reminders (control) 28.8k 28.8k 28.6k
Claude Code, /cost cache read 54.5k 54.5k n/a
Cached reminder, then a tool result 200 200 n/a
Reminder before or between tool results, Gemini 200 200 n/a
Three tool results, Anthropic and Vertex Claude 400 200 n/a
Video in a later system message, with or without explicit caching 400 400 n/a

Anthropic 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_KEY and ANTHROPIC_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 with ANTHROPIC_BASE_URL set to the proxy and every model alias set to gemini-3.8-flash (cc_leg.sh in the gist). The previous_response_id case runs on its own proxies with a database per leg and store_prompts_in_spend_logs: true (config-db3.yaml in the gist)

model_list:
  - model_name: gemini-3.8-flash
    litellm_params:
      model: vertex_ai/gemini-3.8-flash
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: global
  - model_name: gemini-api-3.8-flash
    litellm_params:
      model: gemini/gemini-3.8-flash
      api_key: os.environ/GEMINI_API_KEY
  - model_name: claude-sonnet-4-6
    litellm_params:
      model: anthropic/claude-sonnet-4-6
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: vertex-claude-sonnet-4-6
    litellm_params:
      model: vertex_ai/claude-sonnet-4-6
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: global
  - model_name: gemini-4-neon
    litellm_params:
      model: vertex_ai/gemini-4-neon
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: global
PYTHON_DOTENV_DISABLED=1 LITELLM_LOCAL_MODEL_COST_MAP=True python litellm/proxy/proxy_cli.py --config config.yaml --port <port> --num_workers 2 --timeout_worker_healthcheck 600

Before (c345f50)

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

$ NONCE=base5-c01-chat-system-reminders-1795396984 ./turns.sh 23127 chat gemini-3.8-flash B 4
[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=
Other cases

Chat completions with "stream": true, Vertex AI, reminders

$ NONCE=base5-c02-chat-stream-reminders-1795396984 ./turns_stream.sh 23127 gemini-3.8-flash B 4
[turn 1] stream chunks=5 prompt_tokens=30822 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] stream chunks=5 prompt_tokens=30870 cached_tokens=0 reply=Fact 0002 ships linen sheets.  error=
[turn 3] stream chunks=5 prompt_tokens=30918 cached_tokens=0 reply=Fact 0003 ships brass gears.  error=
[turn 4] stream chunks=5 prompt_tokens=30966 cached_tokens=0 reply=Fact 0004 ships cedar crates.  error=

Responses API, Vertex AI, history resent, reminders

$ NONCE=base5-c03-responses-resent-reminders-1795396984 ./responses_turns.sh 23127 gemini-3.8-flash B 4
[turn 1] input_tokens=30822 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] input_tokens=30870 cached_tokens=0 reply=Fact 0002 ships linen sheets.  error=
[turn 3] input_tokens=30918 cached_tokens=0 reply=Fact 0003 ships brass gears.  error=
[turn 4] input_tokens=30966 cached_tokens=0 reply=Fact 0004 ships cedar crates.  error=

Responses API, previous_response_id, prompts stored in spend logs

$ NONCE=base4-c04-responses-previous-response-id-1795395843 ./responses_prev.sh 32357 gemini-3.8-flash 4 12
[turn 1] items_sent=2 previous_response_id= input_tokens=30823 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] items_sent=2 previous_response_id=set input_tokens=30925 cached_tokens=0 reply=Fact 0002 ships linen sheets.  error=
[turn 3] items_sent=2 previous_response_id=set input_tokens=31006 cached_tokens=0 reply=Fact 0003 ships brass gears.  error=
[turn 4] items_sent=2 previous_response_id=set input_tokens=31086 cached_tokens=0 reply=Fact 0004 ships cedar crates.  error=

Chat completions, Gemini API, reminders

$ NONCE=base5-c05-chat-gemini-api-reminders-1795396984 ./turns.sh 23127 chat gemini-api-3.8-flash B 4
[turn 1] prompt_tokens=30827 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30878 cached_tokens=0 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=30929 cached_tokens=0 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=30980 cached_tokens=0 reply=Fact 0004 ships cedar crates.  error=

Chat completions, Vertex AI, developer role reminders

$ NONCE=base5-c06-chat-developer-reminders-1795396984 ./turns.sh 23127 chat gemini-3.8-flash D 4
[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=

Chat completions, Vertex AI gemini-4-neon, reminders

$ NONCE=base5-c17-gemini-4-neon-reminders-1795396984 ./turns.sh 23127 chat gemini-4-neon B 4
[turn 1] prompt_tokens=30863 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30922 cached_tokens=0 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=30981 cached_tokens=0 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=31040 cached_tokens=0 reply=Fact 0004 ships cedar crates.  error=

Explicit cache_control on the system prompt, Vertex AI, reminders

$ ./explicit_cache.sh 23127 gemini-3.8-flash 4 base5-c07-explicit-cache-1795396984
[turn 1] prompt_tokens=61612 cached_tokens=30797 reply=According to Fact 0001, the Kobe depot ships brass gears.  error=
[turn 2] prompt_tokens=61685 cached_tokens=30816 reply=According to Fact 0002, the Cebu depot ships linen sheets.  error=
[turn 3] prompt_tokens=61758 cached_tokens=30835 reply=According to Fact 0003, the Perth depot ships brass gears.  error=
[turn 4] prompt_tokens=61831 cached_tokens=30854 reply=According to Fact 0004, the Perth depot ships cedar crates.  error=
cachedContents listed: 6 over 1 page(s)
cachedContents created during this run: 4
  created 2026-11-23T01:29:14.957103Z tokens 30797
  created 2026-11-23T01:29:22.591752Z tokens 30816
  created 2026-11-23T01:29:28.859471Z tokens 30835
  created 2026-11-23T01:29:35.131017Z tokens 30854

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

$ ./explicit_cache_injection.sh 23936 gemini-3.8-flash 4 base6-c18-explicit-cache-injection-last-reminder-1795400062
[turn 1] prompt_tokens=61624 cached_tokens=30803 reply=According to Fact 0001, the Kobe depot ships brass gears.  error=
[turn 2] prompt_tokens=61697 cached_tokens=30822 reply=According to Fact 0002, the Cebu depot ships linen sheets.  error=
[turn 3] prompt_tokens=61770 cached_tokens=30841 reply=According to Fact 0003, the Perth depot ships brass gears.  error=
[turn 4] prompt_tokens=61843 cached_tokens=30860 reply=According to Fact 0004, the Perth depot ships cedar crates.  error=
cachedContents listed: 11 over 1 page(s)
cachedContents created during this run: 4
  created 2026-11-23T02:14:23.902847Z tokens 30803
  created 2026-11-23T02:14:29.988653Z tokens 30822
  created 2026-11-23T02:14:36.324518Z tokens 30841
  created 2026-11-23T02:14:42.740591Z tokens 30860

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

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

A marked reminder carrying the only TTL, Vertex AI (no change expected)

$ ./explicit_cache_reminder_ttl.sh 21437 gemini-3.8-flash base8-c20-explicit-cache-reminder-carries-the-only-ttl-1795407778
[request 1] prompt_tokens=61654 cached_tokens=30820 reply=According to Fact 0002, the depot ships linen sheets.  error=
[request 2] prompt_tokens=30834 cached_tokens=30820 reply=Fact 0002 ships linen sheets.  error=
cachedContents listed: 2 over 1 page(s)
cachedContents created during this run: 1
  created 2026-11-23T04:23:00.638235Z tokens 30820 lives 300s

Chat completions, Vertex AI, no reminders (control)

$ NONCE=base5-c09-chat-no-reminders-1795396984 ./turns.sh 23127 chat gemini-3.8-flash A 4
[turn 1] prompt_tokens=30803 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30832 cached_tokens=28741 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=30861 cached_tokens=28775 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=30890 cached_tokens=28805 reply=Fact 0004 ships cedar crates.  error=

Claude Code TUI on /v1/messages, four turns, then /cost (no change expected)

$ ./cc_leg.sh 23127 base5-c15-claude-code-1795396984
== replies
● Mercury
● Venus
● Earth
● Mars
== /cost
   Usage by model:
       gemini-3.8-flash:  11.3k input, 565 output, 54.5k cache read, 13.6k cache write ($0.1828)
   Prompt cache (main):   4 requests · 69% of input tokens from cache · 3 misses (last 3s ago, 0 tokens re-cached) · warm (5m
   TTL, last activity 3s ago)

A cached reminder, then a reminder and a tool result

$ ./toolcall_cached.sh 23127 gemini-3.8-flash base5-c16-explicit-cache-reminders-before-tool-result-1795396984
[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=30889 reply=The current weather in Paris is 18°C and sunny.  error=

A reminder between a tool call and its result, Gemini

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

A reminder between two parallel tool results, Gemini

$ ./toolcall.sh 23127 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 23127 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_01DiReukSLvtVorQWUnFiLeK. Each `tool_use` block must have a corresponding `tool_r

Three tool results with a reminder between each, Vertex AI Claude

$ ./toolcall3.sh 23127 vertex-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: Vertex_aiException BadRequestError - {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"messages.2: `tool_use` ids were found without `tool_result` blocks immediately after: toolu_vrtx_01T7uHidTXCiND1WxkGkTnzR. Each `tool_use` block must have a

A video in a later system message

$ ./sysvideo.sh 23127 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 23127 gemini-3.8-flash base5-c14-explicit-cache-system-video-400-1795396984
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 (a1a8d15)

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

$ NONCE=head8-c01-chat-system-reminders-1795407778 ./turns.sh 25813 chat gemini-3.8-flash B 4
[turn 1] prompt_tokens=30843 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30912 cached_tokens=28781 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=30981 cached_tokens=28855 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=31050 cached_tokens=28925 reply=Fact 0004 ships cedar crates.  error=
Other cases

Chat completions with "stream": true, Vertex AI, reminders

$ NONCE=head8-c02-chat-stream-reminders-1795407778 ./turns_stream.sh 25813 gemini-3.8-flash B 4
[turn 1] stream chunks=5 prompt_tokens=30843 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] stream chunks=5 prompt_tokens=30912 cached_tokens=28627 reply=Fact 0002 ships linen sheets.  error=
[turn 3] stream chunks=4 prompt_tokens=30981 cached_tokens=28618 reply=Fact 0003 ships brass gears.  error=
[turn 4] stream chunks=4 prompt_tokens=31050 cached_tokens=0 reply=Fact 0004 ships cedar crates.  error=

Responses API, Vertex AI, history resent, reminders

$ NONCE=head8-c03-responses-resent-reminders-1795407778 ./responses_turns.sh 25813 gemini-3.8-flash B 4
[turn 1] input_tokens=30843 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] input_tokens=30912 cached_tokens=28781 reply=Fact 0002 ships linen sheets.  error=
[turn 3] input_tokens=30981 cached_tokens=28855 reply=Fact 0003 ships brass gears.  error=
[turn 4] input_tokens=31050 cached_tokens=28925 reply=Fact 0004 ships cedar crates.  error=

Responses API, previous_response_id, prompts stored in spend logs

$ NONCE=head8-c04-responses-previous-response-id-1795409189 ./responses_prev.sh 23659 gemini-3.8-flash 4 12
[turn 1] items_sent=2 previous_response_id= input_tokens=30844 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] items_sent=2 previous_response_id=set input_tokens=30913 cached_tokens=28623 reply=Fact 0002 ships linen sheets.  error=
[turn 3] items_sent=2 previous_response_id=set input_tokens=30982 cached_tokens=28611 reply=Fact 0003 ships brass gears.  error=
[turn 4] items_sent=2 previous_response_id=set input_tokens=31051 cached_tokens=28598 reply=Fact 0004 ships cedar crates.  error=

Chat completions, Gemini API, reminders

$ NONCE=head8-c05-chat-gemini-api-reminders-1795407778 ./turns.sh 25813 chat gemini-api-3.8-flash B 4
[turn 1] prompt_tokens=30848 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30920 cached_tokens=28788 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=30992 cached_tokens=0 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=31064 cached_tokens=28986 reply=Fact 0004 ships cedar crates.  error=

Chat completions, Vertex AI, developer role reminders

$ NONCE=head8-c06-chat-developer-reminders-1795407778 ./turns.sh 25813 chat gemini-3.8-flash D 4
[turn 1] prompt_tokens=30843 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30912 cached_tokens=28627 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=30981 cached_tokens=28618 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=31050 cached_tokens=28609 reply=Fact 0004 ships cedar crates.  error=

Chat completions, Vertex AI gemini-4-neon, reminders

$ NONCE=head8-c17-gemini-4-neon-reminders-1795407778 ./turns.sh 25813 chat gemini-4-neon B 4
[turn 1] prompt_tokens=30883 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30962 cached_tokens=28826 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=31041 cached_tokens=28913 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=31821 cached_tokens=0 reply=Fact 0004 ships cedar crates.  error=

Explicit cache_control on the system prompt, Vertex AI, reminders

$ ./explicit_cache.sh 25813 gemini-3.8-flash 4 head8-c07-explicit-cache-1795407778
[turn 1] prompt_tokens=61612 cached_tokens=30777 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30904 cached_tokens=30777 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=30973 cached_tokens=30777 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=31042 cached_tokens=30777 reply=Fact 0004 ships cedar crates.  error=
cachedContents listed: 4 over 1 page(s)
cachedContents created during this run: 1
  created 2026-11-23T04:24:06.961349Z tokens 30777

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

$ ./explicit_cache_injection.sh 25813 gemini-3.8-flash 4 head8-c18-explicit-cache-injection-last-reminder-1795407778
[turn 1] prompt_tokens=61624 cached_tokens=30783 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30910 cached_tokens=30783 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=30979 cached_tokens=30783 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=31048 cached_tokens=30783 reply=Fact 0004 ships cedar crates.  error=
cachedContents listed: 3 over 1 page(s)
cachedContents created during this run: 1
  created 2026-11-23T04:23:47.045999Z tokens 30783

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

$ ./explicit_cache_later_block.sh 25813 gemini-3.8-flash head8-c19-explicit-cache-later-block-ending-on-reminder-1795407778
[request 1] prompt_tokens=30860 cached_tokens=0 reply=According to Fact 0002, the Cebu depot ships linen sheets.  error=
[request 2] prompt_tokens=30860 cached_tokens=28813 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 reminder carrying the only TTL, Vertex AI (no change expected)

$ ./explicit_cache_reminder_ttl.sh 25813 gemini-3.8-flash head8-c20-explicit-cache-reminder-carries-the-only-ttl-1795407778
[request 1] prompt_tokens=61656 cached_tokens=30801 reply=According to Fact 0002, the Cebu depot ships linen sheets.  error=
[request 2] prompt_tokens=30855 cached_tokens=30801 reply=Fact 0002 ships linen sheets.  error=
cachedContents listed: 3 over 1 page(s)
cachedContents created during this run: 1
  created 2026-11-23T04:23:19.716554Z tokens 30801 lives 300s

Chat completions, Vertex AI, no reminders (control)

$ NONCE=head8-c09-chat-no-reminders-1795407778 ./turns.sh 25813 chat gemini-3.8-flash A 4
[turn 1] prompt_tokens=30803 cached_tokens=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] prompt_tokens=30832 cached_tokens=28741 reply=Fact 0002 ships linen sheets.  error=
[turn 3] prompt_tokens=30861 cached_tokens=28775 reply=Fact 0003 ships brass gears.  error=
[turn 4] prompt_tokens=30890 cached_tokens=28805 reply=Fact 0004 ships cedar crates.  error=

Claude Code TUI on /v1/messages, four turns, then /cost (no change expected)

$ ./cc_leg.sh 25813 head8-c15-claude-code-1795407778
== replies
● Mercury
● Venus
● Earth
● Mars
== /cost
   Usage by model:
       gemini-3.8-flash:  11.3k input, 704 output, 54.5k cache read, 13.6k cache write ($0.1863)
   Prompt cache (main):   4 requests · 69% of input tokens from cache · 3 misses (last 7s ago, 0 tokens re-cached) · warm (5m
   TTL, last activity 7s ago)

A cached reminder, then a reminder and a tool result

$ ./toolcall_cached.sh 25813 gemini-3.8-flash head8-c16-explicit-cache-reminders-before-tool-result-1795407778
[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=30940 reply=The weather in Paris right now is sunny and 18°C.  error=

A reminder between a tool call and its result, Gemini

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

A reminder between two parallel tool results, Gemini

$ ./toolcall.sh 25813 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=The weather is 18°C and sunny in both Paris and Tokyo right now.  error=

Three tool results with a reminder between each, Anthropic

$ ./toolcall3.sh 25813 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 across all three cities:  | City | Temperature | Condition | |-------|-------------|-----------| | 🇫🇷 **Paris** | 18°C | Sunny error=

Three tool results with a reminder between each, Vertex AI Claude

$ ./toolcall3.sh 25813 vertex-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 25813 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 25813 gemini-3.8-flash head8-c14-explicit-cache-system-video-400-1795407778
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-round5-c01-chat-system-reminders-1795396984 ./direct.sh vertex gemini-3.8-flash B 4
[turn 1] direct promptTokenCount=30824 cachedContentTokenCount=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] direct promptTokenCount=30872 cachedContentTokenCount=28762 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct promptTokenCount=30920 cachedContentTokenCount=28815 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct promptTokenCount=30968 cachedContentTokenCount=28864 reply=Fact 0004 ships cedar crates.  error=

Stream

$ NONCE=direct-round5-c02-chat-stream-reminders-1795396984 ./direct.sh vertex gemini-3.8-flash B 4 stream
[turn 1] direct stream chunks=3 promptTokenCount=30824 cachedContentTokenCount=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] direct stream chunks=2 promptTokenCount=30872 cachedContentTokenCount=28762 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct stream chunks=3 promptTokenCount=30920 cachedContentTokenCount=28815 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct stream chunks=3 promptTokenCount=30968 cachedContentTokenCount=0 reply=Fact 0004 ships cedar crates.  error=

Responses, history resent

$ NONCE=direct-round5-c03-responses-resent-reminders-1795396984 ./direct.sh vertex gemini-3.8-flash B 4
[turn 1] direct promptTokenCount=30824 cachedContentTokenCount=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] direct promptTokenCount=30872 cachedContentTokenCount=28627 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct promptTokenCount=30920 cachedContentTokenCount=28618 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct promptTokenCount=30968 cachedContentTokenCount=28609 reply=Fact 0004 ships cedar crates.  error=

previous_response_id

$ NONCE=direct-db4-c04-responses-previous-response-id-1795395843 ./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=28763 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct promptTokenCount=30921 cachedContentTokenCount=28816 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct promptTokenCount=30969 cachedContentTokenCount=28865 reply=Fact 0004 ships cedar crates.  error=

Gemini API

$ NONCE=direct-round5-c05-chat-gemini-api-reminders-1795396984 ./direct.sh gemini gemini-3.8-flash B 4
[turn 1] direct promptTokenCount=30829 cachedContentTokenCount=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] direct promptTokenCount=30880 cachedContentTokenCount=0 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct promptTokenCount=30931 cachedContentTokenCount=28873 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct promptTokenCount=30982 cachedContentTokenCount=28877 reply=Fact 0004 ships cedar crates.  error=

developer role

$ NONCE=direct-round5-c06-chat-developer-reminders-1795396984 ./direct.sh vertex gemini-3.8-flash D 4
[turn 1] direct promptTokenCount=30805 cachedContentTokenCount=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] direct promptTokenCount=30834 cachedContentTokenCount=28743 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct promptTokenCount=30863 cachedContentTokenCount=28777 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct promptTokenCount=30892 cachedContentTokenCount=28807 reply=Fact 0004 ships cedar crates.  error=

gemini-4-neon

$ NONCE=direct-round5-c17-gemini-4-neon-reminders-1795396984 ./direct.sh vertex gemini-4-neon B 4
[turn 1] direct promptTokenCount=30864 cachedContentTokenCount=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] direct promptTokenCount=30922 cachedContentTokenCount=28807 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct promptTokenCount=31681 cachedContentTokenCount=0 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct promptTokenCount=31739 cachedContentTokenCount=29632 reply=Fact 0004 ships cedar crates.  error=

Explicit cache

$ ./direct_explicit.sh gemini-3.8-flash 4 direct-round5-c07-explicit-cache-1795396984
[create] cachedContent createTime=2026-11-23T01:30:10.059408Z tokens=30778 error=
[turn 1] direct promptTokenCount=30815 cachedContentTokenCount=30778 reply=Fact 0001 ships brass gears.  error=
[turn 2] direct promptTokenCount=30863 cachedContentTokenCount=30778 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct promptTokenCount=30911 cachedContentTokenCount=30778 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct promptTokenCount=30959 cachedContentTokenCount=30778 reply=Fact 0004 ships cedar crates.  error=
cachedContents listed: 8 over 1 page(s)
cachedContents created during this run: 1
  created 2026-11-23T01:30:10.059408Z tokens 30778

Explicit cache, last reminder marked

$ ./direct_explicit.sh gemini-3.8-flash 4 direct-round6-c18-explicit-cache-injection-last-reminder-1795400062
[create] cachedContent createTime=2026-11-23T02:15:13.948762Z tokens=30784 error=
[turn 1] direct promptTokenCount=30821 cachedContentTokenCount=30784 reply=Fact 0001 ships brass gears.  error=
[turn 2] direct promptTokenCount=30869 cachedContentTokenCount=30784 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct promptTokenCount=30917 cachedContentTokenCount=30784 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct promptTokenCount=30965 cachedContentTokenCount=30784 reply=Fact 0004 ships cedar crates.  error=
cachedContents listed: 13 over 1 page(s)
cachedContents created during this run: 1
  created 2026-11-23T02:15:13.948762Z tokens 30784

No reminders

$ NONCE=direct-round5-c09-chat-no-reminders-1795396984 ./direct.sh vertex gemini-3.8-flash A 4
[turn 1] direct promptTokenCount=30805 cachedContentTokenCount=0 reply=Fact 0001 ships brass gears.  error=
[turn 2] direct promptTokenCount=30834 cachedContentTokenCount=28627 reply=Fact 0002 ships linen sheets.  error=
[turn 3] direct promptTokenCount=30863 cachedContentTokenCount=28618 reply=Fact 0003 ships brass gears.  error=
[turn 4] direct promptTokenCount=30892 cachedContentTokenCount=28609 reply=Fact 0004 ships cedar crates.  error=

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, which also answers the flag request on fix(vertex_ai): keep mid-conversation system messages inline for Gemini #42126
    • 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
    • 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
    • A Gemini-only reorder would have duplicated the helper's logic
  • Explicit caching keeps the leading system messages and the first continuous cache_control block in the cache, and later reminders go into the request
    • generateContent rejects system_instruction next to cachedContent, so a reminder in the cache would change the cache key every turn
    • 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
    • Converting reminders inside the cached contents would still change the cache key every turn
  • 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 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 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 no longer adds 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 transformation and cache key/TTL logic, which can alter prompt shape, cache hits, and billing for any conversation with mid-turn system messages.

Overview
Fixes Gemini/Vertex prompt and explicit context caching when agents send system reminders after each turn by no longer hoisting every role: system message into system_instruction.

Gemini request shaping now keeps only the leading system run in system_instruction and passes later system messages through place_mid_conversation_system as in-conversation user parts (with the existing operator note). Tool-call flows group system+tool segments so reminders land after the last function response, including parallel tool results.

Explicit cache_control / cachedContents splits messages more narrowly: cached payload is the leading system run plus the first continuous cached block, with later reminders trimmed from cache boundaries and forwarded on the live generateContent request. TTL is resolved via cached_block_ttl before trimming and folded into cache display names when it differs from cached-message TTL. Models without native system support skip operator-note conversion on the non-cached path; video in any system message is rejected on the caching path via shared reject_system_message_videos.

Unit tests cover stable prompt prefixes, reminder/cache/TTL edge cases, tool ordering, and video errors.

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

…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
@veria-ai

veria-ai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

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

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

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. Bedrock and Anthropic already send later system messages as user text. Hoisting them into systemInstruction 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

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The latest TTL changes appear safe to merge, with no new blocking finding.

Summary

Gemini keeps leading system messages in systemInstruction and sends later reminders in place with an operator note.

  • Gemini keeps later system reminders in their conversation turns.
  • Explicit Gemini caches keep later reminders outside the reusable prefix.
  • Tool results come before reminders from the same tool call.

owen-hj describes the later-message role change, its imitation risk, dropped non-text parts, ignored reminder cache marks, added tokens, and deferred docs as intentional or known caveats.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Messages with cache marks] --> B[Find leading system messages and first marked block]
    B --> C[Read TTL before trimming reminders]
    B --> D[Separate cached messages from later reminders]
    C --> E[Build cache key with selected TTL]
    D --> E
    E --> F{Cache exists?}
    F -->|Yes| G[Reuse cached content]
    F -->|No| H[Create cached content with selected TTL]
    G --> I[Send remaining turns and reminders]
    H --> I
Loading

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

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

Copy link
Copy Markdown
Contributor

@greptileai

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

Copy link
Copy Markdown
Contributor

@greptileai

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

Copy link
Copy Markdown
Contributor

@greptileai

@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 a1a8d15. 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 a2369ce into BerriAI:main Nov 23, 2026
50 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.

[Bug]: Mid-conversation system messages break Gemini/Vertex prompt caching (prefix changes every turn)

2 participants