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
Fall back to the GPT version rule when the cost map carries no breakpoint flag
mateo-berrie16cf5ed3ff1
diff --git a/litellm/integrations/anthropic_cache_control_hook.py b/litellm/integrations/anthropic_cache_control_hook.pyindex f65decc5463..1258c7593b4 100644--- a/litellm/integrations/anthropic_cache_control_hook.py+++ b/litellm/integrations/anthropic_cache_control_hook.py@@ -59,10 +59,9 @@ OPENAI_API_BASE_ENV_VARS: Final = ("OPENAI_BASE_URL", "OPENAI_API_BASE")def supports_openai_prompt_cache_breakpoint(model: str) -> bool:- if _has_model_map_entry(model):- from litellm.utils import supports_prompt_cache_breakpoint-- return supports_prompt_cache_breakpoint(model)+ model_map_flag: Final = _model_map_prompt_cache_breakpoint_flag(model)+ if model_map_flag is not None:+ return model_map_flagversion_match: Final = _GPT_VERSION_PATTERN.match(model.rsplit("/", 1)[-1].lower())if version_match is None:return False@@ -70,10 +69,12 @@ def supports_openai_prompt_cache_breakpoint(model: str) -> bool:return version >= OPENAI_PROMPT_CACHE_BREAKPOINT_MIN_GPT_VERSION-def _has_model_map_entry(model: str) -> bool:+def _model_map_prompt_cache_breakpoint_flag(model: str) -> bool | None:import litellm- return model in litellm.model_cost or model.rsplit("/", 1)[-1] in litellm.model_cost+ entries: Final = (litellm.model_cost.get(key) for key in (model, model.rsplit("/", 1)[-1]))+ flags: Final = (entry.get("supports_prompt_cache_breakpoint") for entry in entries if isinstance(entry, dict))+ return next((bool(flag) for flag in flags if flag is not None), None)def targets_openai_api(api_base: object) -> bool:@@ -150,7 +151,7 @@ class AnthropicCacheControlHook(CustomPromptManagement):else AnthropicCacheControlHook._targets_openai_prompt_cache_breakpoint(model,non_default_params.get("custom_llm_provider"),- non_default_params.get("api_base"),+ non_default_params.get("api_base") or non_default_params.get("base_url"),non_default_params.get("prompt_cache_options"),))diff --git a/litellm/main.py b/litellm/main.pyindex 87b32ab140c..98c220f94e0 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -507,7 +507,7 @@ async def acompletion(custom_llm_provider=cast(str | None, custom_llm_provider), # cast-ok: read from untyped kwargstools=tools,enable_prompt_caching=cast(bool | None, kwargs.get("enable_prompt_caching")), # cast-ok: untyped kwargs- api_base=kwargs.get("api_base"),+ api_base=kwargs.get("api_base") or base_url,)if isinstance(litellm_logging_obj, LiteLLMLoggingObj) and (@@ -5172,7 +5172,7 @@ def completion(custom_llm_provider=cast(str | None, kwargs.get("custom_llm_provider")), # cast-ok: untyped kwargstools=tools,enable_prompt_caching=cast(bool | None, kwargs.get("enable_prompt_caching")), # cast-ok: untyped kwargs- api_base=kwargs.get("api_base"),+ api_base=kwargs.get("api_base") or base_url,)if isinstance(litellm_logging_obj, LiteLLMLoggingObj) and (diff --git a/litellm/responses/utils.py b/litellm/responses/utils.pyindex 504009802f2..716a815547d 100644--- a/litellm/responses/utils.py+++ b/litellm/responses/utils.py@@ -37,20 +37,28 @@ def normalize_responses_api_stream_options(return ResponsesAPIStreamOptions(include_obfuscation=include_obfuscation)+def _is_chat_text_part(part: object) -> bool:+ return isinstance(part, dict) and part.get("type") == "text"+++def _as_input_text_part(part: object) -> object:+ if isinstance(part, dict) and part.get("type") == "text":+ return {**part, "type": "input_text"} # mutable-ok: fresh part so the caller's block keeps its chat type+ return part++class ResponsesAPIRequestUtils:"""Helper utils for constructing ResponseAPI requests"""@staticmethod- def shape_prompt_managed_messages_for_responses(messages: Iterable[object]) -> None:- for message in messages:- if not isinstance(message, dict) or message.get("role") == "assistant":- continue- content: object = message.get("content")- if not isinstance(content, list):- continue- for part in content:- if isinstance(part, dict) and part.get("type") == "text":- part["type"] = "input_text"+ def shape_prompt_managed_message_for_responses(message: object) -> object:+ if not isinstance(message, dict) or message.get("role") == "assistant":+ return message+ content: object = message.get("content")+ if not isinstance(content, list) or not any(_is_chat_text_part(part) for part in content):+ return message+ shaped_content: Final = [_as_input_text_part(part) for part in content] # mutable-ok: Responses-shaped copy+ return {**message, "content": shaped_content} # mutable-ok: copy, the hook's message stays untouched@staticmethoddef merge_prompt_management_input(@@ -58,16 +66,16 @@ class ResponsesAPIRequestUtils:client_input: list[AllMessageValues],merged_input: list[AllMessageValues],) -> list[object]:- ResponsesAPIRequestUtils.shape_prompt_managed_messages_for_responses(merged_input)+ shape: Final = ResponsesAPIRequestUtils.shape_prompt_managed_message_for_responsesif isinstance(original_input, str):- return [*merged_input]+ return [shape(message) for message in merged_input]original_items: Final = tuple(original_input)client_item_ids: Final = frozenset(id(item) for item in client_input)message_positions = tuple(index for index, item in enumerate(original_items) if id(item) in client_item_ids)if len(message_positions) == len(original_items):- return [*merged_input]+ return [shape(message) for message in merged_input]if not message_positions:verbose_logger.warning("Prompt management hook returned messages without Responses API input messages; merged messages were ignored"@@ -82,7 +90,7 @@ class ResponsesAPIRequestUtils:if corresponding_messages:merged_by_position: Final = dict(zip(message_positions, merged_input))return [- merged_by_position[index] if index in merged_by_position else item+ shape(merged_by_position[index]) if index in merged_by_position else itemfor index, item in enumerate(original_items)]@@ -95,14 +103,14 @@ class ResponsesAPIRequestUtils:for index, position in enumerate(message_positions)}trailing_items: Final = original_items[message_positions[-1] + 1 :]- return [item for merged in merged_input for item in (*prefixes.get(id(merged), ()), merged)] + list(+ return [item for merged in merged_input for item in (*prefixes.get(id(merged), ()), shape(merged))] + list(trailing_items)verbose_logger.warning("Prompt management hook replaced Responses API messages; non-message input items were dropped")- return [*merged_input]+ return [shape(message) for message in merged_input]@staticmethoddef merge_client_forwarded_headers(diff --git a/tests/test_litellm/integrations/test_anthropic_cache_control_hook.py b/tests/test_litellm/integrations/test_anthropic_cache_control_hook.pyindex 4eb774af5bc..e92a368d24b 100644--- a/tests/test_litellm/integrations/test_anthropic_cache_control_hook.py+++ b/tests/test_litellm/integrations/test_anthropic_cache_control_hook.py@@ -2697,11 +2697,14 @@ class TestToolConfigSlotInOpenAIDialect:class TestPromptCacheBreakpointCapability:- """Eligibility comes from the model map's supports_prompt_cache_breakpoint flag, with the GPT version- rule only for models the map does not know (#37509)."""+ """Eligibility comes from the model map's supports_prompt_cache_breakpoint flag when the entry carries one,+ with the GPT version rule for unlisted models and for entries the published map has not flagged yet (#37509)."""@pytest.fixture(autouse=True)- def _fresh_model_info_cache(self):+ def _bundled_model_map(self, monkeypatch):+ bundled = os.path.join(os.path.dirname(litellm.__file__), "model_prices_and_context_window_backup.json")+ with open(bundled) as handle:+ monkeypatch.setattr(litellm, "model_cost", json.load(handle))litellm.utils._cached_get_model_info_helper.cache_clear()yieldlitellm.utils._cached_get_model_info_helper.cache_clear()@@ -2724,15 +2727,47 @@ class TestPromptCacheBreakpointCapability:monkeypatch.setitem(litellm.model_cost, "gpt-4.1", flagged)assert supports_openai_prompt_cache_breakpoint("gpt-4.1") is True- def test_listed_gpt_5_6_without_the_flag_is_not_eligible(self, monkeypatch):+ def test_listed_gpt_5_6_without_the_flag_falls_back_to_the_version_rule(self, monkeypatch):unflagged = {k: v for k, v in litellm.model_cost["gpt-5.6"].items() if k != "supports_prompt_cache_breakpoint"}monkeypatch.setitem(litellm.model_cost, "gpt-5.6", unflagged)+ assert supports_openai_prompt_cache_breakpoint("gpt-5.6") is True+ assert supports_openai_prompt_cache_breakpoint("openai/gpt-5.6") is True++ def test_listed_model_flagged_false_is_not_eligible(self, monkeypatch):+ monkeypatch.setitem(+ litellm.model_cost, "gpt-5.6", {**litellm.model_cost["gpt-5.6"], "supports_prompt_cache_breakpoint": False}+ )assert supports_openai_prompt_cache_breakpoint("gpt-5.6") is False- def test_listed_gpt_model_without_the_flag_is_false(self):+ def test_listed_gpt_model_without_the_flag_follows_the_version_rule(self):assert "supports_prompt_cache_breakpoint" not in litellm.model_cost["gpt-4.1"]assert supports_openai_prompt_cache_breakpoint("gpt-4.1") is False+ def test_published_map_without_the_flag_still_injects_on_gpt_5_6(self, monkeypatch):+ unflagged = {k: v for k, v in litellm.model_cost["gpt-5.6"].items() if k != "supports_prompt_cache_breakpoint"}+ monkeypatch.setitem(litellm.model_cost, "gpt-5.6", unflagged)+ points = [{"location": "message", "role": "system"}]++ _, chat_messages, chat_params = AnthropicCacheControlHook().get_chat_completion_prompt(+ model="openai/gpt-5.6",+ messages=[{"role": "system", "content": "sys"}, {"role": "user", "content": "hi"}],+ non_default_params={"cache_control_injection_points": copy.deepcopy(points)},+ prompt_id=None,+ prompt_variables=None,+ dynamic_callback_params={},+ )+ assert chat_messages[0]["content"] == [+ {"type": "text", "text": "sys", "prompt_cache_breakpoint": {"mode": "explicit"}}+ ]+ assert chat_params["prompt_cache_options"] == {"mode": "explicit"}++ kwargs = {"cache_control_injection_points": copy.deepcopy(points)}+ _, system = AnthropicCacheControlHook.maybe_inject_cache_control(+ [{"role": "user", "content": "hi"}], "sys", kwargs, model="gpt-5.6", custom_llm_provider="openai"+ )+ assert system == [{"type": "text", "text": "sys", "prompt_cache_breakpoint": {"mode": "explicit"}}]+ assert kwargs == {"prompt_cache_options": {"mode": "explicit"}}+@pytest.mark.parametrize("model,expected", [("gpt-5.6-2026-01-01", True), ("gpt-5.5-preview-unlisted", False)])def test_unlisted_model_falls_back_to_the_version_rule(self, model, expected):assert model not in litellm.model_costdiff --git a/tests/test_litellm/responses/test_responses_api_request_body.py b/tests/test_litellm/responses/test_responses_api_request_body.pyindex 1402491a6b6..14eb9ab6e12 100644--- a/tests/test_litellm/responses/test_responses_api_request_body.py+++ b/tests/test_litellm/responses/test_responses_api_request_body.py@@ -564,6 +564,24 @@ async def test_aresponses_regional_openai_api_base_marks_input_text():assert body["prompt_cache_options"] == {"mode": "explicit"}[email protected]("_no_openai_api_base_override")+def test_responses_custom_base_url_sends_no_openai_markers():+ with patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post") as mock_post:+ mock_post.return_value = MockResponse(_minimal_responses_api_payload("resp_pcb_gate_base_url", "gpt-5.6"), 200)++ litellm.responses(+ model="gpt-5.6",+ api_key="fake-api-key",+ base_url=_CUSTOM_API_BASE,+ input=copy.deepcopy(_INJECTION_POINT_INPUT),+ cache_control_injection_points=copy.deepcopy(_SYSTEM_INJECTION_POINT),+ )++ body = _sent_body(mock_post)+ assert body["input"] == _INJECTION_POINT_INPUT+ assert "prompt_cache_options" not in body++@pytest.mark.usefixtures("_no_openai_api_base_override")def test_responses_custom_api_base_sends_no_openai_markers():with patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post") as mock_post:diff --git a/tests/test_litellm/responses/test_responses_utils.py b/tests/test_litellm/responses/test_responses_utils.pyindex 35bf99db6dc..2f4a699d307 100644--- a/tests/test_litellm/responses/test_responses_utils.py+++ b/tests/test_litellm/responses/test_responses_utils.py@@ -671,6 +671,33 @@ class TestMergePromptManagementInputReshape:]assert result[1] == {"role": "user", "content": "hi"}+ def test_reshape_returns_copies_and_leaves_hook_output_untouched(self):+ user_part = {"type": "text", "text": "follow-up"}+ user_message = {"role": "user", "content": [user_part]}+ merged = [user_message]++ result = ResponsesAPIRequestUtils.merge_prompt_management_input(+ original_input="ignored", client_input=[], merged_input=merged+ )++ assert result == [{"role": "user", "content": [{"type": "input_text", "text": "follow-up"}]}]+ assert user_part == {"type": "text", "text": "follow-up"}+ assert user_message == {"role": "user", "content": [user_part]}+ assert result[0] is not user_message++ def test_reshape_keeps_non_message_items_when_hook_returns_client_objects(self):+ user_message = {"role": "user", "content": [{"type": "text", "text": "question"}]}+ reference = {"type": "item_reference", "id": "msg_123"}+ original_input = [reference, user_message]++ result = ResponsesAPIRequestUtils.merge_prompt_management_input(+ original_input=original_input, client_input=[user_message], merged_input=[user_message]+ )++ assert result == [reference, {"role": "user", "content": [{"type": "input_text", "text": "question"}]}]+ assert result[0] is reference+ assert user_message["content"] == [{"type": "text", "text": "question"}]+def test_assistant_text_parts_are_left_alone(self):merged = [{"role": "assistant", "content": [{"type": "text", "text": "earlier answer"}]},diff --git a/tests/test_litellm/test_main.py b/tests/test_litellm/test_main.pyindex 786adf2d78b..4b223a3a900 100644--- a/tests/test_litellm/test_main.py+++ b/tests/test_litellm/test_main.py@@ -2707,6 +2707,42 @@ def test_completion_custom_api_base_sends_no_prompt_cache_breakpoint_for_gpt_5_6assert "prompt_cache_options" not in json.dumps(request_body)[email protected]("_no_openai_api_base_override")+def test_completion_custom_base_url_sends_no_prompt_cache_breakpoint_for_gpt_5_6():+ from openai import OpenAI++ client = OpenAI(api_key="fake-api-key", base_url="http://127.0.0.1:9/v1")+ request_body = _openai_chat_create_kwargs(client, model="gpt-5.6", base_url="http://127.0.0.1:9/v1")++ assert request_body["messages"][0] == {"role": "system", "content": "sys", "cache_control": {"type": "ephemeral"}}+ assert "prompt_cache_breakpoint" not in json.dumps(request_body["messages"])+ assert "prompt_cache_options" not in json.dumps(request_body)++[email protected]("_no_openai_api_base_override")+async def test_acompletion_custom_base_url_sends_no_prompt_cache_breakpoint_for_gpt_5_6():+ from openai import AsyncOpenAI++ client = AsyncOpenAI(api_key="fake-api-key", base_url="http://127.0.0.1:9/v1")+ with patch.object(client.chat.completions.with_raw_response, "create") as mock_create:+ with contextlib.suppress(Exception):+ await litellm.acompletion(+ model="gpt-5.6",+ messages=[{"role": "system", "content": "sys"}, {"role": "user", "content": "hi"}],+ cache_control_injection_points=[{"location": "message", "role": "system"}],+ client=client,+ base_url="http://127.0.0.1:9/v1",+ )++ mock_create.assert_called_once()+ request_body = mock_create.call_args.kwargs++ assert request_body["messages"][0] == {"role": "system", "content": "sys", "cache_control": {"type": "ephemeral"}}+ assert "prompt_cache_breakpoint" not in json.dumps(request_body["messages"])+ assert "prompt_cache_options" not in json.dumps(request_body)++@pytest.mark.usefixtures("_no_openai_api_base_override")def test_completion_default_api_base_sends_prompt_cache_breakpoint_for_gpt_5_6():from openai import OpenAI