Skip to content

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]

fix(bedrock): gate in-place system role messages on model support for Claude Invoke (#32831)

Mateo Wang5e23a5ab053f
diff --git a/litellm/litellm_core_utils/fallback_generalizations.py b/litellm/litellm_core_utils/fallback_generalizations.py
index abc171f900a..8b5a797cbd7 100644
--- a/litellm/litellm_core_utils/fallback_generalizations.py
+++ b/litellm/litellm_core_utils/fallback_generalizations.py
@@ -8,9 +8,12 @@ The metadata is a partial cost-map entry: ``litellm_provider`` drives provider
routing, and the remaining fields (``mode``, ``supports_*``, context window,
pricing, ...) drive ``get_model_info`` / ``supports_*``.
-Precedence: rules are evaluated in file order and the first match wins. They are
-consulted only after exact and case-insensitive lookups miss, so an exact entry
-always takes precedence over a rule.
+Precedence: rules are evaluated in file order and the first match wins. Callers
+with extra constraints (model-info resolution checks the provider) use
+``match_all_fallback_generalizations`` to skip inapplicable earlier rules instead
+of discarding the model name. Rules are consulted only after exact and
+case-insensitive lookups miss, so an exact entry always takes precedence over a
+rule.
Patterns are matched case-insensitively with ``re.search`` and are not implicitly
anchored: a rule must include ``^`` and ``$`` (as the shipped rules do) to bind to
@@ -105,15 +108,15 @@ class _FallbackGeneralizations:
)
return compiled
- def match(self, model: str) -> Optional[dict]:
+ def matches(self, model: str) -> list[dict]:
if not model:
- return None
+ return []
if self._compiled is None:
self._compiled = self._compile()
- for pattern, model_info in self._compiled:
- if pattern.search(model) is not None:
- return dict(model_info)
- return None
+ return [dict(model_info) for pattern, model_info in self._compiled if pattern.search(model) is not None]
+
+ def match(self, model: str) -> Optional[dict]:
+ return next(iter(self.matches(model)), None)
_registry = _FallbackGeneralizations()
@@ -139,3 +142,12 @@ def match_fallback_generalization(model: str) -> Optional[dict]:
O(number of rules). Only call this once exact lookups have missed.
"""
return _registry.match(model)
+
+
+def match_all_fallback_generalizations(model: str) -> list[dict]:
+ """Return the ``model_info`` of every rule whose regex matches ``model``, in rule order.
+
+ Lets a caller with extra constraints (e.g. a provider match) skip an
+ inapplicable earlier rule instead of discarding the whole candidate.
+ """
+ return _registry.matches(model)
diff --git a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
index 155fba008d4..56a47432997 100644
--- a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
+++ b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py
@@ -93,31 +93,48 @@ class AmazonAnthropicClaudeMessagesConfig(
return [{"type": "text", "text": value}]
return [value]
- def _normalize_system_role_messages_for_bedrock(self, anthropic_messages_request: dict) -> None:
- """Bedrock Invoke rejects a conversation that opens with ``role: "system"``
- entries inside ``messages`` ("messages.0: use the top-level 'system'
- parameter for the initial system prompt"); Anthropic Messages carries that
- content in the top-level ``system`` field, so hoist the leading run of
- system entries there. Mid-conversation system entries (e.g. Claude Code's
- ``mid-conversation-system-2026-04-07`` reminders) are accepted by Invoke in
- place and MUST stay in place: hoisting one mutates the ``system`` prefix
- and invalidates the prompt cache for the entire message history.
+ @staticmethod
+ def _is_system_role_message(message: Any) -> bool:
+ return isinstance(message, dict) and message.get("role") == "system"
+
+ def _normalize_system_role_messages_for_bedrock(self, anthropic_messages_request: dict, model: str) -> None:
+ """Bedrock Invoke validates ``role: "system"`` entries inside ``messages``
+ per model. Models carrying ``supports_mid_conversation_system`` in the
+ cost map (the Opus 4.8 family) only reject a leading run ("messages.0:
+ use the top-level 'system' parameter for the initial system prompt") and
+ accept mid-conversation entries (e.g. Claude Code's
+ ``mid-conversation-system-2026-04-07`` reminders) in place, where they
+ MUST stay: hoisting one mutates the ``system`` prefix and invalidates the
+ prompt cache for the entire message history. Older Claude models (Opus
+ 4.7, Sonnet 4.6, Haiku 4.5, ...) reject the role in every position
+ ("role 'system' is not supported on this model"), so without the flag
+ every system entry is hoisted into the top-level ``system`` field.
Billing-header system blocks are stripped from the top-level ``system``
field regardless of whether anything was hoisted."""
messages = anthropic_messages_request.get("messages")
if not isinstance(messages, list):
return
- leading_count = next(
- (i for i, m in enumerate(messages) if not (isinstance(m, dict) and m.get("role") == "system")),
- len(messages),
- )
- if leading_count:
- anthropic_messages_request["messages"] = messages[leading_count:]
+ if _supports_factory(
+ model=model,
+ custom_llm_provider="bedrock",
+ key="supports_mid_conversation_system",
+ ):
+ leading_count = next(
+ (i for i, m in enumerate(messages) if not self._is_system_role_message(m)),
+ len(messages),
+ )
+ 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:
+ anthropic_messages_request["messages"] = remaining
system_content = [
block
for source in (
anthropic_messages_request.get("system"),
- *(m.get("content") for m in messages[:leading_count]),
+ *(m.get("content") for m in hoisted),
)
for block in self._as_system_content_blocks(source)
]
@@ -674,7 +691,7 @@ class AmazonAnthropicClaudeMessagesConfig(
litellm_params=litellm_params,
headers=headers,
)
- self._normalize_system_role_messages_for_bedrock(anthropic_messages_request)
+ self._normalize_system_role_messages_for_bedrock(anthropic_messages_request, model=model)
#########################################################
############## BEDROCK Invoke SPECIFIC TRANSFORMATION ###
#########################################################
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index f3adfaedbdc..b42ba23fa78 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -1481,6 +1481,7 @@
"anthropic.claude-opus-4-8": {
"bedrock_converse_supports_strict_tools": false,
"supports_adaptive_thinking": true,
+ "supports_mid_conversation_system": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1516,6 +1517,7 @@
"global.anthropic.claude-opus-4-8": {
"bedrock_converse_supports_strict_tools": false,
"supports_adaptive_thinking": true,
+ "supports_mid_conversation_system": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1551,6 +1553,7 @@
"us.anthropic.claude-opus-4-8": {
"bedrock_converse_supports_strict_tools": false,
"supports_adaptive_thinking": true,
+ "supports_mid_conversation_system": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1586,6 +1589,7 @@
"eu.anthropic.claude-opus-4-8": {
"bedrock_converse_supports_strict_tools": false,
"supports_adaptive_thinking": true,
+ "supports_mid_conversation_system": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1621,6 +1625,7 @@
"au.anthropic.claude-opus-4-8": {
"bedrock_converse_supports_strict_tools": false,
"supports_adaptive_thinking": true,
+ "supports_mid_conversation_system": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -45033,6 +45038,17 @@
},
"fallback_generalizations": {
"rules": [
+ {
+ "name": "bedrock-anthropic-claude-mid-conversation-system",
+ "pattern": "anthropic\\.claude-[a-z]+-(?:4[-._](?:[89]|[1-9]\\d)(?!\\d)|(?:[5-9]|[1-9]\\d)(?!\\d)(?:[-._]\\d{1,2}(?!\\d))?)",
+ "description": "Bedrock Invoke ids for Claude 4.8 or higher: anthropic.claude-<family> with minor 4.8 through 4.99, any 5.x or later major-minor, or a bare 5+ major, which also admits new families such as fable. These models accept mid-conversation role system messages in place (verified live on Opus 4.8, Sonnet 5 and Fable 5), so unmapped future Bedrock Claudes keep the cache-preserving in-place handling instead of the hoist-all default. Listed first so bare-id provider inference, which takes the first pattern hit, resolves these Bedrock ids to bedrock; model-info resolution skips provider-mismatched rules either way.",
+ "extends": "anthropic-claude",
+ "model_info": {
+ "litellm_provider": "bedrock",
+ "supports_adaptive_thinking": true,
+ "supports_mid_conversation_system": true
+ }
+ },
{
"name": "anthropic-claude-adaptive-thinking",
"pattern": "(?:opus|sonnet|haiku)[-._](?:4[-._](?:[6-9]|[1-9]\\d)(?!\\d)|(?:[5-9]|[1-9]\\d{1,})[-._]\\d{1,2}(?!\\d))",
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 8a5acc24d19..e33e2335525 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -143,6 +143,7 @@ class ProviderSpecificModelInfo(TypedDict, total=False):
supports_web_search: Optional[bool]
supports_reasoning: Optional[bool]
supports_adaptive_thinking: Optional[bool]
+ supports_mid_conversation_system: Optional[bool]
supports_url_context: Optional[bool]
supports_none_reasoning_effort: Optional[bool]
supports_minimal_reasoning_effort: Optional[bool]
diff --git a/litellm/utils.py b/litellm/utils.py
index 5af7b62b332..731be992af0 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -61,7 +61,7 @@ from litellm._lazy_imports import (
)
from litellm._uuid import uuid
from litellm.litellm_core_utils.fallback_generalizations import (
- match_fallback_generalization,
+ match_all_fallback_generalizations,
)
from litellm.constants import (
DEFAULT_CHAT_COMPLETION_PARAM_VALUES,
@@ -5046,9 +5046,10 @@ def _get_model_info_from_generalization(
"""Resolve an unmapped model via a declarative fallback-generalization rule.
Tries the same name candidates as the exact lookups, in the same order, and
- returns ``(matched_name, model_info)`` for the first candidate whose rule also
- satisfies the provider constraint. O(number of rules); only call after the
- exact lookups have missed.
+ returns ``(matched_name, model_info)`` for the first matching rule that also
+ satisfies the provider constraint; a rule scoped to another provider is
+ skipped in favor of later rules rather than discarding the candidate.
+ O(number of rules); only call after the exact lookups have missed.
"""
candidates = [
potential_model_names["combined_model_name"],
@@ -5058,11 +5059,9 @@ def _get_model_info_from_generalization(
potential_model_names["stripped_model_name"],
]
for candidate in candidates:
- generalized_info = match_fallback_generalization(candidate)
- if generalized_info is not None and _check_provider_match(
- model_info=generalized_info, custom_llm_provider=custom_llm_provider
- ):
- return candidate, generalized_info
+ for generalized_info in match_all_fallback_generalizations(candidate):
+ if _check_provider_match(model_info=generalized_info, custom_llm_provider=custom_llm_provider):
+ return candidate, generalized_info
return None
@@ -5472,6 +5471,7 @@ def _get_model_info_helper(
supports_url_context=_model_info.get("supports_url_context", None),
supports_reasoning=_model_info.get("supports_reasoning", None),
supports_adaptive_thinking=_model_info.get("supports_adaptive_thinking", None),
+ supports_mid_conversation_system=_model_info.get("supports_mid_conversation_system", None),
supports_none_reasoning_effort=_model_info.get("supports_none_reasoning_effort", None),
supports_minimal_reasoning_effort=_model_info.get("supports_minimal_reasoning_effort", None),
supports_low_reasoning_effort=_model_info.get("supports_low_reasoning_effort", None),
diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json
index a85b8922849..4920f12e428 100644
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@ -1481,6 +1481,7 @@
"anthropic.claude-opus-4-8": {
"bedrock_converse_supports_strict_tools": false,
"supports_adaptive_thinking": true,
+ "supports_mid_conversation_system": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1516,6 +1517,7 @@
"global.anthropic.claude-opus-4-8": {
"bedrock_converse_supports_strict_tools": false,
"supports_adaptive_thinking": true,
+ "supports_mid_conversation_system": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1551,6 +1553,7 @@
"us.anthropic.claude-opus-4-8": {
"bedrock_converse_supports_strict_tools": false,
"supports_adaptive_thinking": true,
+ "supports_mid_conversation_system": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1586,6 +1589,7 @@
"eu.anthropic.claude-opus-4-8": {
"bedrock_converse_supports_strict_tools": false,
"supports_adaptive_thinking": true,
+ "supports_mid_conversation_system": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1621,6 +1625,7 @@
"au.anthropic.claude-opus-4-8": {
"bedrock_converse_supports_strict_tools": false,
"supports_adaptive_thinking": true,
+ "supports_mid_conversation_system": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -45266,6 +45271,17 @@
},
"fallback_generalizations": {
"rules": [
+ {
+ "name": "bedrock-anthropic-claude-mid-conversation-system",
+ "pattern": "anthropic\\.claude-[a-z]+-(?:4[-._](?:[89]|[1-9]\\d)(?!\\d)|(?:[5-9]|[1-9]\\d)(?!\\d)(?:[-._]\\d{1,2}(?!\\d))?)",
+ "description": "Bedrock Invoke ids for Claude 4.8 or higher: anthropic.claude-<family> with minor 4.8 through 4.99, any 5.x or later major-minor, or a bare 5+ major, which also admits new families such as fable. These models accept mid-conversation role system messages in place (verified live on Opus 4.8, Sonnet 5 and Fable 5), so unmapped future Bedrock Claudes keep the cache-preserving in-place handling instead of the hoist-all default. Listed first so bare-id provider inference, which takes the first pattern hit, resolves these Bedrock ids to bedrock; model-info resolution skips provider-mismatched rules either way.",
+ "extends": "anthropic-claude",
+ "model_info": {
+ "litellm_provider": "bedrock",
+ "supports_adaptive_thinking": true,
+ "supports_mid_conversation_system": true
+ }
+ },
{
"name": "anthropic-claude-adaptive-thinking",
"pattern": "(?:opus|sonnet|haiku)[-._](?:4[-._](?:[6-9]|[1-9]\\d)(?!\\d)|(?:[5-9]|[1-9]\\d{1,})[-._]\\d{1,2}(?!\\d))",
diff --git a/tests/test_litellm/litellm_core_utils/test_fallback_generalizations.py b/tests/test_litellm/litellm_core_utils/test_fallback_generalizations.py
index 410014958b6..cf74bed9c15 100644
--- a/tests/test_litellm/litellm_core_utils/test_fallback_generalizations.py
+++ b/tests/test_litellm/litellm_core_utils/test_fallback_generalizations.py
@@ -16,6 +16,7 @@ sys.path.insert(0, os.path.abspath("../../.."))
import litellm
from litellm.litellm_core_utils.fallback_generalizations import (
get_fallback_generalization_rules,
+ match_all_fallback_generalizations,
match_fallback_generalization,
set_fallback_generalizations,
)
@@ -57,6 +58,48 @@ def test_match_returns_model_info_of_first_matching_rule(restore_generalizations
assert matched["tag"] == "first"
+def test_match_all_returns_every_matching_rule_in_order(restore_generalizations):
+ restore_generalizations(
+ [
+ {
+ "name": "first",
+ "pattern": r"^acme-",
+ "model_info": {"litellm_provider": "openai", "tag": "first"},
+ },
+ {
+ "name": "second",
+ "pattern": r"^acme-pro-",
+ "model_info": {"litellm_provider": "anthropic", "tag": "second"},
+ },
+ ]
+ )
+ assert [m["tag"] for m in match_all_fallback_generalizations("acme-pro-1")] == ["first", "second"]
+ assert match_all_fallback_generalizations("gpt-4o") == []
+
+
+def test_provider_scoped_rule_is_skipped_for_other_providers(restore_generalizations):
+ """Model-info resolution must fall through a provider-mismatched earlier rule to a
+ later applicable one, instead of discarding the model name at the first pattern hit."""
+ restore_generalizations(
+ [
+ {
+ "name": "bedrock-scoped",
+ "pattern": r"^acme-",
+ "model_info": {"litellm_provider": "bedrock", "supports_vision": False},
+ },
+ {
+ "name": "openai-scoped",
+ "pattern": r"^acme-",
+ "model_info": {"litellm_provider": "openai", "mode": "chat", "supports_vision": True},
+ },
+ ]
+ )
+ litellm.get_model_info.cache_clear()
+ info = litellm.get_model_info("acme-fast-1", custom_llm_provider="openai")
+ assert info["litellm_provider"] == "openai"
+ assert info["supports_vision"] is True
+
+
def test_match_is_case_insensitive(restore_generalizations):
restore_generalizations(
[{"name": "r", "pattern": r"^claude-opus", "model_info": {"ok": True}}]
@@ -298,3 +341,47 @@ def test_shipped_adaptive_rule_gates_on_version_not_pricing(shipped_cost_map):
assert non_adaptive not in litellm.model_cost
assert AnthropicModelInfo._is_adaptive_thinking_model(adaptive) is True
assert AnthropicModelInfo._is_adaptive_thinking_model(non_adaptive) is False
+
+
+def test_shipped_bedrock_rule_resolves_unmapped_future_claude_for_bedrock(shipped_cost_map):
+ """An unmapped Bedrock Claude >= 4.8 resolves via the bedrock-scoped
+ ``bedrock-anthropic-claude-mid-conversation-system`` rule even when the lookup
+ carries ``custom_llm_provider="bedrock"``, which the provider check uses to drop
+ the anthropic-scoped rules. It inherits base capabilities, gains both
+ version-gated flags, and stays unpriced."""
+ model = "us.anthropic.claude-opus-4-9"
+ assert model not in litellm.model_cost
+ info = litellm.get_model_info(model, custom_llm_provider="bedrock")
+ assert info["litellm_provider"] == "bedrock"
+ assert info["supports_mid_conversation_system"] is True
+ assert info["supports_adaptive_thinking"] is True
+ assert info["supports_function_calling"] is True
+ assert not info.get("input_cost_per_token")
+
+
+def test_shipped_bedrock_mid_conversation_rule_gates_on_version_and_naming(shipped_cost_map):
+ """The bedrock rule only claims Bedrock-style ids at 4.8+, bare 5+ majors and
+ new families included; pre-4.8 Bedrock ids and native ids never gain the flag,
+ and the rule outranks the anthropic-scoped ones for Bedrock ids because it is
+ listed first."""
+ for flagged in (
+ "us.anthropic.claude-opus-4-8",
+ "jp.anthropic.claude-opus-4-8",
+ "anthropic.claude-sonnet-5",
+ "us.anthropic.claude-fable-5",
+ "anthropic.claude-sonnet-5-20260101-v1:0",
+ ):
+ matched = match_fallback_generalization(flagged)
+ assert matched is not None, flagged
+ assert matched["litellm_provider"] == "bedrock", flagged
+ assert matched["supports_mid_conversation_system"] is True, flagged
+ for unflagged in (
+ "us.anthropic.claude-opus-4-7",
+ "us.anthropic.claude-sonnet-4-6",
+ "us.anthropic.claude-haiku-4-5-20251001-v1:0",
+ "anthropic.claude-3-5-sonnet-20240620-v1:0",
+ "claude-opus-4-9",
+ "claude-sonnet-5",
+ ):
+ matched = match_fallback_generalization(unflagged)
+ assert matched is None or not matched.get("supports_mid_conversation_system"), unflagged
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.py
index ffe45cd5e79..43ce4873023 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
@@ -1974,14 +1974,15 @@ def test_bedrock_invoke_transform_merges_list_content_system_role_into_system():
]
-def test_bedrock_invoke_transform_keeps_mid_conversation_system_role_in_place():
+def test_bedrock_invoke_transform_keeps_mid_conversation_system_role_in_place(local_model_cost_map):
"""Regression test for the Bedrock prompt-cache collapse: hoisting a
mid-conversation ``role: "system"`` message (e.g. Claude Code's
``mid-conversation-system-2026-04-07`` reminders) into the top-level
``system`` field mutates the cache prefix and invalidates the cached message
- history, so such entries must be forwarded in place. Invoke only rejects a
- system entry at ``messages.0``. Billing-header blocks must still be stripped
- from the top-level ``system`` field even when nothing is hoisted."""
+ history, so on models flagged ``supports_mid_conversation_system`` (the Opus
+ 4.8 family, which Invoke accepts the role on) such entries must be forwarded
+ in place. Billing-header blocks must still be stripped from the top-level
+ ``system`` field even when nothing is hoisted."""
from litellm.types.router import GenericLiteLLMParams
cfg = AmazonAnthropicClaudeMessagesConfig()
@@ -2013,10 +2014,11 @@ def test_bedrock_invoke_transform_keeps_mid_conversation_system_role_in_place():
]
-def test_bedrock_invoke_transform_hoists_only_leading_system_run():
- """Only the leading run of ``role: "system"`` messages is hoisted into the
- top-level ``system`` field; a later system entry keeps its position in
- ``messages`` so the serialized prefix stays stable across turns."""
+def test_bedrock_invoke_transform_hoists_only_leading_system_run(local_model_cost_map):
+ """On models flagged ``supports_mid_conversation_system``, only the leading
+ run of ``role: "system"`` messages is hoisted into the top-level ``system``
+ field; a later system entry keeps its position in ``messages`` so the
+ serialized prefix stays stable across turns."""
from litellm.types.router import GenericLiteLLMParams
cfg = AmazonAnthropicClaudeMessagesConfig()
@@ -2047,6 +2049,103 @@ def test_bedrock_invoke_transform_hoists_only_leading_system_run():
]
+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."""
+ from litellm.types.router import GenericLiteLLMParams
+
+ cfg = AmazonAnthropicClaudeMessagesConfig()
+ messages = [
+ {"role": "user", "content": "read the file"},
+ {"role": "system", "content": "[Truncated: PARTIAL view of big1.txt]"},
+ {"role": "assistant", "content": "reading"},
+ {"role": "user", "content": "continue"},
+ ]
+
+ result = cfg.transform_anthropic_messages_request(
+ model="us.anthropic.claude-opus-4-7",
+ messages=copy.deepcopy(messages),
+ anthropic_messages_optional_request_params={
+ "max_tokens": 256,
+ "stream": False,
+ "system": [{"type": "text", "text": "Base."}],
+ },
+ litellm_params=GenericLiteLLMParams(),
+ headers={},
+ )
+
+ assert result["messages"] == [
+ {"role": "user", "content": "read the file"},
+ {"role": "assistant", "content": "reading"},
+ {"role": "user", "content": "continue"},
+ ]
+ assert result["system"] == [
+ {"type": "text", "text": "Base."},
+ {"type": "text", "text": "[Truncated: PARTIAL view of big1.txt]"},
+ ]
+
+
+def test_bedrock_invoke_transform_hoists_all_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."""
+ from litellm.types.router import GenericLiteLLMParams
+
+ cfg = AmazonAnthropicClaudeMessagesConfig()
+ messages = [
+ {"role": "user", "content": "hi"},
+ {"role": "system", "content": "mid-conversation reminder"},
+ {"role": "assistant", "content": "hello"},
+ {"role": "user", "content": "continue"},
+ ]
+
+ result = cfg.transform_anthropic_messages_request(
+ model="us.anthropic.claude-opus-3-9",
+ messages=copy.deepcopy(messages),
+ anthropic_messages_optional_request_params={"max_tokens": 256, "stream": False},
+ litellm_params=GenericLiteLLMParams(),
+ headers={},
+ )
+
+ assert result["messages"] == [
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "hello"},
+ {"role": "user", "content": "continue"},
+ ]
+ assert result["system"] == [{"type": "text", "text": "mid-conversation reminder"}]
+
+
+def test_bedrock_invoke_transform_keeps_system_in_place_for_unmapped_future_claude(local_model_cost_map):
+ """An unmapped Bedrock Claude at 4.8 or higher resolves through the
+ ``bedrock-anthropic-claude-mid-conversation-system`` fallback rule, so a
+ future model that has not landed in the cost map yet keeps the
+ cache-preserving in-place behavior instead of falling back to hoist-all."""
+ from litellm.types.router import GenericLiteLLMParams
+
+ cfg = AmazonAnthropicClaudeMessagesConfig()
+ messages = [
+ {"role": "user", "content": "hi"},
+ {"role": "system", "content": "mid-conversation reminder"},
+ {"role": "assistant", "content": "hello"},
+ {"role": "user", "content": "continue"},
+ ]
+
+ result = cfg.transform_anthropic_messages_request(
+ model="us.anthropic.claude-opus-4-9",
+ messages=copy.deepcopy(messages),
+ anthropic_messages_optional_request_params={"max_tokens": 256, "stream": False},
+ litellm_params=GenericLiteLLMParams(),
+ headers={},
+ )
+
+ assert result["messages"] == messages
+ assert "system" not in result
+
+
def test_as_system_content_blocks_handles_each_shape():
"""``_as_system_content_blocks`` normalizes every system shape: ``None`` -> empty,
a string -> a single text block, a list -> a shallow copy, and any other value
diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py
index bdb25120563..26ae6ff7f4c 100644
--- a/tests/test_litellm/test_utils.py
+++ b/tests/test_litellm/test_utils.py
@@ -855,6 +855,7 @@ def test_aaamodel_prices_and_context_window_json_is_valid():
"supports_xhigh_reasoning_effort": {"type": "boolean"},
"supports_max_reasoning_effort": {"type": "boolean"},
"supports_adaptive_thinking": {"type": "boolean"},
+ "supports_mid_conversation_system": {"type": "boolean"},
"supports_sampling_params": {"type": "boolean"},
"supports_output_config": {"type": "boolean"},
"supports_speed": {"type": "boolean"},