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/litellm_internal_staging' into litellm_fix_model_router_spend_log_model

ryan-crabbe-berric04b5dba32d7
diff --cc litellm/llms/azure_ai/common_utils.py
index 9d37d8d1185,d09055d7671..e8431f29f07
--- a/litellm/llms/azure_ai/common_utils.py
+++ b/litellm/llms/azure_ai/common_utils.py
@@@ -5,10 -5,52 +5,55 @@@ import litell
from litellm.llms.base_llm.base_utils import BaseLLMModelInfo, BaseTokenCounter
from litellm.secret_managers.main import get_secret_str
from litellm.types.llms.openai import AllMessageValues
+ from litellm.types.router import GenericLiteLLMParams
+
+ AzureAIApiKeyHeader = Literal["Authorization", "api-key", "Api-Key", "Ocp-Apim-Subscription-Key"]
+
+
+ def get_azure_ai_entra_token(litellm_params: Mapping[str, object] | None = None) -> str | None:
+ """
+ Resolve an Entra ID / OAuth access token for an Azure AI Foundry deployment.
+
+ Accepts the same credential set as the `azure` provider: service principal
+ (`tenant_id` / `client_id` / `client_secret`), a pre-fetched `azure_ad_token`, an OIDC
+ federated token, username/password, or `DefaultAzureCredential` / managed identity.
+ """
+ from litellm.llms.azure.common_utils import get_azure_ad_token
+
+ params = GenericLiteLLMParams.model_validate(litellm_params) if litellm_params else GenericLiteLLMParams()
+
+ return get_azure_ad_token(params)
+
+
+ def get_azure_ai_auth_headers(
+ api_key: str | None,
+ litellm_params: Mapping[str, object] | None = None,
+ api_key_header: AzureAIApiKeyHeader = "Authorization",
+ api_key_env_var: str = "AZURE_AI_API_KEY",
+ ) -> Mapping[str, str]:
+ """
+ Build the auth headers for an Azure AI Foundry route.
+
+ Prefers the API key when one is configured, and otherwise falls back to Entra ID / OAuth,
+ sending the access token as a bearer token.
+ """
+ if api_key:
+ return {api_key_header: f"Bearer {api_key}" if api_key_header == "Authorization" else api_key}
+
+ azure_ad_token = get_azure_ai_entra_token(litellm_params=litellm_params)
+ if azure_ad_token:
+ return {"Authorization": f"Bearer {azure_ad_token}"}
+
+ raise ValueError(
+ f"Missing Azure AI credentials - set an API key (`api_key` or {api_key_env_var}), or Entra ID / OAuth "
+ "credentials (`tenant_id` + `client_id` + `client_secret`, `azure_ad_token`, an OIDC token, or a managed "
+ "identity with `litellm.enable_azure_ad_token_refresh = True`)"
+ )
+
+AZURE_MODEL_ROUTER_SELECTED_MODEL_KEY: Final = "azure_model_router_selected_model"
+
+
class AzureFoundryModelInfo(BaseLLMModelInfo):
"""Model info for Azure AI / Azure Foundry models."""
diff --cc tests/test_litellm/litellm_core_utils/test_litellm_logging.py
index a0f7de6b320,1cac0cce4ef..1ed9fc3fad5
--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
+++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
@@@ -3729,82 -3867,6 +3867,90 @@@ def test_get_standard_logging_object_pa
assert payload["litellm_call_id"] == call_id
+# ── Azure Model Router selected-model attribution ────────────────────────────
+
+
+def _model_router_response(selected_model: str, stamp: bool):
+ """A ModelResponse as AzureModelRouterConfig hands it back, with or without the stamp."""
+ from litellm.llms.azure_ai.common_utils import (
+ AZURE_MODEL_ROUTER_SELECTED_MODEL_KEY,
+ )
+ from litellm.types.utils import ModelResponse
+
+ response = ModelResponse(model=selected_model)
- response._hidden_params = {AZURE_MODEL_ROUTER_SELECTED_MODEL_KEY: selected_model} if stamp else {}
++ response._hidden_params = (
++ {AZURE_MODEL_ROUTER_SELECTED_MODEL_KEY: selected_model} if stamp else {}
++ )
+ return response
+
+
+def test_standard_logging_payload_uses_stamped_model_router_model(logging_obj):
+ """
+ The selected model must win off the stamp, not off "model-router" appearing in the
+ requested model. An operator whose model group is named anything else was invisible
+ to the name check, so their logs and spend rows named the router instead.
+ """
+ import datetime
+
+ from litellm.litellm_core_utils.litellm_logging import (
+ get_standard_logging_object_payload,
+ )
+
+ now = datetime.datetime.now()
+ payload = get_standard_logging_object_payload(
+ kwargs={
+ "model": "azure_ai/smart-pick",
+ "custom_llm_provider": "azure_ai",
+ "messages": [],
+ "litellm_params": {"metadata": {}},
+ },
- init_response_obj=_model_router_response("azure_ai/grok-4-1-fast-reasoning", stamp=True),
++ init_response_obj=_model_router_response(
++ "azure_ai/grok-4-1-fast-reasoning", stamp=True
++ ),
+ start_time=now,
+ end_time=now,
+ logging_obj=logging_obj,
+ status="success",
+ )
+
+ assert payload is not None
+ assert payload["model"] == "azure_ai/grok-4-1-fast-reasoning"
+
+
- def test_standard_logging_payload_keeps_requested_model_without_router_stamp(logging_obj):
++def test_standard_logging_payload_keeps_requested_model_without_router_stamp(
++ logging_obj,
++):
+ """
+ Control for the test above: an ordinary azure_ai deployment is unaffected, so the stamp
+ is what redirects attribution rather than the response model winning unconditionally.
+ """
+ import datetime
+
+ from litellm.litellm_core_utils.litellm_logging import (
+ get_standard_logging_object_payload,
+ )
+
+ now = datetime.datetime.now()
+ payload = get_standard_logging_object_payload(
+ kwargs={
+ "model": "azure_ai/smart-pick",
+ "custom_llm_provider": "azure_ai",
+ "messages": [],
+ "litellm_params": {"metadata": {}},
+ },
- init_response_obj=_model_router_response("azure_ai/grok-4-1-fast-reasoning", stamp=False),
++ init_response_obj=_model_router_response(
++ "azure_ai/grok-4-1-fast-reasoning", stamp=False
++ ),
+ start_time=now,
+ end_time=now,
+ logging_obj=logging_obj,
+ status="success",
+ )
+
+ assert payload is not None
+ assert payload["model"] == "azure_ai/smart-pick"
+
+
def _make_dict_logging_obj():
"""Build a Logging instance configured for a non-streaming dict result."""
obj = LitellmLogging(
diff --cc tests/test_litellm/llms/azure_ai/chat/test_azure_ai_transformation.py
index 1f684ecc3b5,d4fcbc823a6..11a727c9635
--- a/tests/test_litellm/llms/azure_ai/chat/test_azure_ai_transformation.py
+++ b/tests/test_litellm/llms/azure_ai/chat/test_azure_ai_transformation.py
@@@ -201,80 -201,6 +201,90 @@@ def test_azure_model_router_response_sh
)
+def test_azure_model_router_stamps_selected_model_on_hidden_params():
+ """
+ The selected model must be stamped on _hidden_params, not left for downstream code to
+ re-derive by looking for "model-router" in the model string. Deployments whose alias
+ does not contain that text are invisible to the string check.
+ """
+ from httpx import Response
+
+ from litellm.llms.azure_ai.common_utils import (
+ AZURE_MODEL_ROUTER_SELECTED_MODEL_KEY,
+ AzureFoundryModelInfo,
+ )
+ from litellm.llms.base_llm.chat.transformation import LiteLLMLoggingObj
+ from litellm.types.utils import ModelResponse
+
+ raw_response_json = {
+ "id": "chatcmpl-test456",
+ "object": "chat.completion",
+ "created": 1234567890,
+ "model": "grok-4-1-fast-reasoning",
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "pong"},
+ "finish_reason": "stop",
+ }
+ ],
+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
+ }
+
+ mock_response = MagicMock(spec=Response)
+ mock_response.json.return_value = raw_response_json
+ mock_response.text = json.dumps(raw_response_json)
+ mock_response.headers = {}
+
+ logging_obj = MagicMock(spec=LiteLLMLoggingObj)
+ logging_obj.post_call = MagicMock()
+ logging_obj.model_call_details = {}
+
+ result = AzureModelRouterConfig().transform_response(
+ model="smart-pick",
+ raw_response=mock_response,
+ model_response=ModelResponse(),
+ logging_obj=logging_obj,
+ request_data={},
+ messages=[{"role": "user", "content": "Reply with just pong"}],
+ optional_params={},
+ litellm_params={"model": "azure_ai/model_router/smart-pick"},
+ encoding=None,
+ api_key="test-key",
+ json_mode=False,
+ )
+
+ assert result._hidden_params[AZURE_MODEL_ROUTER_SELECTED_MODEL_KEY] == result.model
- assert result._hidden_params[AZURE_MODEL_ROUTER_SELECTED_MODEL_KEY] == "azure_ai/grok-4-1-fast-reasoning"
- assert AzureFoundryModelInfo.get_model_router_selected_model(result._hidden_params) == (
- "azure_ai/grok-4-1-fast-reasoning"
++ assert (
++ result._hidden_params[AZURE_MODEL_ROUTER_SELECTED_MODEL_KEY]
++ == "azure_ai/grok-4-1-fast-reasoning"
++ )
++ assert AzureFoundryModelInfo.get_model_router_selected_model(
++ result._hidden_params
++ ) == ("azure_ai/grok-4-1-fast-reasoning")
++ assert (
++ AzureFoundryModelInfo.is_model_router_call(
++ model="smart-pick", hidden_params=result._hidden_params
++ )
++ is True
+ )
- assert AzureFoundryModelInfo.is_model_router_call(model="smart-pick", hidden_params=result._hidden_params) is True
+
+
+def test_azure_model_router_stamp_does_not_leak_across_responses():
+ """
+ ModelResponse declares _hidden_params as a class-level dict, so the stamp has to be written
+ as a fresh dict. Mutating in place would bleed the selected model into unrelated responses.
+ """
- from litellm.llms.azure_ai.common_utils import AZURE_MODEL_ROUTER_SELECTED_MODEL_KEY
++ from litellm.llms.azure_ai.common_utils import (
++ AZURE_MODEL_ROUTER_SELECTED_MODEL_KEY,
++ )
+ from litellm.types.utils import ModelResponse
+
+ untouched = ModelResponse()
+
+ assert AZURE_MODEL_ROUTER_SELECTED_MODEL_KEY not in (untouched._hidden_params or {})
+
+
def test_drop_tool_level_extra_fields_strips_copilot_mcp_server_name():
"""
Regression test: Azure AI returns 400 when tools contain copilot_mcp_server_name.
diff --cc tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py
index e9a22a75607,6c8e641642b..dab9415de77
--- a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py
+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py
@@@ -4,15 -4,8 +4,10 @@@ import jso
from datetime import timezone
from typing import Any, Final, cast
+from typing_extensions import ReadOnly, TypedDict
+
import pytest
- sys.path.insert(
- 0, os.path.abspath("../../../..")
- ) # Adds the parent directory to the system path
from unittest.mock import AsyncMock, MagicMock, patch
diff --cc tests/test_litellm/proxy/test_common_request_processing.py
index 562046b2f81,58714a5e319..c9b3e5faf8b
--- a/tests/test_litellm/proxy/test_common_request_processing.py
+++ b/tests/test_litellm/proxy/test_common_request_processing.py
@@@ -2207,52 -2294,6 +2294,54 @@@ class TestOverrideOpenAIResponseModel
assert response_obj.model == actual_model_used
assert response_obj.model != requested_model
- def test_override_model_preserves_model_router_model_for_alias_without_router_in_name(self):
++ def test_override_model_preserves_model_router_model_for_alias_without_router_in_name(
++ self,
++ ):
+ """
+ The client sends a model group alias, which carries no model_router/ prefix, so the
+ name check alone only fires when the operator happened to put "model-router" in the
+ alias. With the stamp on the response the actual model survives whatever it is named.
+ """
+ from litellm.llms.azure_ai.common_utils import (
+ AZURE_MODEL_ROUTER_SELECTED_MODEL_KEY,
+ )
+
+ requested_model = "smart-pick"
+ actual_model_used = "azure_ai/grok-4-1-fast-reasoning"
+
+ response_obj = MagicMock()
+ response_obj.model = actual_model_used
+ response_obj._hidden_params = {
+ "additional_headers": {},
+ AZURE_MODEL_ROUTER_SELECTED_MODEL_KEY: actual_model_used,
+ }
+
+ _override_openai_response_model(
+ response_obj=response_obj,
+ requested_model=requested_model,
+ log_context="test_context",
+ )
+ assert response_obj.model == actual_model_used
+
+ def test_override_model_still_restamps_non_router_alias_without_stamp(self):
+ """
+ Control for the test above: absent the stamp, an ordinary deployment keeps being
+ restamped to the requested model, so the stamp is doing the work rather than the
+ preserve branch having gone unconditional.
+ """
+ requested_model = "smart-pick"
+
+ response_obj = MagicMock()
+ response_obj.model = "azure_ai/grok-4-1-fast-reasoning"
+ response_obj._hidden_params = {"additional_headers": {}}
+
+ _override_openai_response_model(
+ response_obj=response_obj,
+ requested_model=requested_model,
+ log_context="test_context",
+ )
+ assert response_obj.model == requested_model
+
def test_override_model_uses_winning_model_for_fastest_response(self):
"""
Test that when fastest_response batch completion is used with a