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
Merge branch 'main' into litellm_add_edenai_provider
yassin7dc9609109e5
diff --cc litellm/integrations/anthropic_cache_control_hook.pyindex 4f9b18713d0,0d6cbc2232e..494d9e0935a--- a/litellm/integrations/anthropic_cache_control_hook.py+++ b/litellm/integrations/anthropic_cache_control_hook.py@@@ -574,12 -652,19 +577,13 @@@ class AnthropicCacheControlHook(CustomPcustom_llm_provider: str | None,api_base: object,prompt_cache_options: object,- ) -> Sequence[Mapping[str, object]]:- """Carry onto the points what the prompt-management hook never receives.-- The hook sees neither the tools nor the request kwargs, so the target dialect- and the client's breakpoint count outside the message list ride on the points.- Builds copies because config-owned point dicts are shared across requests.- """- with_dialect: Final = AnthropicCacheControlHook._stamped_with_dialect(++ request_kwargs: object,+ ) -> Sequence[Mapping[str, object]] | None:- if AnthropicCacheControlHook._should_stand_down(points, messages, None, tools, cache_control):++ if AnthropicCacheControlHook._should_stand_down(points, messages, None, tools, cache_control, request_kwargs):+ return None+ return AnthropicCacheControlHook._stamped_with_dialect(points, model, custom_llm_provider, api_base, prompt_cache_options)- if external_breakpoints == 0:- return with_dialect- return AnthropicCacheControlHook._stamped(with_dialect, EXTERNAL_BREAKPOINTS_STAMP, external_breakpoints)@staticmethoddef _stamped_with_dialect(@@@ -600,63 -685,29 +604,64 @@@)@staticmethod- def _stamped(points: Sequence[Mapping[str, object]], key: str, value: object) -> Sequence[Mapping[str, object]]:+ def _stamped(+ points: Sequence[CacheControlInjectionPoint], key: str, value: object+ ) -> Sequence[Mapping[str, object]]:return [{**point, key: value} for point in points]+ @staticmethod+ def _should_stand_down(+ points: Sequence[CacheControlInjectionPoint],+ messages: list[AllMessageValues],+ system: str | list | None,+ tools: list | None,+ cache_control: object = None,++ request_kwargs: object = None,+ ) -> bool:+ """Whether configured injection points must yield to client-set cache_control.++ Points that a prior pass over this request already judged and wrote+ back carry the internal judged stamp; any re-entry (acompletion+ re-entering completion, the async-to-sync /v1/messages dispatch,+ interceptor sub-calls reusing the request kwargs) must not re-judge+ them, because by then the messages carry litellm's own injected marks+ and the judgment would misread those as client breakpoints.+ """+ if all(point.get("_litellm_judged") for point in points):+ return False- return AnthropicCacheControlHook._request_has_cache_control(messages, system, tools, cache_control)++ return AnthropicCacheControlHook._request_has_cache_control(++ messages, system, tools, cache_control, request_kwargs++ )+@staticmethoddef _request_has_cache_control(messages: list[AllMessageValues],system: str | list | None,tools: list | None = None,cache_control: object = None,+ request_kwargs: object = None,) -> bool:-- """Return True if the request already carries any client-supplied cache_control.--- When the client (e.g. Claude Code) already marks its own breakpoints we- stand down entirely rather than add more, per the auto-caching contract.- Tools count: they are a breakpoint the client can mark, they count toward- the provider's four-block limit, and caching only the tool definitions is- a common pattern, so injecting alongside them can exceed the cap. Tools- carry the mark either at the top level (Anthropic shape) or nested under- ``function`` (OpenAI shape); the Anthropic chat transform accepts both.- 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, 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.-- """- if cache_control is not None:- return True- if AnthropicCacheControlHook.count_request_cache_breakpoints(messages, system) > 0:- return True- if tools is not None:- return any(- isinstance(tool, dict)- and (- tool.get("cache_control") is not None- or (isinstance(tool.get("function"), dict) and tool["function"].get("cache_control") is not None)- return (- AnthropicCacheControlHook.count_request_cache_breakpoints(messages, system)- + AnthropicCacheControlHook.count_external_cache_breakpoints(tools, cache_control, request_kwargs)- ) > 0++ """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"+ )- for tool in tools++ is not None++ for tool in (_validated_object_list(body.get("tools")) or ())+ )- return False++ for body in bodies++ )@staticmethoddef get_default_injection_points(@@@ -779,31 -815,30 +769,34 @@@) -> None:"""For /chat/completions: resolve the injection points the request should carry.- 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.+ 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."""+ import litellm+- 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"), non_default_params- ),+ 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"),model,custom_llm_provider,api_base,non_default_params.get("prompt_cache_options"),++ non_default_params,)+ if judged is None:+ non_default_params.pop("cache_control_injection_points")+ else:+ non_default_params["cache_control_injection_points"] = judgedreturnpoints: Final = AnthropicCacheControlHook.get_default_injection_points(messages=messages,@@@ -924,13 -958,8 +917,13 @@@configured: Final = cast( # cast-ok: kwargs is untyped; this key only holds the documented injection-point listlist[CacheControlInjectionPoint] | None, kwargs.pop("cache_control_injection_points", None))- injection_points: Final[Sequence[CacheControlInjectionPoint]] = configured or (- AnthropicCacheControlHook.get_default_injection_points(+ if configured and AnthropicCacheControlHook._should_stand_down(- configured, typed_messages, system, tools, cache_control++ configured, typed_messages, system, tools, cache_control, kwargs+ ):+ return messages, system+ injection_points: list[CacheControlInjectionPoint] = configured or []+ if not injection_points and model is not None:+ injection_points = AnthropicCacheControlHook.get_default_injection_points(messages=typed_messages,system=system,tools=tools,diff --cc litellm/llms/azure_ai/common_utils.pyindex 0665b3f64c5,cffe9049de6..d5a05cb8ea5--- a/litellm/llms/azure_ai/common_utils.py+++ b/litellm/llms/azure_ai/common_utils.py@@@ -70,6 -140,25 +139,17 @@@ def get_azure_ai_auth_headersAZURE_MODEL_ROUTER_SELECTED_MODEL_KEY: Final = "azure_model_router_selected_model"+ def azure_ai_supports_native_responses(model: str | None, api_base: str | None) -> bool:+ resolved_base: Final = AzureFoundryModelInfo.get_api_base(api_base)+ if resolved_base is not None and not is_azure_openai_v1_host(resolved_base):+ return False+ if model is None:+ return True+ if "claude" in model.lower():+ return False+ return AzureFoundryModelInfo.get_azure_ai_route(model) == "default"++-def foundry_chat_rejects_function_tools_while_reasoning(- model: str, reasoning_effort: str | Mapping[str, object] | None-) -> bool:- if reasoning_effort is None:- return OpenAIGPT5Config.is_model_gpt_6_plus_model(model)- return OpenAIGPT5Config.is_model_gpt_5_6_plus_model(model)--class AzureFoundryModelInfo(BaseLLMModelInfo):"""Model info for Azure AI / Azure Foundry models."""diff --cc litellm/llms/edenai/audio_transcription/transformation.pyindex 236353defa6,00000000000..fc8a13d5ccdmode 100644,000000..100644--- a/litellm/llms/edenai/audio_transcription/transformation.py+++ b/litellm/llms/edenai/audio_transcription/transformation.py@@@ -1,87 -1,0 +1,91 @@@+"""+Support for OpenAI's `/v1/audio/transcriptions` endpoint on Eden AI, served at `/v3/audio/transcriptions`+with the real per-request cost at the top level of the JSON body.++Docs: https://www.edenai.co/docs/api-reference/audio/audio-transcriptions+"""++from collections.abc import Mapping+from typing import Final++import httpx++from litellm.litellm_core_utils.audio_utils.utils import process_audio_file+from litellm.litellm_core_utils.core_helpers import set_response_cost_in_hidden_params+from litellm.llms.base_llm.audio_transcription.transformation import AudioTranscriptionRequestData+from litellm.llms.base_llm.chat.transformation import BaseLLMException+from litellm.llms.openai.transcriptions.whisper_transformation import OpenAIWhisperAudioTranscriptionConfig+from litellm.types.llms.openai import AllMessageValues+from litellm.types.utils import FileTypes, TranscriptionResponse+from litellm.utils import convert_to_model_response_object++from ..common_utils import EdenAIException, authorized_headers, endpoint_url, reported_cost+++def _form_fields(model: str, optional_params: Mapping[str, object]) -> dict[str, object]: # mutable-ok: httpx form data+ """LiteLLM parks non-OpenAI params, `model` included, under `extra_body` for the OpenAI SDK; a+ multipart body carries them as top-level text fields instead."""+ extras: Final = optional_params.get("extra_body")+ nested: Final = extras.items() if isinstance(extras, Mapping) else ()+ fields: Final = (*optional_params.items(), *nested, ("model", model))+ return {key: value for key, value in fields if key != "extra_body"} # mutable-ok: httpx form data+++class EdenAIAudioTranscriptionConfig(OpenAIWhisperAudioTranscriptionConfig):++ @property++ def has_native_transcription_endpoint(self) -> bool:++ return True+++ def get_complete_url(+ self,+ api_base: str | None,+ api_key: str | None,+ model: str,+ optional_params: dict[str, object], # mutable-ok: inherited contract+ litellm_params: dict[str, object], # mutable-ok: inherited contract+ stream: bool | None = None,+ ) -> str:+ return endpoint_url(api_base, "audio/transcriptions")++ def validate_environment(+ self,+ headers: dict[str, object], # mutable-ok: inherited contract+ model: str,+ messages: list[AllMessageValues], # mutable-ok: inherited contract+ optional_params: dict[str, object], # mutable-ok: inherited contract+ litellm_params: dict[str, object], # mutable-ok: inherited contract+ api_key: str | None = None,+ api_base: str | None = None,+ ) -> dict[str, object]: # mutable-ok: inherited contract+ return authorized_headers(headers, api_key, model)++ def transform_audio_transcription_request(+ self,+ model: str,+ audio_file: FileTypes,+ optional_params: dict[str, object], # mutable-ok: inherited contract+ litellm_params: dict[str, object], # mutable-ok: inherited contract+ ) -> AudioTranscriptionRequestData:+ """Eden reports `duration` and `cost` on every body, so the Whisper default of `verbose_json`,+ which the gpt-4o-transcribe models reject, is not needed for cost tracking."""+ audio: Final = process_audio_file(audio_file)+ files: Final = {"file": (audio.filename, audio.file_content, audio.content_type)} # mutable-ok: httpx contract+ return AudioTranscriptionRequestData(data=_form_fields(model, optional_params), files=files)++ def transform_audio_transcription_response(self, raw_response: httpx.Response) -> TranscriptionResponse:+ if "application/json" not in raw_response.headers.get("content-type", ""):+ return TranscriptionResponse(text=raw_response.text)+ body: Final = raw_response.json()+ response: Final[TranscriptionResponse] = convert_to_model_response_object(+ response_object=body, model_response_object=TranscriptionResponse(), response_type="audio_transcription"+ )+ set_response_cost_in_hidden_params(response, reported_cost(body))+ return response++ def get_error_class(+ self,+ error_message: str,+ status_code: int,+ headers: dict[str, object] | httpx.Headers, # mutable-ok: inherited contract+ ) -> BaseLLMException:+ return EdenAIException(message=error_message, status_code=status_code, headers=headers)diff --cc tests/test_litellm/integrations/test_anthropic_cache_control_hook.pyindex 6b7780acd20,7bf4533979a..83649c3386a--- a/tests/test_litellm/integrations/test_anthropic_cache_control_hook.py+++ b/tests/test_litellm/integrations/test_anthropic_cache_control_hook.py@@@ -5,12 -4,11 +4,10 @@@ import oimport subprocessimport sysimport textwrap- import unittest-from typing import Final, List, Optional, Tuple+from typing import List, Optional, Tuple- from unittest.mock import ANY, MagicMock, Mock, patch+ from unittest.mock import MagicMock, patch- import httpximport pytest-from pydantic import BaseModel, ConfigDictimport litellmfrom litellm.integrations.anthropic_cache_control_hook import (@@@ -1599,6 -1673,182 +1595,178 @@@ class TestEnableAnthropicPromptCachingassert supports_prompt_caching(model=model, custom_llm_provider=provider) is Trueassert 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" and not configured:++ if client_control != "none":+ 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" or configured)++ assert bool(seeded.get("cache_control_injection_points")) == (client_control == "none")++ @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_cachingdiff --cc tests/test_litellm/litellm_core_utils/test_litellm_logging.pyindex 504421400ec,325052ebda9..277ae33a076--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py+++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py@@@ -23,7 -24,8 +24,8 @@@ from litellm.litellm_core_utils.litellm_get_status_fields,set_callbacks,)+ from litellm.llms.base_llm.ocr.transformation import OCRUsageInfo-from litellm.types.llms.openai import ResponseAPIUsage, ResponsesAPIResponse+from litellm.types.llms.openai import ResponseAPIUsage, ResponseCompletedEvent, ResponsesAPIResponsefrom litellm.types.utils import (CallTypes,LiteLLMRealtimeStreamLoggingObject,@@@ -7081,53 -7247,171 +7247,223 @@@ def test_get_additional_headers_survive_run_while_a_thread_grows(headers, read, reads=300)+ def test_add_dynamic_callback_registers_once_per_list_without_touching_the_callers_list(logging_obj: LitellmLogging):+ callback: Final = CustomLogger()+ caller_owned: Final = ["langfuse"]+ logging_obj.dynamic_success_callbacks = caller_owned++ logging_obj.add_dynamic_callback(callback)+ logging_obj.add_dynamic_callback(callback)++ assert caller_owned == ["langfuse"]+ assert logging_obj.dynamic_success_callbacks == ["langfuse", callback]+ assert logging_obj.dynamic_input_callbacks == [callback]+ assert logging_obj.dynamic_async_success_callbacks == [callback]+ assert logging_obj.dynamic_failure_callbacks == [callback]+ assert logging_obj.dynamic_async_failure_callbacks == [callback]+ assert LitellmLogging._with_dynamic_callback(None, callback) == [callback]+ assert LitellmLogging._with_dynamic_callback((callback,), callback) == [callback]+++ class TestAzurePTUSpilloverCost:+ """Azure PTU deployments price tokens at zero because the reservation is billed flat.++ A request Azure spills onto pay-as-you-go capacity must bill per token instead, so+ the zeroed custom pricing has to be skipped when the provider reports spillover.+ """++ ROUTER_MODEL_ID: Final = "ptu-spill-router-model-id"+ SERVED_MODEL: Final = "azure/spill-served-model-ptu"+ PTU_MODEL_INFO: Final = {+ "id": ROUTER_MODEL_ID,+ "team_id": "team-1",+ "ptu_count": 100,+ "cost_per_ptu_per_hour": 1.0,+ "ptu_effective_from": "2026-01-01",+ "input_cost_per_token": 0.0,+ "output_cost_per_token": 0.0,+ }+ EXPECTED_SPILL_COST: Final = 100 * 2e-6 + 50 * 8e-6++ @staticmethod+ def _register_models() -> None:+ litellm.register_model(+ model_cost={+ TestAzurePTUSpilloverCost.ROUTER_MODEL_ID: {+ "input_cost_per_token": 0.0,+ "output_cost_per_token": 0.0,+ "litellm_provider": "azure",+ "mode": "chat",+ },+ TestAzurePTUSpilloverCost.SERVED_MODEL: {+ "input_cost_per_token": 2e-6,+ "output_cost_per_token": 8e-6,+ "litellm_provider": "azure",+ "mode": "chat",+ },+ }+ )++ @staticmethod+ def _unregister_models() -> None:+ litellm.model_cost.pop(TestAzurePTUSpilloverCost.ROUTER_MODEL_ID, None)+ litellm.model_cost.pop(TestAzurePTUSpilloverCost.SERVED_MODEL, None)++ def _logging_obj(self, model_info: dict, *, flag: str, litellm_rate: float, monkeypatch) -> LitellmLogging:+ monkeypatch.setenv("LITELLM_ENABLE_PTU_COST_ATTRIBUTION", flag)+ obj = LitellmLogging(+ model=self.SERVED_MODEL,+ messages=[{"role": "user", "content": "Hi"}],+ stream=False,+ call_type="completion",+ start_time=time.time(),+ litellm_call_id="ptu-spill-1",+ function_id="f",+ )+ obj.update_environment_variables(+ model=self.SERVED_MODEL,+ user="",+ optional_params={},+ litellm_params={+ "api_base": "",+ "metadata": {"model_info": model_info},+ "input_cost_per_token": litellm_rate,+ "output_cost_per_token": litellm_rate,+ },+ custom_llm_provider="azure",+ )+ return obj++ @staticmethod+ def _response() -> ModelResponse:+ from litellm.types.utils import Usage++ return ModelResponse(+ id="chatcmpl-spill-1",+ created=1234567890,+ model="spill-served-model-ptu",+ choices=[+ {+ "index": 0,+ "message": {"role": "assistant", "content": "ok"},+ "finish_reason": "stop",+ }+ ],+ usage=Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150),+ )++ def test_spillover_via_response_additional_headers_bills_per_token(self, monkeypatch) -> None:+ self._register_models()+ try:+ obj = self._logging_obj(dict(self.PTU_MODEL_INFO), flag="True", litellm_rate=0.0, monkeypatch=monkeypatch)+ response = self._response()+ response._hidden_params["additional_headers"] = {"llm_provider-x-ms-is-spilled-over": "true"}++ assert obj._response_cost_calculator(result=response) == pytest.approx(self.EXPECTED_SPILL_COST)+ finally:+ self._unregister_models()++ def test_spillover_via_streaming_response_headers_bills_per_token(self, monkeypatch) -> None:+ self._register_models()+ try:+ obj = self._logging_obj(dict(self.PTU_MODEL_INFO), flag="True", litellm_rate=0.0, monkeypatch=monkeypatch)+ obj.model_call_details["response_headers"] = {+ "x-ms-is-spilled-over": "true",+ "x-ms-spillover-from-deployment": "ptu-dep",+ }++ assert obj._response_cost_calculator(result=self._response()) == pytest.approx(self.EXPECTED_SPILL_COST)+ finally:+ self._unregister_models()++ def test_non_spilled_ptu_request_stays_zero_priced(self, monkeypatch) -> None:+ self._register_models()+ try:+ obj = self._logging_obj(dict(self.PTU_MODEL_INFO), flag="True", litellm_rate=0.0, monkeypatch=monkeypatch)++ assert obj._response_cost_calculator(result=self._response()) == 0.0+ finally:+ self._unregister_models()++ def test_spillover_header_without_the_flag_stays_zero_priced(self, monkeypatch) -> None:+ self._register_models()+ try:+ obj = self._logging_obj(dict(self.PTU_MODEL_INFO), flag="", litellm_rate=0.0, monkeypatch=monkeypatch)+ response = self._response()+ response._hidden_params["additional_headers"] = {"llm_provider-x-ms-is-spilled-over": "true"}++ assert obj._response_cost_calculator(result=response) == 0.0+ finally:+ self._unregister_models()++ def test_spillover_header_does_not_touch_non_ptu_custom_pricing(self, monkeypatch) -> None:+ self._register_models()+ custom_model_id: Final = "non-ptu-custom-router-model-id"+ litellm.model_cost[custom_model_id] = {+ "input_cost_per_token": 1e-6,+ "output_cost_per_token": 1e-6,+ "litellm_provider": "azure",+ "mode": "chat",+ }+ try:+ model_info: Final = {"id": custom_model_id, "input_cost_per_token": 1e-6}+ obj = self._logging_obj(model_info, flag="True", litellm_rate=1e-6, monkeypatch=monkeypatch)+ response = self._response()+ response._hidden_params["additional_headers"] = {"llm_provider-x-ms-is-spilled-over": "true"}++ assert obj._response_cost_calculator(result=response) == pytest.approx(150 * 1e-6)+ finally:+ litellm.model_cost.pop(custom_model_id, None)+ self._unregister_models()+++++def _completed_responses_event(usage: ResponseAPIUsage) -> ResponseCompletedEvent:+ return ResponseCompletedEvent(+ type="response.completed",+ response=ResponsesAPIResponse(+ id="resp-1", created_at=1, object="response", status="completed", model="codex-mini-latest", output=[], usage=usage+ ),+ )+++def _responses_stream_logging_obj() -> LitellmLogging:+ logging_obj = _make_logging_obj(stream=True)+ logging_obj.update_environment_variables(+ model="openai/codex-mini-latest", user="", optional_params={}, litellm_params={"api_base": ""}+ )+ return logging_obj+++def test_get_assembled_streaming_response_bills_a_provider_reported_usage_cost():+ """A Responses stream whose completed event carries ``usage.cost`` is billed that number,+ the way an assembled chat stream already is, instead of a price-map estimate."""+ logging_obj = _responses_stream_logging_obj()+ now = datetime.datetime.now()++ assembled = logging_obj._get_assembled_streaming_response(+ result=_completed_responses_event(ResponseAPIUsage(input_tokens=12, output_tokens=2, total_tokens=14, cost=0.0042)),+ start_time=now,+ end_time=now,+ is_async=True,+ streaming_chunks=[],+ )++ assert assembled._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"] == 0.0042+ assert logging_obj._response_cost_calculator(result=assembled) == 0.0042+++def test_get_assembled_streaming_response_without_usage_cost_leaves_pricing_to_the_price_map():+ logging_obj = _responses_stream_logging_obj()+ now = datetime.datetime.now()++ assembled = logging_obj._get_assembled_streaming_response(+ result=_completed_responses_event(ResponseAPIUsage(input_tokens=12, output_tokens=2, total_tokens=14)),+ start_time=now,+ end_time=now,+ is_async=True,+ streaming_chunks=[],+ )++ assert "additional_headers" not in assembled._hidden_params+ price_map_cost = logging_obj._response_cost_calculator(result=assembled)+ assert price_map_cost is not None and 0 < price_map_cost != 0.0042