The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix: preserve prompt cache for mid-conversation system on unflagged Claude models
Shifat Islam Santo658c67c1523a
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.pyindex 4d3354c58b7..1e016cffb0e 100644--- a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py+++ b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py@@ -159,8 +159,22 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig):def _is_system_role_message(message: Any) -> bool:return isinstance(message, dict) and message.get("role") == "system"+ _CONVERTED_SYSTEM_NOTE: Final = (+ "Operator note (not from the user): the following was originally a mid-conversation system-role reminder."+ )++ def _system_role_message_as_user(self, message: dict) -> dict:+ return {+ **message,+ "role": "user",+ "content": [+ {"type": "text", "text": self._CONVERTED_SYSTEM_NOTE},+ *self._as_system_content_blocks(message.get("content")),+ ],+ }+def _normalize_system_role_messages(self, anthropic_messages_request: dict, model: str) -> None:- """Move ``role: "system"`` entries out of ``messages`` per the Anthropic+ """Normalize ``role: "system"`` entries in ``messages`` per the Anthropic``/v1/messages`` contract, which the first-party API, Bedrock Invoke,Vertex, and Azure Foundry all enforce identically.@@ -173,9 +187,12 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig):stay: hoisting one mutates the ``system`` prefix and invalidates theprompt cache for the whole message history. Older Claude models reject therole in every position ("role 'system' is not supported on this model"),- so without the flag every system entry is hoisted to keep the request from- 400-ing. Billing-header system blocks are stripped from the top-level- ``system`` field regardless of whether anything was hoisted.+ so without the flag a mid-conversation entry is converted to a user turn+ in place (prefixed with an operator note) rather than hoisted: hoisting+ would mutate the ``system`` prefix and likewise collapse the cache, while+ the in-place conversion keeps everything before it byte-identical.+ Billing-header system blocks are stripped from the top-level ``system``+ field regardless of whether anything was hoisted.Subclasses whose upstream rejects the role opt in by calling this fromtheir ``transform_anthropic_messages_request``; the first-party Anthropic@@ -185,21 +202,24 @@ class AnthropicMessagesConfig(BaseAnthropicMessagesConfig):messages: Final = anthropic_messages_request.get("messages")if not isinstance(messages, list):return- if _supports_factory(- model=model,- custom_llm_provider=self.custom_llm_provider,- key="supports_mid_conversation_system",- ):- leading_count: Final = next(- (i for i, m in enumerate(messages) if not self._is_system_role_message(m)),- len(messages),+ leading_count: Final = next(+ (i for i, m in enumerate(messages) if not self._is_system_role_message(m)),+ len(messages),+ )+ hoisted: Final = messages[:leading_count]+ remaining: Final = (+ messages[leading_count:]+ if _supports_factory(+ model=model,+ custom_llm_provider=self.custom_llm_provider,+ key="supports_mid_conversation_system",)- hoisted = messages[:leading_count]- remaining = messages[leading_count:]- else:- hoisted = [m for m in messages if self._is_system_role_message(m)]- remaining = [m for m in messages if not self._is_system_role_message(m)]- if hoisted:+ else [+ self._system_role_message_as_user(m) if self._is_system_role_message(m) else m+ for m in messages[leading_count:]+ ]+ )+ if hoisted or remaining != messages:anthropic_messages_request["messages"] = remainingsystem_content: Final = [blockdiff --git a/tests/e2e/llm_translation/test_messages_mid_conversation_system_e2e.py b/tests/e2e/llm_translation/test_messages_mid_conversation_system_e2e.pyindex fff2109b0cf..e1d836108e0 100644--- a/tests/e2e/llm_translation/test_messages_mid_conversation_system_e2e.py+++ b/tests/e2e/llm_translation/test_messages_mid_conversation_system_e2e.py@@ -6,7 +6,7 @@ and the 5 family) must keep a mid-conversation system reminder in place inside``messages`` so the top-level ``system`` prefix stays byte-identical and theprompt cache written on turn one is read back in full on turn two. Modelswithout the flag (Claude 4.7 and older) reject the role inside ``messages``-outright, so the proxy must hoist the reminder into the top-level ``system``+outright, so the proxy must convert the reminder to a user turn in placefield and the call must still return a completion instead of a provider 400.The conversation shape mirrors what Claude Code sends mid-session: a cached@@ -201,7 +201,7 @@ class TestBedrockInvokeMidConversationSystem:"llm.messages.bedrock_invoke.mid_conversation_system.nonstream.works",exercised_on=[],)- def test_unflagged_model_hoists_system_reminder_and_succeeds(+ def test_unflagged_model_converts_system_reminder_and_succeeds(self, endpoints_client: EndpointsClient, resources: ResourceManager) -> None:model = _register_invoke_deployment(@@ -227,5 +227,5 @@ class TestBedrockInvokeMidConversationSystem:assert completion.text.strip(), (f"{model}: conversation with a mid-conversation system reminder "f"returned no text; the reminder was forwarded in place to a model "- f"that rejects role 'system' inside messages instead of being hoisted"+ f"that rejects role 'system' inside messages instead of being converted to a user turn")diff --git a/tests/e2e/llm_translation/test_messages_mid_conversation_system_native_providers_e2e.py b/tests/e2e/llm_translation/test_messages_mid_conversation_system_native_providers_e2e.pyindex 35ed3dc881a..6eae0d66c59 100644--- a/tests/e2e/llm_translation/test_messages_mid_conversation_system_native_providers_e2e.py+++ b/tests/e2e/llm_translation/test_messages_mid_conversation_system_native_providers_e2e.py@@ -7,13 +7,13 @@ accepted in place on Claude 4.8+/5 (200) but rejected on Claude 4.7 and older("role 'system' is not supported on this model", 400), and a *leading* systementry is rejected on every model ("messages.0: use the top-level 'system'parameter"). This mirrors Bedrock Invoke (PRs #32578/#32831/#32882); the same-model-gated hoist now runs for these two providers (customer RCA gap #3).+model-gated normalization now runs for these two providers (customer RCA gap #3).Flagged models (``supports_mid_conversation_system`` in the cost map: Claude4.8+ and the 5 family) must keep the reminder in ``messages`` so the top-level``system`` prefix stays byte-identical and the prompt cache written on turn oneis read back in full on turn two. Unflagged models (Claude 4.7 and older) must-have the reminder hoisted into the top-level ``system`` field so the call+have the reminder converted to a user turn in place so the callreturns a completion instead of a provider 400.The conversation shape mirrors what Claude Code sends mid-session: a cached@@ -206,7 +206,7 @@ def _assert_flagged_model_keeps_cache()-def _assert_unflagged_model_hoists_and_succeeds(+def _assert_unflagged_model_converts_and_succeeds(client: EndpointsClient, resources: ResourceManager, params: LiteLLMParamsBody) -> None:model = _register_deployment(client, resources, params)@@ -228,7 +228,7 @@ def _assert_unflagged_model_hoists_and_succeeds(assert completion.text.strip(), (f"{model}: conversation with a mid-conversation system reminder returned "f"no text; the reminder was forwarded in place to a model that rejects "- f"role 'system' inside messages instead of being hoisted"+ f"role 'system' inside messages instead of being converted to a user turn")@@ -250,10 +250,10 @@ class TestAzureFoundryMidConversationSystem:"llm.messages.azure_foundry.mid_conversation_system.nonstream.works",exercised_on=[],)- def test_unflagged_model_hoists_system_reminder_and_succeeds(+ def test_unflagged_model_converts_system_reminder_and_succeeds(self, endpoints_client: EndpointsClient, resources: ResourceManager) -> None:- _assert_unflagged_model_hoists_and_succeeds(+ _assert_unflagged_model_converts_and_succeeds(endpoints_client, resources, _azure_params(self.UNFLAGGED_MODEL))@@ -276,9 +276,9 @@ class TestVertexMidConversationSystem:"llm.messages.vertex.mid_conversation_system.nonstream.works",exercised_on=[],)- def test_unflagged_model_hoists_system_reminder_and_succeeds(+ def test_unflagged_model_converts_system_reminder_and_succeeds(self, endpoints_client: EndpointsClient, resources: ResourceManager) -> None:- _assert_unflagged_model_hoists_and_succeeds(+ _assert_unflagged_model_converts_and_succeeds(endpoints_client, resources, _vertex_params(self.UNFLAGGED_MODEL))diff --git a/tests/test_litellm/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.py b/tests/test_litellm/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.pyindex f6446b43fab..add1e9967db 100644--- a/tests/test_litellm/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.py+++ b/tests/test_litellm/llms/azure_ai/claude/test_azure_anthropic_messages_transformation.py@@ -425,7 +425,7 @@ class TestAzureAnthropicMidConversationSystem:{"type": "text", "text": "Cite sources."},]- def test_unsupported_model_hoists_mid_conversation_system(self, local_model_cost_map):+ def test_unsupported_model_converts_mid_conversation_system_in_place(self, local_model_cost_map):messages = [{"role": "user", "content": "read the file"},{"role": "system", "content": "[Truncated: PARTIAL view of big1.txt]"},@@ -437,13 +437,23 @@ class TestAzureAnthropicMidConversationSystem:)assert result["messages"] == [{"role": "user", "content": "read the file"},+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": (+ "Operator note (not from the user): the following was "+ "originally a mid-conversation system-role reminder."+ ),+ },+ {"type": "text", "text": "[Truncated: PARTIAL view of big1.txt]"},+ ],+ },{"role": "assistant", "content": "reading"},{"role": "user", "content": "continue"},]- assert result["system"] == [- {"type": "text", "text": "Base."},- {"type": "text", "text": "[Truncated: PARTIAL view of big1.txt]"},- ]+ assert result["system"] == [{"type": "text", "text": "Base."}]def test_azure_claude_4_8_plus_cost_map_entries_carry_mid_conversation_system_flag():diff --git a/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py b/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.pyindex fd66667af64..84df706b722 100644--- a/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py+++ b/tests/test_litellm/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py@@ -2125,13 +2125,14 @@ def test_bedrock_invoke_transform_hoists_only_leading_system_run(local_model_cos]-def test_bedrock_invoke_transform_hoists_mid_conversation_system_for_older_claude(local_model_cost_map):- """Regression test for Claude Code 400s on pre-Opus-4.8 Bedrock models:- Invoke rejects ``role: "system"`` in every position on Opus 4.7, Sonnet 4.6,- Haiku 4.5, etc. ("role 'system' is not supported on this model"), so on- models without ``supports_mid_conversation_system`` every system entry must- be hoisted into the top-level ``system`` field, mid-conversation ones- included."""+def test_bedrock_invoke_transform_converts_mid_conversation_system_for_older_claude(local_model_cost_map):+ """Invoke rejects ``role: "system"`` in every position on Opus 4.7, Sonnet+ 4.6, Haiku 4.5, etc. ("role 'system' is not supported on this model"), but+ hoisting a mid-conversation reminder into the top-level ``system`` field+ mutates the cached prefix and reprocesses the whole history. On models+ without ``supports_mid_conversation_system`` the reminder is converted to a+ user turn in place instead: the request stays valid and a cache breakpoint+ before the reminder still hits."""from litellm.types.router import GenericLiteLLMParamscfg = AmazonAnthropicClaudeMessagesConfig()@@ -2156,19 +2157,30 @@ def test_bedrock_invoke_transform_hoists_mid_conversation_system_for_older_claudassert result["messages"] == [{"role": "user", "content": "read the file"},+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": (+ "Operator note (not from the user): the following was "+ "originally a mid-conversation system-role reminder."+ ),+ },+ {"type": "text", "text": "[Truncated: PARTIAL view of big1.txt]"},+ ],+ },{"role": "assistant", "content": "reading"},{"role": "user", "content": "continue"},]- assert result["system"] == [- {"type": "text", "text": "Base."},- {"type": "text", "text": "[Truncated: PARTIAL view of big1.txt]"},- ]+ assert result["system"] == [{"type": "text", "text": "Base."}]-def test_bedrock_invoke_transform_hoists_all_system_for_unmapped_model(local_model_cost_map):+def test_bedrock_invoke_transform_converts_system_for_unmapped_model(local_model_cost_map):"""A model with no cost-map entry and no fallback-generalization rule gets- the hoist-everything behavior: the safe default is a mutated cache prefix,- never a provider 400 from forwarding a role the model may not accept."""+ the unsupported-model treatment: the safe default converts the reminder to+ a user turn in place, never a provider 400 from forwarding a role the model+ may not accept, and never a mutated cache prefix."""from litellm.types.router import GenericLiteLLMParamscfg = AmazonAnthropicClaudeMessagesConfig()@@ -2189,10 +2201,23 @@ def test_bedrock_invoke_transform_hoists_all_system_for_unmapped_model(local_modassert result["messages"] == [{"role": "user", "content": "hi"},+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": (+ "Operator note (not from the user): the following was "+ "originally a mid-conversation system-role reminder."+ ),+ },+ {"type": "text", "text": "mid-conversation reminder"},+ ],+ },{"role": "assistant", "content": "hello"},{"role": "user", "content": "continue"},]- assert result["system"] == [{"type": "text", "text": "mid-conversation reminder"}]+ assert "system" not in resultdef test_bedrock_invoke_transform_keeps_system_in_place_for_unmapped_future_claude(local_model_cost_map):diff --git a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.pyindex 292bddf1274..ef7db337a74 100644--- a/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py+++ b/tests/test_litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/test_vertex_ai_partner_models_anthropic_messages_config.py@@ -622,7 +622,7 @@ class TestVertexAnthropicMidConversationSystem:{"type": "text", "text": "Cite sources."},]- def test_unsupported_model_hoists_mid_conversation_system(self, local_model_cost_map):+ def test_unsupported_model_converts_mid_conversation_system_in_place(self, local_model_cost_map):messages = [{"role": "user", "content": "read the file"},{"role": "system", "content": "[Truncated: PARTIAL view of big1.txt]"},@@ -634,12 +634,35 @@ class TestVertexAnthropicMidConversationSystem:)assert result["messages"] == [{"role": "user", "content": "read the file"},+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": (+ "Operator note (not from the user): the following was "+ "originally a mid-conversation system-role reminder."+ ),+ },+ {"type": "text", "text": "[Truncated: PARTIAL view of big1.txt]"},+ ],+ },{"role": "assistant", "content": "reading"},{"role": "user", "content": "continue"},]+ assert result["system"] == [{"type": "text", "text": "Base."}]++ def test_unsupported_model_still_hoists_leading_system_run(self, local_model_cost_map):+ messages = [+ {"role": "system", "content": "You are terse."},+ {"role": "system", "content": "Cite sources."},+ {"role": "user", "content": "hi"},+ ]+ result = _vertex_transform("claude-sonnet-4-6", messages)+ assert result["messages"] == [{"role": "user", "content": "hi"}]assert result["system"] == [- {"type": "text", "text": "Base."},- {"type": "text", "text": "[Truncated: PARTIAL view of big1.txt]"},+ {"type": "text", "text": "You are terse."},+ {"type": "text", "text": "Cite sources."},]