Repository navigation
fix: preserve prompt cache for mid-conversation system on unflagged Claude models - #36968
Conversation
| def _system_role_message_as_user(self, message: dict) -> dict: | ||
| return { | ||
| **message, | ||
| "role": "user", |
There was a problem hiding this comment.
Low: Trusted instructions are downgraded to user input
Changing the role to user removes the provider-enforced priority of application-supplied system reminders. An attacker controlling a later user turn can submit contradictory instructions at the same priority and override restrictions such as tool-use or data-handling rules; the textual operator note does not restore the system trust boundary. For models that cannot accept this role in place, retain the previous top-level hoist despite the cache miss, route to a supporting model, or reject the request rather than silently weakening the instruction.
There was a problem hiding this comment.
Known tradeoff, discussed in #36559 and accepted by the maintainer: these models reject true system turns entirely, so the alternative is losing the cache
Greptile SummaryThe PR preserves prompt-cache prefixes for unflagged Claude models by converting mid-conversation system reminders into user turns while retaining leading-system hoisting and flagged-model behavior.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains; the previously reported unflagged-model cache-coverage gap is addressed by priming the cache and asserting that the reminder turn reads the complete cached prefix.
|
| Filename | Overview |
|---|---|
| litellm/llms/anthropic/experimental_pass_through/messages/transformation.py | Converts unsupported mid-conversation system messages in place and preserves tool-use/tool-result adjacency. |
| tests/e2e/llm_translation/test_messages_mid_conversation_system_e2e.py | The Bedrock unflagged-model test now primes the full cache prefix and directly checks that the reminder turn reads it back. |
| tests/e2e/llm_translation/test_messages_mid_conversation_system_native_providers_e2e.py | Azure and Vertex unflagged-model tests now assert full-prefix cache reuse, with Vertex pinned to a regional endpoint. |
| tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py | Adds focused request-shape coverage for conversion, tool-result ordering, extra-field removal, and unmapped models. |
| tests/test_litellm/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.py | Updates Azure transformation expectations for in-place conversion. |
| tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py | Updates Vertex conversion expectations and verifies leading system runs remain hoisted. |
Reviews (5): Last reviewed commit: "test(e2e): pin the unflagged Vertex cach..." | Re-trigger Greptile
PR overviewThis pull request changes Anthropic pass-through message transformation so mid-conversation system messages on unflagged Claude models are represented as user messages, preserving prompt caching instead of hoisting them to the top-level system prompt. One security concern remains open, with no issues addressed yet. The new transformation removes provider-enforced priority from application-supplied reminders, allowing a later user message to contradict them when those reminders govern behavior such as tool use or data handling. Exploitation depends on applications relying on mid-conversation system instructions for those controls. Open issues (1)
Fixed/addressed: 0 · PR risk: 4/10 |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
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 1b5e507. Configure here.
…rsation system turns
On models without supports_mid_conversation_system, a system entry between
an assistant tool_use turn and the user tool_result turn became a user turn
in that position and the provider rejected the request ("tool_use ids were
found without tool_result blocks immediately after"). That run of entries
now goes right after the tool_result turn, where consecutive user turns
merge upstream. The converted turn also carries only role and content, as
the hoist did, so an entry with extra keys no longer 400s with "Extra
inputs are not permitted".
The e2e cache priming re-sends the identical first turn until its own cache
entry reads back before the reminder turn goes out, since Vertex can take a
few seconds to serve a freshly written entry.
…/litellm into fix-anthropic-mid-conversation-system-cache
|
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 e11399f. Configure here.
mateo-berri
left a comment
There was a problem hiding this comment.
LGTM. Thanks for the contribution!
6d47468
into
BerriAI:litellm_internal_staging
…ons system prompt translate_system_message hoisted every role=system message, at any index, into the top-level system block. On a conversation carrying a mid-session reminder that rewrites the cached prefix, so the provider re-bills the whole history at cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages; the chat completions path, shared by first-party Anthropic, Vertex, Azure AI and Bedrock Invoke, still hoisted. Only the leading system run becomes the system prompt now. Later system messages go through the placement policy, and anthropic_messages_pt emits a system message instead of rejecting the role. The caller's message list is no longer mutated. Tests pin the two-turn prefix invariant across all four chat configs and both flag states.
…ons system prompt translate_system_message hoisted every role=system message, at any index, into the top-level system block. On a conversation carrying a mid-session reminder that rewrites the cached prefix, so the provider re-bills the whole history at cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages; the chat completions path, shared by first-party Anthropic, Vertex, Azure AI and Bedrock Invoke, still hoisted. Only the leading system run becomes the system prompt now. Later system messages go through the placement policy, and anthropic_messages_pt emits a system message instead of rejecting the role. The caller's message list is no longer mutated. Tests pin the two-turn prefix invariant across all four chat configs and both flag states.
…ons system prompt translate_system_message hoisted every role=system message, at any index, into the top-level system block. On a conversation carrying a mid-session reminder that rewrites the cached prefix, so the provider re-bills the whole history at cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages; the chat completions path, shared by first-party Anthropic, Vertex, Azure AI and Bedrock Invoke, still hoisted. Only the leading system run becomes the system prompt now. Later system messages go through the placement policy, and anthropic_messages_pt emits a system message instead of rejecting the role. The caller's message list is no longer mutated. Tests pin the two-turn prefix invariant across all four chat configs and both flag states.
…ons system prompt translate_system_message hoisted every role=system message, at any index, into the top-level system block. On a conversation carrying a mid-session reminder that rewrites the cached prefix, so the provider re-bills the whole history at cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages; the chat completions path, shared by first-party Anthropic, Vertex, Azure AI and Bedrock Invoke, still hoisted. Only the leading system run becomes the system prompt now. Later system messages go through the placement policy, and anthropic_messages_pt emits a system message instead of rejecting the role. The caller's message list is no longer mutated. Tests pin the two-turn prefix invariant across all four chat configs and both flag states.
…ons system prompt translate_system_message hoisted every role=system message, at any index, into the top-level system block. On a conversation carrying a mid-session reminder that rewrites the cached prefix, so the provider re-bills the whole history at cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages; the chat completions path, shared by first-party Anthropic, Vertex, Azure AI and Bedrock Invoke, still hoisted. Only the leading system run becomes the system prompt now. Later system messages go through the placement policy, and anthropic_messages_pt emits a system message instead of rejecting the role. The caller's message list is no longer mutated. Tests pin the two-turn prefix invariant across all four chat configs and both flag states.
…ons system prompt translate_system_message hoisted every role=system message, at any index, into the top-level system block. On a conversation carrying a mid-session reminder that rewrites the cached prefix, so the provider re-bills the whole history at cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages; the chat completions path, shared by first-party Anthropic, Vertex, Azure AI and Bedrock Invoke, still hoisted. Only the leading system run becomes the system prompt now. Later system messages go through the placement policy, and anthropic_messages_pt emits a system message instead of rejecting the role. The caller's message list is no longer mutated. Tests pin the two-turn prefix invariant across all four chat configs and both flag states.
…ons system prompt translate_system_message hoisted every role=system message, at any index, into the top-level system block. On a conversation carrying a mid-session reminder that rewrites the cached prefix, so the provider re-bills the whole history at cache-write pricing on every turn (BerriAI#36559). BerriAI#36968 fixed this on /v1/messages; the chat completions path, shared by first-party Anthropic, Vertex, Azure AI and Bedrock Invoke, still hoisted. Only the leading system run becomes the system prompt now. Later system messages go through the placement policy, and anthropic_messages_pt emits a system message instead of rejecting the role. The caller's message list is no longer mutated. Tests pin the two-turn prefix invariant across all four chat configs and both flag states.
…inking on chat completions (#42630) * feat(anthropic): placement policy for mid-conversation system messages Pure functions over the OpenAI-format message list: split off the leading system run, keep later system messages as role=system at a placement Anthropic accepts on models flagged supports_mid_conversation_system (after a user turn, before an assistant turn or the end, never adjacent), and convert them to user turns in place elsewhere, keeping tool_result first in a merged user turn. * fix(anthropic): keep mid-conversation system out of the chat completions system prompt translate_system_message hoisted every role=system message, at any index, into the top-level system block. On a conversation carrying a mid-session reminder that rewrites the cached prefix, so the provider re-bills the whole history at cache-write pricing on every turn (#36559). #36968 fixed this on /v1/messages; the chat completions path, shared by first-party Anthropic, Vertex, Azure AI and Bedrock Invoke, still hoisted. Only the leading system run becomes the system prompt now. Later system messages go through the placement policy, and anthropic_messages_pt emits a system message instead of rejecting the role. The caller's message list is no longer mutated. Tests pin the two-turn prefix invariant across all four chat configs and both flag states. * refactor(anthropic): single-source the converted system note The /v1/messages pass-through and the chat completions path must prefix a converted system turn with the same operator note. * test(e2e): prove the prompt cache survives a mid-conversation system reminder on chat completions Same priming and assertions as the /v1/messages cases, through /v1/chat/completions with OpenAI-format messages, for first-party Anthropic and Bedrock Invoke on a flagged (Opus 4.8) and an unflagged (Haiku 4.5) model. The reminder sits between the assistant turn and the next user turn, the shape OpenAI-style agent frameworks send, which is the placement the chat path has to translate. * test(anthropic): cover the cache_control rebuild shapes and type the test helpers Codecov flagged the 5m ttl branch and the empty-system path of the wire builder; both now have a test. Greptile asked for full typing on the new test helpers. * refactor(anthropic): read the mid-conversation flag through a public supports_ helper supports_mid_conversation_system joins the other supports_* helpers in litellm.utils, so the chat transformation stops importing the private _supports_factory. * chore(typing): declare the mid-conversation type aliases with TypeAlias The Final sweep tightened LIT010, which exempts TypeAlias declarations but counts a bare alias assignment as an unannotated binding. * fix(anthropic): let add_code_execution_tool take the pass-through message union The translator now emits role=system inside messages for models that accept it, so anthropic_messages_pt returns the pass-through union. add_code_execution_tool still declared the narrower user/assistant union while only ever reading content, so upstream's strip_advisor_blocks_from_messages call in between made the mismatch visible to the type checker. * fix(bedrock): keep mid-conversation system messages in place on converse path * fix: ruff format + multi tool_result order + regression test * fix: satisfy type-discipline gate + update osv ignore for mlflow PYSEC-2026-3865 * fix(bedrock): restore role narrowing in hoisted system loop for basedpyright budget * test(bedrock): cover mid-conversation system conversion branches - non-dict guard in _opens_with_tool_result - in-place conversion without tool context - str/list cache_control preservation in mid-conversation path - drop unreachable non-system guard in hoisted loop * Place type-discipline suppressions on the lines the gate scans * Narrow hoisted loop to system role so basedpyright sees the right TypedDict * fix(anthropic): place mid-conversation system runs by their neighbours only A run after an assistant turn now slides behind the user turn that immediately follows it, and a run that ends the array or precedes an assistant turn becomes a user turn in place. No later message can move an earlier run, so a client that replays the conversation with more turns appended sends a byte-identical prefix and preserved thinking blocks keep their binding * refactor(bedrock): share the converted system note with the anthropic module Converse imports CONVERTED_SYSTEM_NOTE instead of carrying its own copy of the same text, and the reordering helpers lose their comments * test: pin the replayed request prefix across preserved-thinking turns One test per audited feature, through the real entrypoint: the chat transformations for anthropic, bedrock invoke, vertex and converse, the modify_params dummy tool result, dotprompt with unchanged variables, and Presidio masking against an in-process fake. Each serializes system, tools and the earlier messages of turn N and N+1 and asserts they match. The e2e mid-conversation system test imports its content blocks from models.py again and is marked provider_live * fix(anthropic): move mid-conversation system placement into prompt_templates The prompt factory imported the placement helper from the Anthropic provider package, whose common_utils reads a factory constant at import time, so loading the factory first raised ImportError. The module now sits next to anthropic_messages_pt and every consumer imports core utils A user turn with content [] or None puts no block on the wire, so a system run anchored to it landed first in messages or behind an assistant turn. Such a run now converts in place; empty strings and empty text blocks still anchor because the factory fills them with a placeholder * fix(anthropic): anchor system messages only on user turns that reach the wire * fix(bedrock): type the converse system-message helpers over the message TypedDicts * fix(anthropic): read replayed pydantic messages in the Converse helpers and convert a system run whose assistant follower sends nothing A history that replays the previous turn as the litellm.Message object was invisible to the Converse system-message helpers, so a mid-conversation system stayed between a tool call and its result or reached Converse as role: system. The helpers now read fields through the shared message_field and parts_of accessors and drop the local role predicate. Flagged placement anchored a system run on any assistant follower, but anthropic_messages_pt drops an assistant turn that puts no block on the wire (content None, an empty list, an unsigned thinking part), so the system landed directly before the next user turn, which Anthropic rejects. Such a run now converts in place. An empty or whitespace text turn still anchors, since the converter pads it with a placeholder. * fix(anthropic): treat bridged encrypted reasoning as a vanishing assistant turn for system placement An assistant turn whose only blocks carry Responses API encrypted reasoning is dropped by anthropic_messages_pt, so a mid-conversation system run anchored before it landed directly before the next user turn. The unsignable-thinking predicate now lives in common_utils and both the factory and the placement policy consult it. * fix(anthropic): let an inline thinking part hide separate thinking_blocks in system placement anthropic_messages_pt skips an assistant turn's separate thinking_blocks as soon as its content list carries an inline thinking or redacted_thinking part, so a turn whose inline part is unsigned puts nothing on the wire even when the separate block is signed. The placement policy now mirrors that rule. --------- Co-authored-by: Shifat Islam Santo <shifatislamsanto764@gmail.com> Co-authored-by: ege-arhan <egearhany@gmail.com> Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
TLDR
Problem this solves:
systemHow it solves it:
User Flow
Before: a Claude Code user routed to a Vertex Claude 4.6 deployment pays full cache-write pricing every turn a reminder appears
cache_controlbreakpointsrole: "system"reminder mid-conversationusageshowscache_creation_input_tokensaround 1746 withcache_read_input_tokensdropping to 5265: the whole prior history was re-billed at cache-write pricing (reporter's real Vertex numbers in Mid-conversation system-role hoist invalidates the entire prompt-cache prefix (AnthropicMessagesConfig) #36559)After: the same session keeps its cache; only the new turn is fresh
cache_controlbreakpointsrole: "system"reminder mid-conversationusageshowscache_read_input_tokensaround 6973 withcache_creation_input_tokensaround 60: the full prior history read back from cacheRelevant issues
Fixes #36559
Linear ticket
Resolves LIT-5872
https://linear.app/litellm-ai/issue/LIT-5872/hoisting-mid-conversation-system-reminders-on-pre-48-claude
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
@greptileaito re-request a review after pushing changes)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
The changed path runs only for the partner routes (Vertex, Bedrock Invoke, Azure Foundry) behind POST /v1/messages; the first-party Anthropic route and chat completions never call it. Both legs drive the real Claude Code CLI (2.1.237) through a local proxy, one session per provider, with the proxy booted from the merge base (Before) and from this PR (After) and nothing else different
Shared setup.
config.yaml(keys come from the environment):The aliases are deliberately names Claude Code does not recognize: for those it sends its reminders as
role: "system"turns after every prompt, which is the issue's setup. For a recognized name such asclaude-sonnet-4-6it inlines them as<system-reminder>text instead, and that session read its cache fine on both legs.big.txtin the working directory is 400 lines of inventory text, about 45k tokens. Each session:then the user types, in order,
Read big.txt in full, then reply with exactly one word: done,Reply with exactly one word: thanks,Reply with exactly one word: again, and/cost. Every session answereddone,thanks,againon both legs. Per-response usage below comes from the session transcript Claude Code writes for the user (cache_read_input_tokens / cache_creation_input_tokens, one line per response):Before (6fcdea0)
Vertex (vertex-sonnet-4-6)
claude --model vertex-sonnet-4-6 --strict-mcp-config --mcp-config '{"mcpServers":{}}', then the three prompts0 / 48827,0 / 64609,42868 / 22089,42868 / 22439. The read never grows past the first breakpoint and about 22k tokens are written again on every turn/cost:vertex-sonnet-4-6: 10 input, 163 output, 85.7k cache read, 158.0k cache write ($1.03)Bedrock (bedrock-haiku-4-5)
claude --model bedrock-haiku-4-5 --strict-mcp-config --mcp-config '{"mcpServers":{}}', then the three prompts0 / 50156,44174 / 21062,44174 / 21275,44174 / 21625/cost:bedrock-haiku-4-5: 862 input, 751 output, 132.5k cache read, 114.1k cache write ($0.80)Azure Foundry (azure-foundry-opus-4-7)
claude --model azure-foundry-opus-4-7 --strict-mcp-config --mcp-config '{"mcpServers":{}}', then the three prompts0 / 53972,45998 / 8302,45998 / 26473,45998 / 26969,45998 / 27471/cost:azure-foundry-opus-4-7: 1.2k input, 385 output, 184.0k cache read, 143.2k cache write ($1.00)After (155ef8c)
e11399f on top of it only touches
tests/e2e, which cannot change proxy behaviorVertex (vertex-sonnet-4-6)
claude --model vertex-sonnet-4-6 --strict-mcp-config --mcp-config '{"mcpServers":{}}', then the three prompts0 / 45456,36513 / 28111,64624 / 54,65041 / 10. The read grows to the whole conversation and later turns write only the new turn/cost:vertex-sonnet-4-6: 4.9k input, 190 output, 295.9k cache read, 74.4k cache write ($0.64)Bedrock (bedrock-haiku-4-5)
claude --model bedrock-haiku-4-5 --strict-mcp-config --mcp-config '{"mcpServers":{}}', then the three prompts0 / 46785,46785 / 18319,65104 / 59,65526 / 10/cost:bedrock-haiku-4-5: 5.7k input, 1.9k output, 308.1k cache read, 65.9k cache write ($0.64)Azure Foundry (azure-foundry-opus-4-7)
claude --model azure-foundry-opus-4-7 --strict-mcp-config --mcp-config '{"mcpServers":{}}', then the three prompts0 / 49570,49570 / 4738,54308 / 18211,72519 / 79,73115 / 15/cost:azure-foundry-opus-4-7: 7.8k input, 411 output, 395.2k cache read, 73.6k cache write ($0.71)Observations from the run:
Type
🐛 Bug Fix
Caveats (if any)
QA runbook
The unflagged-model tests in both e2e files prime the prompt cache first and assert the reminder turn reads the whole primed prefix back, so the same steps prove both the completion and the cache. Priming waits until the first turn reads back on three sends in a row, because the Vertex global location serves the cache per region and a chunk written seconds earlier can still be missing from the region the next request lands on; the Vertex test also pins
us-east5, a single cache store, for the same reason. The flagged-model cache tests stay skipped under LIT-4873 and are untouchedbedrock/invoke/us.anthropic.claude-haiku-4-5-20251001-v1:0in us-east-1 (needs AWS credentials), then POST /key/generate for a key scoped to itcache_control, plus onecache_controluser turn of about 100 notes; repeat with a fresh user turn every 3s until one response shows bothcache_read_input_tokens > 0andcache_creation_input_tokens > 0, note their sum, then re-send that exact turn untilcache_read_input_tokensreaches that sum on three sends in a rowrole: "system"reminder, an assistant turn, and a freshcache_controluser turncache_read_input_tokensat least the sum noted aboveazure_ai/claude-opus-4-7(needs AZURE_AI_API_BASE and AZURE_AI_API_KEY)vertex_ai/claude-sonnet-4-6inus-east5(needs VERTEXAI_PROJECT and Google credentials)Final Attestation
Note
Medium Risk
Changes request shaping on hot proxy paths (Bedrock/Vertex/Azure Messages) and alters how system reminders are interpreted for older Claude; leading-system hoist and flagged-model paths are unchanged but billing/cache behavior is sensitive.
Overview
Fixes prompt-cache invalidation on Bedrock Invoke, Vertex, and Azure Foundry when Claude Code sends a mid-conversation
role: "system"reminder on pre-4.8 Claude models.Before: models without
supports_mid_conversation_systemhad every in-thread system message hoisted into the top-levelsystemfield. That rewrote the cached prefix and forced full cache-write billing on later turns.After:
_normalize_system_role_messagesstill hoists only a leading run of system messages (required by the API). Mid-conversation reminders on unflagged models are rewritten in place torole: "user"with a fixed operator-note prefix plus the original content, so bytes before the reminder stay unchanged. Flagged Claude 4.8+/5 behavior is unchanged (reminders stay as system inmessages).Unit tests for Azure, Bedrock, and Vertex pin the new message shape; unflagged-model e2e flows now prime the cache and assert
cache_read_input_tokenson the reminder turn. Vertex adds coverage that leading system runs are still hoisted on unsupported models.Reviewed by Cursor Bugbot for commit 1b5e507. Bugbot is set up for automated code reviews on this repo. Configure here.