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]

Merge remote-tracking branch 'origin/main' into litellm_explicit_cache_injection_points_survive_client_marks

mateo-berri9573fd4161c2
diff --cc litellm/integrations/anthropic_cache_control_hook.py
index cff7d23935c,494d9e0935a..f9b9238b181
--- a/litellm/integrations/anthropic_cache_control_hook.py
+++ b/litellm/integrations/anthropic_cache_control_hook.py
@@@ -307,44 -296,6 +310,60 @@@ class AnthropicCacheControlHook(CustomP
)
return system_blocks + sum(AnthropicCacheControlHook._count_cache_control_blocks(msg) for msg in messages)
+ @staticmethod
- def count_external_cache_breakpoints(tools: Iterable[object] | None, cache_control: object = None) -> int:
++ def count_external_cache_breakpoints(
++ tools: Iterable[object] | None, cache_control: object = None, request_kwargs: object = None
++ ) -> int:
+ """Client breakpoints outside messages and system that the provider cap still counts.
+
+ A tool carries its mark at the top level (Anthropic shape) or under ``function``
+ (OpenAI shape). A top-level ``cache_control`` is Anthropic's automatic caching,
- which places one breakpoint of its own on top of the explicit ones. Callers
- pass only the tools whose mark reaches the provider on their path.
++ which places one breakpoint of its own on top of the explicit ones. Marks the
++ client sends through the ``extra_body`` envelope of ``request_kwargs`` reach the
++ wire too and count the same way. Callers pass only the tools whose mark reaches
++ the provider on their path.
+ """
- automatic_blocks: Final = 1 if cache_control is not None else 0
- tool_blocks: Final = sum(1 for tool in tools if _tool_carries_cache_breakpoint(tool)) if tools else 0
- return automatic_blocks + tool_blocks
++ extra_body: Final = (
++ _validated_object_mapping(AnthropicCacheControlHook._request_value(request_kwargs, "extra_body")) or {}
++ )
++ automatic_blocks: Final = sum(
++ 1 for control in (cache_control, extra_body.get("cache_control")) if control is not None
++ )
++ tool_blocks: Final = sum(
++ 1
++ for tool in (*(tools or ()), *(_validated_object_list(extra_body.get("tools")) or ()))
++ if _tool_carries_cache_breakpoint(tool)
++ )
++ envelope_blocks: Final = AnthropicCacheControlHook.count_request_cache_breakpoints(
++ _validated_object_list(extra_body.get("messages")) or (), extra_body.get("system")
++ )
++ return automatic_blocks + tool_blocks + envelope_blocks
+
+ @staticmethod
+ def _blocks_reserved_outside_messages(
+ remaining_points: Sequence[CacheControlInjectionPoint], external_breakpoints: int, openai_dialect: bool
+ ) -> int:
+ """Slots of the provider cap that the message census cannot see.
+
+ The client's breakpoints on tools and its automatic top-level ``cache_control``
+ are already on the wire, and a ``tool_config`` point becomes one more cachePoint
+ in the Bedrock converse transform. OpenAI's cap counts only its own block markers.
+ """
+ if openai_dialect:
+ return 0
+ tool_config_blocks: Final = 1 if any(p.get("location") == "tool_config" for p in remaining_points) else 0
+ return external_breakpoints + tool_config_blocks
+
+ @staticmethod
+ def _points_with_a_slot_left(
+ remaining_points: Sequence[CacheControlInjectionPoint], breakpoints_on_wire: int, openai_dialect: bool
+ ) -> tuple[CacheControlInjectionPoint, ...]:
+ """A ``tool_config`` point becomes a cachePoint the Bedrock converse transform never
+ counts against the cap, so it is forwarded only while the wire still has a slot."""
+ if openai_dialect or breakpoints_on_wire < MAX_CACHE_CONTROL_BLOCKS:
+ return tuple(remaining_points)
+ return tuple(point for point in remaining_points if point.get("location") != "tool_config")
+
@staticmethod
def _apply_message_injections(
points: Sequence[CacheControlMessageInjectionPoint],
@@@ -663,18 -639,29 +682,20 @@@
system: str | list | None,
tools: list | None = None,
cache_control: object = None,
+ request_kwargs: object = None,
) -> bool:
- """Client breakpoints own caching in both the request and its extra_body envelope."""
- bodies: Final = (
- {"messages": messages, "system": system, "tools": tools, "cache_control": cache_control},
- _validated_object_mapping(AnthropicCacheControlHook._request_value(request_kwargs, "extra_body")) or {},
- )
- return any(
- body.get("cache_control") is not None
- or AnthropicCacheControlHook.count_request_cache_breakpoints(
- _validated_object_list(body.get("messages")) or (), body.get("system")
- )
- > 0
- or any(
- AnthropicCacheControlHook._request_value(tool, "cache_control") is not None
- or AnthropicCacheControlHook._request_value(
- AnthropicCacheControlHook._request_value(tool, "function"), "cache_control"
- )
- is not None
- for tool in (_validated_object_list(body.get("tools")) or ())
- )
- for body in bodies
- )
+ """Return True if the request already carries any client-supplied cache_control.
+
+ Only the automatic defaults stand down on it: a client that marks its own
+ breakpoints (Claude Code does) has a caching strategy the defaults would
- clash with. Configured injection points are an explicit instruction and are
++ clash with, whether the marks sit in the request or in its ``extra_body``
++ envelope. Configured injection points are an explicit instruction and are
+ applied alongside the client's marks, bounded by the provider cap.
+ """
+ return (
+ AnthropicCacheControlHook.count_request_cache_breakpoints(messages, system)
- + AnthropicCacheControlHook.count_external_cache_breakpoints(tools, cache_control)
++ + AnthropicCacheControlHook.count_external_cache_breakpoints(tools, cache_control, request_kwargs)
+ ) > 0
@staticmethod
def get_default_injection_points(
@@@ -797,23 -769,24 +803,25 @@@
) -> None:
"""For /chat/completions: resolve the injection points the request should carry.
- Configured injection points win over the automatic defaults, but stand
- down entirely when the client already marked its own cache_control
- breakpoints (messages or tools): injecting alongside them clashes with
- the client's caching strategy and can exceed the provider's four-block
- limit. The judgment happens once per request; points a prior pass
- wrote back carry the judged stamp and are never re-judged (see
- ``_should_stand_down``). Seeding the param lets the existing
- prompt-management gate and the AnthropicCacheControlHook run
- unchanged.
+ Configured injection points win over the automatic defaults and are applied
+ even when the client marked its own cache_control elsewhere in the request;
+ the provider's four-block cap bounds them, counting the client's marks on
+ messages, tools and the top-level ``cache_control``. Only the defaults stand
+ down on client marks. Seeding the param lets the existing prompt-management
+ gate and the AnthropicCacheControlHook run unchanged.
"""
+ import litellm
+
- if non_default_params.get("cache_control_injection_points"):
- judged: Final = AnthropicCacheControlHook._judged_configured_points(
- non_default_params["cache_control_injection_points"],
- messages,
- tools,
- non_default_params.get("cache_control"),
+ configured: Final = non_default_params.get("cache_control_injection_points")
+ if configured:
+ tools_keeping_marks: Final = tuple(
+ tool for tool in tools or () if not _chat_transform_drops_tool_cache_control(tool)
+ )
+ non_default_params["cache_control_injection_points"] = AnthropicCacheControlHook._stamped_for_prompt_hook(
+ configured,
+ AnthropicCacheControlHook.count_external_cache_breakpoints(
- tools_keeping_marks, non_default_params.get("cache_control")
++ tools_keeping_marks, non_default_params.get("cache_control"), non_default_params
+ ),
model,
custom_llm_provider,
api_base,
@@@ -964,7 -945,6 +972,9 @@@
system=system,
injection_points=injection_points,
openai_dialect=openai_dialect,
- external_breakpoints=AnthropicCacheControlHook.count_external_cache_breakpoints(tools, cache_control),
++ external_breakpoints=AnthropicCacheControlHook.count_external_cache_breakpoints(
++ tools, cache_control, kwargs
++ ),
)
breakpoints_added: Final = (
AnthropicCacheControlHook.count_request_cache_breakpoints(messages, system) - breakpoints_before
diff --cc tests/test_litellm/integrations/test_anthropic_cache_control_hook.py
index 2723526ae6b,83649c3386a..78aee3048ca
--- a/tests/test_litellm/integrations/test_anthropic_cache_control_hook.py
+++ b/tests/test_litellm/integrations/test_anthropic_cache_control_hook.py
@@@ -1664,6 -1595,178 +1664,182 @@@ class TestEnableAnthropicPromptCaching
assert supports_prompt_caching(model=model, custom_llm_provider=provider) is True
assert self._points(model=model, provider=provider) == []
+ @pytest.mark.parametrize("family", ["haiku-4-5", "sonnet-5", "opus-5", "fable-5", "fable-5-1"])
+ @pytest.mark.parametrize(
+ "provider, template",
+ [("anthropic", "{}"), ("vertex_ai", "{}"), ("azure_ai", "{}"), ("bedrock", "us.anthropic.{}-v1:0")],
+ )
+ @pytest.mark.parametrize("infer_provider", [False, True])
+ @pytest.mark.parametrize("supported", [False, True])
+ def test_claude_transport_defaults(self, monkeypatch, local_model_cost_map, family, provider, template, infer_provider, supported):
+ from litellm.utils import supports_prompt_caching
+
+ model = template.format(f"claude-{family}")
+ qualified = f"{provider}/{model}"
+ entry = {"litellm_provider": provider, "mode": "chat", "supports_prompt_caching": supported}
+ monkeypatch.setitem(litellm.model_cost, model, entry)
+ monkeypatch.setitem(litellm.model_cost, qualified, entry)
+ monkeypatch.setattr(litellm, "enable_anthropic_prompt_caching", False)
+ target = qualified if infer_provider else model
+ resolved_provider = None if infer_provider else provider
+ assert supports_prompt_caching(model=target, custom_llm_provider=resolved_provider) is supported
+ points = AnthropicCacheControlHook.get_default_injection_points(
+ messages=copy.deepcopy(self.MESSAGES), system=None, model=target,
+ custom_llm_provider=resolved_provider, enable_prompt_caching=True,
+ )
+ assert [point["index"] for point in points] == ([None, -1] if supported else [])
+ affinity_messages = AnthropicCacheControlHook.messages_with_default_injections(
+ copy.deepcopy(self.MESSAGES), models=[qualified], enable_prompt_caching=True,
+ )
+ assert sum(AnthropicCacheControlHook._count_cache_control_blocks(m) for m in affinity_messages) == (2 if supported else 0)
+
+ @pytest.mark.parametrize(
+ "provider, model",
+ [
+ ("bedrock", "us.openai.gpt-6-astra"),
+ ("bedrock", "amazon.nova-pro-v1:0"),
+ ("bedrock", "us.xai.grok-4.6"),
+ ("bedrock", "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/opaque"),
+ ("vertex_ai", "gemini-3.8-flash"),
+ ("azure_ai", "gpt-6-astra"),
+ ("anthropic", "unknown-model"),
+ ],
+ )
+ def test_non_claude_caching_capability_does_not_enable_defaults(self, monkeypatch, local_model_cost_map, provider, model):
+ from litellm.utils import supports_prompt_caching
+
+ qualified = f"{provider}/{model}"
+ entry = {"litellm_provider": provider, "mode": "chat", "supports_prompt_caching": True}
+ monkeypatch.setitem(litellm.model_cost, model, entry)
+ monkeypatch.setitem(litellm.model_cost, qualified, entry)
+ monkeypatch.setattr(litellm, "enable_anthropic_prompt_caching", True)
+ assert supports_prompt_caching(model=model, custom_llm_provider=provider)
+ assert self._points(model=model, provider=provider) == []
+ assert self._points(model=qualified, provider=None) == []
+ assert AnthropicCacheControlHook.messages_with_default_injections(self.MESSAGES, [qualified]) == self.MESSAGES
+
+ @pytest.mark.parametrize("provider", ["vertex_ai", "azure_ai"])
+ @pytest.mark.parametrize("client_control", ["none", "message", "system", "tool", "function", "top_level"])
+ @pytest.mark.parametrize("envelope", ["request", "extra_body"])
+ @pytest.mark.parametrize("configured", [False, True])
+ def test_new_transports_preserve_client_controls(self, monkeypatch, local_model_cost_map, provider, client_control, envelope, configured):
+ from litellm.llms.vertex_ai.vertex_ai_partner_models.anthropic.transformation import VertexAIAnthropicConfig
+
+ model = "claude-sonnet-5"
+ monkeypatch.setattr(litellm, "enable_anthropic_prompt_caching", True)
+ monkeypatch.setitem(litellm.model_cost, f"{provider}/{model}", {
+ **litellm.model_cost[f"{provider}/{model}"], "supports_prompt_caching": True,
+ })
+ control = {"type": "ephemeral"}
+ messages = [{"role": "user", "content": [{"type": "text", "text": "question", **({"cache_control": control} if client_control == "message" else {})}]}]
+ system = [{"type": "text", "text": "stable context", **({"cache_control": control} if client_control == "system" else {})}]
+ tools = [{"name": "lookup", "description": "Lookup", "input_schema": {"type": "object", "properties": {}}, **({"cache_control": control} if client_control == "tool" else {})}]
+ if client_control == "function":
+ tools = [{"type": "function", "function": {"name": "lookup", "parameters": {}, "cache_control": control}}]
+ kwargs = {"metadata": {}, "model_info": {"id": "selected-deployment"}, **({"cache_control": control} if client_control == "top_level" else {})}
+ if envelope == "extra_body":
+ kwargs["extra_body"] = {"messages": messages, "system": system, "tools": tools}
+ if "cache_control" in kwargs:
+ kwargs["extra_body"]["cache_control"] = kwargs.pop("cache_control")
+ messages, system, tools = [{"role": "user", "content": "question"}], "stable context", []
+ if configured:
+ kwargs["cache_control_injection_points"] = [
+ {"location": "message", "role": "system", "index": None, "control": control},
+ {"location": "message", "role": None, "index": -1, "control": control},
+ ]
+ seeded = copy.deepcopy(kwargs)
+ original = copy.deepcopy((messages, system, tools))
+ result_messages, result_system = AnthropicCacheControlHook.maybe_inject_cache_control(
+ messages, system, kwargs, model, provider, tools=tools,
+ )
- if client_control != "none":
++ if client_control != "none" and not configured:
+ assert (result_messages, result_system, tools) == original
+ assert kwargs["metadata"] == {}
+ else:
+ assert kwargs["metadata"]["litellm_gateway_injected_cache"] == "selected-deployment"
+ assert sum(AnthropicCacheControlHook._count_cache_control_blocks(m) for m in result_messages) == 1
+ assert result_system[0]["cache_control"] == control
++ assert result_messages[-1]["content"][-1]["cache_control"] == control
++ assert tools == original[2]
++ assert (result_messages == original[0]) == (envelope == "request" and client_control == "message")
++ assert (result_system == original[1]) == (envelope == "request" and client_control == "system")
+ if provider == "vertex_ai":
+ wire = VertexAIAnthropicConfig().transform_request(
+ model=model, messages=[{"role": "system", "content": result_system}, *result_messages],
+ optional_params={"max_tokens": 8}, litellm_params={}, headers={},
+ )
+ assert wire["system"][0]["cache_control"] == control
+ assert wire["messages"][-1]["content"][-1]["cache_control"] == control
+ affinity = AnthropicCacheControlHook.messages_with_default_injections(
+ [{"role": "system", "content": original[1]}, *original[0]], [f"{provider}/{model}"],
+ tools=tools, request_kwargs=seeded,
+ )
+ if client_control != "none":
+ assert affinity == [{"role": "system", "content": original[1]}, *original[0]]
+ AnthropicCacheControlHook.maybe_seed_default_injection_points(
+ seeded, [{"role": "system", "content": original[1]}, *original[0]], model, provider, tools=tools,
+ )
- assert bool(seeded.get("cache_control_injection_points")) == (client_control == "none")
++ assert bool(seeded.get("cache_control_injection_points")) == (client_control == "none" or configured)
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("asynchronous", [False, True])
+ @pytest.mark.parametrize("model, target, client_control, expected", [
+ ("vertex_ai/claude-sonnet-5", "bedrock/amazon.nova-pro-v1:0", False, 0),
+ ("azure_ai/gpt-6-astra", "azure_ai/claude-sonnet-5", False, 2),
+ ("azure_ai/claude-sonnet-5", None, False, 2),
+ ("azure_ai/claude-sonnet-5", None, True, 1),
+ ("azure_ai/model_router/claude-replacement", None, False, 2),
+ ])
+ async def test_public_completion_cache_ownership(self, monkeypatch, local_model_cost_map, asynchronous, model, target, client_control, expected):
+ import httpx
+ from litellm.llms.custom_httpx.http_handler import HTTPHandler
+
+ monkeypatch.setattr(litellm, "enable_anthropic_prompt_caching", True)
+ monkeypatch.setattr(litellm, "model_alias_map", {model: target} if target else {})
+ for qualified in (model, target):
+ if qualified:
+ provider = qualified.split("/")[0]
+ entry = {"litellm_provider": provider, "mode": "chat", "supports_prompt_caching": True}
+ monkeypatch.setitem(litellm.model_cost, qualified, entry)
+ monkeypatch.setitem(litellm.model_cost, qualified.split("/", 1)[-1], entry)
+ sent = []
+ def respond(request):
+ sent.append(json.loads(request.content))
+ return httpx.Response(200, request=request, json={
+ "id": "msg-test", "type": "message", "role": "assistant", "model": "claude-sonnet-5",
+ "content": [{"type": "text", "text": "ok"}], "stop_reason": "end_turn", "stop_sequence": None,
+ "output": {"message": {"role": "assistant", "content": [{"text": "ok"}]}}, "stopReason": "end_turn",
+ "usage": {"input_tokens": 10, "output_tokens": 1, "inputTokens": 10, "outputTokens": 1, "totalTokens": 11},
+ })
+ control = {"type": "ephemeral", "ttl": "1h"}
+ messages = [{"role": "system", "content": "stable context"}, {"role": "user", "content": "question"}]
+ metadata = {}
+ kwargs = {
+ "model": model, "messages": copy.deepcopy(messages), "max_tokens": 32, "num_retries": 0,
+ "litellm_metadata": metadata,
+ "api_base": "https://rig.services.ai.azure.com/anthropic", "api_key": "synthetic-test-key",
+ "aws_access_key_id": "synthetic", "aws_secret_access_key": "synthetic", "aws_region_name": "us-east-1",
+ **({"extra_body": {"cache_control": control}} if client_control else {}),
+ }
+ if asynchronous:
+ handler = AsyncHTTPHandler()
+ await handler.client.aclose()
+ async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client:
+ handler.client = client
+ response = await litellm.acompletion(**kwargs, client=handler)
+ else:
+ with httpx.Client(transport=httpx.MockTransport(respond)) as client:
+ response = litellm.completion(**kwargs, client=HTTPHandler(client=client))
+ assert response.choices[0].message.content == "ok"
+ assert len(sent) == 1
+ assert ("litellm_gateway_injected_cache" in metadata) == (expected == 2)
+ serialized = json.dumps(sent[0])
+ assert serialized.count('"cache_control"') + serialized.count('"cachePoint"') == expected
+ if client_control:
+ assert sent[0]["cache_control"] == control
+ affinity = AnthropicCacheControlHook.messages_with_default_injections(messages, [model], request_kwargs=kwargs)
+ assert AnthropicCacheControlHook.count_request_cache_breakpoints(affinity) == (2 if expected == 2 else 0)
+
def test_databricks_claude_not_injected_despite_caching_support(self, monkeypatch, local_model_cost_map):
from litellm.utils import supports_prompt_caching
@@@ -2388,7 -2363,12 +2564,39 @@@ class TestConfiguredInjectionPointsSurv
_, result_sys = self._inject(copy.deepcopy(self.V1_MESSAGES), kwargs)
assert result_sys == [{"type": "text", "text": "sys", "cache_control": {"type": "ephemeral"}}]
+ @pytest.mark.parametrize(
- "configured",
- [None, CONFIGURED],
- ids=["automatic_defaults", "configured_points"],
++ "extra_body,injected",
++ [
++ ({"tools": [MARKED_TOOL_TOP_LEVEL]}, 0),
++ ({"cache_control": {"type": "ephemeral"}}, 0),
++ ({"tools": [UNMARKED_TOOL]}, 1),
++ ],
++ ids=["marked_tool", "root_cache_control", "unmarked_tool"],
++ )
++ def test_chat_cap_counts_client_marks_sent_through_extra_body(self, extra_body, injected):
++ """Marks a client sends inside ``extra_body`` reach the wire like any other, so
++ the seeding pass has to count them or a configured point lands as a fifth block."""
++ messages = [{"role": "system", "content": "sys"}, *self._marked_user_turns(3)]
++ params = {"cache_control_injection_points": copy.deepcopy(self.CONFIGURED), "extra_body": extra_body}
++ self._seed(params, copy.deepcopy(messages))
++ processed = self._chat(params, copy.deepcopy(messages))
++ assert _count_cache_control(processed) == 3 + injected
++
++ @pytest.mark.parametrize(
++ "extra_body,expected_system",
++ [
++ ({"cache_control": {"type": "ephemeral"}}, "sys"),
++ ({"tools": [MARKED_V1_TOOL]}, "sys"),
++ ({"tools": [UNMARKED_V1_TOOL]}, [{"type": "text", "text": "sys", "cache_control": {"type": "ephemeral"}}]),
++ ],
++ ids=["root_cache_control", "marked_tool", "unmarked_tool"],
+ )
- def test_v1_messages_stands_down_for_root_cache_control(self, monkeypatch, configured):
++ def test_v1_messages_cap_counts_client_marks_sent_through_extra_body(self, extra_body, expected_system):
++ kwargs = {"cache_control_injection_points": copy.deepcopy(self.CONFIGURED), "extra_body": extra_body}
++ _, result_sys = self._inject(self._marked_user_turns(3), kwargs)
++ assert result_sys == expected_system
++
+ def test_v1_messages_automatic_defaults_stand_down_for_root_cache_control(self, monkeypatch):
monkeypatch.setattr(litellm, "enable_anthropic_prompt_caching", True)
root_cache_control = {"type": "ephemeral"}
kwargs = {"cache_control": root_cache_control, "litellm_metadata": {}}