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]

feat(azure_ai): support entra id / oauth auth on every azure ai foundry route

mateoabf7dab0c282
diff --git a/litellm/images/main.py b/litellm/images/main.py
index 17ea9aa177b..4c88eb52cd8 100644
--- a/litellm/images/main.py
+++ b/litellm/images/main.py
@@ -430,24 +430,31 @@ def image_generation(
aimg_generation=aimg_generation,
)
elif custom_llm_provider == "azure_ai":
- from litellm.llms.azure_ai.common_utils import AzureFoundryModelInfo
+ from litellm.llms.azure_ai.common_utils import (
+ AzureFoundryModelInfo,
+ get_azure_ai_auth_headers,
+ )
api_base = AzureFoundryModelInfo.get_api_base(api_base)
api_key = AzureFoundryModelInfo.get_api_key(api_key)
if extra_headers is not None:
optional_params["extra_headers"] = extra_headers
- default_headers = {
+ caller_set_auth = "api-key" in headers or "Authorization" in headers
+ auth_headers = (
+ headers
+ if caller_set_auth
+ else get_azure_ai_auth_headers(
+ api_key=api_key,
+ litellm_params=litellm_params_dict,
+ api_key_header="api-key",
+ )
+ )
+ headers = {
"Content-Type": "application/json",
+ **auth_headers,
+ **headers,
}
- # Only add api-key header if api_key is not None
- # Azure AD authentication will use Authorization header instead
- if api_key is not None:
- default_headers["api-key"] = api_key
-
- for k, v in default_headers.items():
- if k not in headers:
- headers[k] = v
model_response = azure_chat_completions.image_generation(
model=model,
diff --git a/litellm/llms/azure/common_utils.py b/litellm/llms/azure/common_utils.py
index 91f5793e269..85100e595e6 100644
--- a/litellm/llms/azure/common_utils.py
+++ b/litellm/llms/azure/common_utils.py
@@ -2,6 +2,7 @@ import asyncio
import hashlib
import json
import os
+from functools import lru_cache
from typing import Any, Callable, Dict, Literal, NamedTuple, Optional, Union, cast
import httpx
@@ -57,6 +58,24 @@ def process_azure_headers(headers: Union[httpx.Headers, dict]) -> dict:
return {**llm_response_headers, **openai_headers}
+@lru_cache(maxsize=128)
+def _cached_entra_id_token_provider(
+ tenant_id: str,
+ client_id: str,
+ client_secret: str,
+ scope: str,
+) -> Callable[[], str]:
+ """Build (once per credential set) a bearer token provider backed by a `ClientSecretCredential`.
+
+ The credential caches the access token internally and only talks to Entra ID when it is close
+ to expiry, so reusing the provider keeps one AAD round trip per token lifetime instead of one
+ per request.
+ """
+ from azure.identity import ClientSecretCredential, get_bearer_token_provider
+
+ return get_bearer_token_provider(ClientSecretCredential(tenant_id, client_id, client_secret), scope)
+
+
def get_azure_ad_token_from_entra_id(
tenant_id: str,
client_id: str,
@@ -75,8 +94,6 @@ def get_azure_ad_token_from_entra_id(
Returns:
callable that returns a bearer token.
"""
- from azure.identity import ClientSecretCredential, get_bearer_token_provider
-
verbose_logger.debug("Getting Azure AD Token from Entra ID")
if tenant_id.startswith("os.environ/"):
@@ -102,9 +119,13 @@ def get_azure_ad_token_from_entra_id(
)
if _tenant_id is None or _client_id is None or _client_secret is None:
raise ValueError("tenant_id, client_id, and client_secret must be provided")
- credential = ClientSecretCredential(_tenant_id, _client_id, _client_secret)
- token_provider = get_bearer_token_provider(credential, scope)
+ token_provider = _cached_entra_id_token_provider(
+ tenant_id=_tenant_id,
+ client_id=_client_id,
+ client_secret=_client_secret,
+ scope=scope,
+ )
verbose_logger.debug("token_provider %s", token_provider)
diff --git a/litellm/llms/azure_ai/common_utils.py b/litellm/llms/azure_ai/common_utils.py
index 9965aa693c3..5dd5f5c78cc 100644
--- a/litellm/llms/azure_ai/common_utils.py
+++ b/litellm/llms/azure_ai/common_utils.py
@@ -1,9 +1,54 @@
+from collections.abc import Mapping
from typing import List, Literal, Optional
import litellm
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",
+) -> dict[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`)"
+ )
class AzureFoundryModelInfo(BaseLLMModelInfo):
@@ -43,7 +88,7 @@ class AzureFoundryModelInfo(BaseLLMModelInfo):
@staticmethod
def get_api_key(api_key: Optional[str] = None) -> Optional[str]:
- return api_key or litellm.api_key or litellm.openai_key or get_secret_str("AZURE_AI_API_KEY")
+ return api_key or litellm.api_key or get_secret_str("AZURE_AI_API_KEY")
@property
def api_version(self, api_version: Optional[str] = None) -> Optional[str]:
diff --git a/litellm/llms/azure_ai/image_edit/flux2_transformation.py b/litellm/llms/azure_ai/image_edit/flux2_transformation.py
index 1bc3bdcddc1..db429b85082 100644
--- a/litellm/llms/azure_ai/image_edit/flux2_transformation.py
+++ b/litellm/llms/azure_ai/image_edit/flux2_transformation.py
@@ -5,7 +5,10 @@ from typing import Any, Dict, Optional, Tuple
from httpx._types import RequestFiles
import litellm
-from litellm.llms.azure_ai.common_utils import AzureFoundryModelInfo
+from litellm.llms.azure_ai.common_utils import (
+ AzureFoundryModelInfo,
+ get_azure_ai_auth_headers,
+)
from litellm.llms.azure_ai.image_generation.flux_transformation import (
AzureFoundryFluxImageGenerationConfig,
)
@@ -71,16 +74,13 @@ class AzureFoundryFlux2ImageEditConfig(OpenAIImageEditConfig):
"""
Validate Azure AI Foundry environment and set up authentication
"""
- api_key = AzureFoundryModelInfo.get_api_key(api_key)
-
- if not api_key:
- raise ValueError(
- f"Azure AI API key is required for model {model}. Set AZURE_AI_API_KEY environment variable or pass api_key parameter."
- )
-
headers.update(
{
- "Api-Key": api_key,
+ **get_azure_ai_auth_headers(
+ api_key=AzureFoundryModelInfo.get_api_key(api_key),
+ litellm_params=litellm_params,
+ api_key_header="Api-Key",
+ ),
"Content-Type": "application/json",
}
)
diff --git a/litellm/llms/azure_ai/image_edit/mai_transformation.py b/litellm/llms/azure_ai/image_edit/mai_transformation.py
index aa1092b0a53..fdac9912193 100644
--- a/litellm/llms/azure_ai/image_edit/mai_transformation.py
+++ b/litellm/llms/azure_ai/image_edit/mai_transformation.py
@@ -3,7 +3,10 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, cast
import httpx
from httpx._types import RequestFiles
-from litellm.llms.azure_ai.common_utils import AzureFoundryModelInfo
+from litellm.llms.azure_ai.common_utils import (
+ AzureFoundryModelInfo,
+ get_azure_ai_auth_headers,
+)
from litellm.llms.azure_ai.image_generation.mai_transformation import (
AzureFoundryMAIImageGenerationConfig,
)
@@ -91,15 +94,13 @@ class AzureFoundryMAIImageEditConfig(OpenAIImageEditConfig):
litellm_params: Optional[dict] = None,
api_base: Optional[str] = None,
) -> dict:
- api_key = AzureFoundryModelInfo.get_api_key(api_key)
-
- if not api_key:
- raise ValueError(
- f"Azure AI API key is required for model {model}. "
- "Set AZURE_AI_API_KEY environment variable or pass api_key parameter."
+ headers.update(
+ get_azure_ai_auth_headers(
+ api_key=AzureFoundryModelInfo.get_api_key(api_key),
+ litellm_params=litellm_params,
+ api_key_header="api-key",
)
-
- headers.update({"api-key": api_key})
+ )
return headers
def get_complete_url(
diff --git a/litellm/llms/azure_ai/image_edit/transformation.py b/litellm/llms/azure_ai/image_edit/transformation.py
index 5393a0ba55f..22b0b169faf 100644
--- a/litellm/llms/azure_ai/image_edit/transformation.py
+++ b/litellm/llms/azure_ai/image_edit/transformation.py
@@ -3,7 +3,10 @@ from typing import Optional
import httpx
import litellm
-from litellm.llms.azure_ai.common_utils import AzureFoundryModelInfo
+from litellm.llms.azure_ai.common_utils import (
+ AzureFoundryModelInfo,
+ get_azure_ai_auth_headers,
+)
from litellm.llms.openai.image_edit.transformation import OpenAIImageEditConfig
from litellm.secret_managers.main import get_secret_str
from litellm.utils import _add_path_to_api_base
@@ -30,19 +33,14 @@ class AzureFoundryFluxImageEditConfig(OpenAIImageEditConfig):
) -> dict:
"""
Validate Azure AI Foundry environment and set up authentication
- Uses Api-Key header format
+ Uses the Api-Key header format, or an Entra ID / OAuth bearer token when no key is set
"""
- api_key = AzureFoundryModelInfo.get_api_key(api_key)
-
- if not api_key:
- raise ValueError(
- f"Azure AI API key is required for model {model}. Set AZURE_AI_API_KEY environment variable or pass api_key parameter."
- )
-
headers.update(
- {
- "Api-Key": api_key, # Azure AI Foundry uses Api-Key header format
- }
+ get_azure_ai_auth_headers(
+ api_key=AzureFoundryModelInfo.get_api_key(api_key),
+ litellm_params=litellm_params,
+ api_key_header="Api-Key",
+ )
)
return headers
diff --git a/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py b/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py
index 7d915892a28..4db4472dfc2 100644
--- a/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py
+++ b/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py
@@ -25,6 +25,7 @@ from litellm.constants import (
AZURE_OPERATION_POLLING_TIMEOUT,
)
from litellm.litellm_core_utils.url_utils import encode_url_path_segment
+from litellm.llms.azure_ai.common_utils import get_azure_ai_auth_headers
from litellm.llms.base_llm.ocr.transformation import (
BaseOCRConfig,
DocumentType,
@@ -215,17 +216,13 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig):
"""
Validate environment and return headers for Azure Document Intelligence.
- Authentication uses Ocp-Apim-Subscription-Key header.
+ Authentication uses the Ocp-Apim-Subscription-Key header, or an Entra ID / OAuth bearer
+ token when no subscription key is set.
"""
# Get API key from environment if not provided
if api_key is None:
api_key = get_secret_str(AZURE_DOCUMENT_INTELLIGENCE_API_KEY_ENV_VAR)
- if api_key is None:
- raise ValueError(
- "Missing Azure Document Intelligence API Key - Set AZURE_DOCUMENT_INTELLIGENCE_API_KEY environment variable or pass api_key parameter"
- )
-
# Validate API base/endpoint is provided
if api_base is None:
api_base = get_secret_str("AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT")
@@ -236,7 +233,12 @@ class AzureDocumentIntelligenceOCRConfig(BaseOCRConfig):
)
headers = {
- "Ocp-Apim-Subscription-Key": api_key,
+ **get_azure_ai_auth_headers(
+ api_key=api_key,
+ litellm_params=litellm_params,
+ api_key_header="Ocp-Apim-Subscription-Key",
+ api_key_env_var=AZURE_DOCUMENT_INTELLIGENCE_API_KEY_ENV_VAR,
+ ),
"Content-Type": "application/json",
**headers,
}
diff --git a/litellm/llms/azure_ai/ocr/transformation.py b/litellm/llms/azure_ai/ocr/transformation.py
index a57e3e869cf..abc23008f6a 100644
--- a/litellm/llms/azure_ai/ocr/transformation.py
+++ b/litellm/llms/azure_ai/ocr/transformation.py
@@ -9,6 +9,7 @@ from litellm.litellm_core_utils.prompt_templates.image_handling import (
async_convert_url_to_base64,
convert_url_to_base64,
)
+from litellm.llms.azure_ai.common_utils import get_azure_ai_auth_headers
from litellm.llms.base_llm.ocr.transformation import DocumentType, OCRRequestData
from litellm.llms.mistral.ocr.transformation import MistralOCRConfig
from litellm.secret_managers.main import get_secret_str
@@ -47,17 +48,12 @@ class AzureAIOCRConfig(MistralOCRConfig):
"""
Validate environment and return headers for Azure AI OCR.
- Azure AI uses Bearer token authentication with AZURE_AI_API_KEY.
+ Authenticates with AZURE_AI_API_KEY, or with an Entra ID / OAuth token when no key is set.
"""
# Get API key from environment if not provided
if api_key is None:
api_key = get_secret_str(AZURE_AI_OCR_API_KEY_ENV_VAR)
- if api_key is None:
- raise ValueError(
- "Missing Azure AI API Key - A call is being made to Azure AI but no key is set either in the environment variables or via params"
- )
-
# Validate API base is provided
if api_base is None:
api_base = get_secret_str("AZURE_AI_API_BASE")
@@ -68,7 +64,7 @@ class AzureAIOCRConfig(MistralOCRConfig):
)
headers = {
- "Authorization": f"Bearer {api_key}",
+ **get_azure_ai_auth_headers(api_key=api_key, litellm_params=litellm_params),
"Content-Type": "application/json",
**headers,
}
diff --git a/litellm/llms/azure_ai/rerank/transformation.py b/litellm/llms/azure_ai/rerank/transformation.py
index 928f53bd485..24cdc67a23b 100644
--- a/litellm/llms/azure_ai/rerank/transformation.py
+++ b/litellm/llms/azure_ai/rerank/transformation.py
@@ -2,12 +2,14 @@
Translate between Cohere's `/rerank` format and Azure AI's `/rerank` format.
"""
+from collections.abc import Mapping
from typing import Optional
import httpx
import litellm
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+from litellm.llms.azure_ai.common_utils import get_azure_ai_auth_headers
from litellm.llms.cohere.rerank.transformation import CohereRerankConfig
from litellm.secret_managers.main import get_secret_str
from litellm.types.utils import RerankResponse
@@ -64,15 +66,13 @@ class AzureAIRerankConfig(CohereRerankConfig):
model: str,
api_key: Optional[str] = None,
optional_params: Optional[dict] = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> dict:
if api_key is None:
api_key = get_secret_str("AZURE_AI_API_KEY") or litellm.azure_key
- if api_key is None:
- raise ValueError("Azure AI API key is required. Please set 'AZURE_AI_API_KEY' or 'litellm.azure_key'")
-
default_headers = {
- "Authorization": f"Bearer {api_key}",
+ **get_azure_ai_auth_headers(api_key=api_key, litellm_params=litellm_params),
"accept": "application/json",
"content-type": "application/json",
}
diff --git a/litellm/llms/base_llm/rerank/transformation.py b/litellm/llms/base_llm/rerank/transformation.py
index eac44ba85c5..e9f210fb31c 100644
--- a/litellm/llms/base_llm/rerank/transformation.py
+++ b/litellm/llms/base_llm/rerank/transformation.py
@@ -1,4 +1,5 @@
from abc import ABC, abstractmethod
+from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union
import httpx
@@ -24,6 +25,7 @@ class BaseRerankConfig(ABC):
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> dict:
pass
diff --git a/litellm/llms/cohere/rerank/transformation.py b/litellm/llms/cohere/rerank/transformation.py
index e494e89fbf2..86d9a3d224d 100644
--- a/litellm/llms/cohere/rerank/transformation.py
+++ b/litellm/llms/cohere/rerank/transformation.py
@@ -1,3 +1,4 @@
+from collections.abc import Mapping
from typing import Any, Dict, List, Union
import httpx
@@ -81,6 +82,7 @@ class CohereRerankConfig(BaseRerankConfig):
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> dict:
if api_key is None:
api_key = get_secret_str("COHERE_API_KEY") or get_secret_str("CO_API_KEY") or litellm.cohere_key
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index ec1301e5923..e41fbea94d6 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -1063,6 +1063,7 @@ class BaseLLMHTTPHandler:
headers=headers or {},
model=model,
optional_params=optional_rerank_params,
+ litellm_params=litellm_params,
)
api_base = provider_config.get_complete_url(
diff --git a/litellm/llms/dashscope/rerank/transformation.py b/litellm/llms/dashscope/rerank/transformation.py
index 365e15fdd7a..b8c369b892c 100644
--- a/litellm/llms/dashscope/rerank/transformation.py
+++ b/litellm/llms/dashscope/rerank/transformation.py
@@ -22,6 +22,7 @@ as supported only for gte-rerank-v2 / qwen3-vl-rerank.
Docs - https://help.aliyun.com/zh/model-studio/text-rerank-api
"""
+from collections.abc import Mapping
from typing import Any, Dict, List, Union
import httpx
@@ -85,6 +86,7 @@ class DashScopeRerankConfig(BaseRerankConfig):
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> dict:
if api_key is None:
api_key = get_secret_str("DASHSCOPE_API_KEY")
diff --git a/litellm/llms/deepinfra/rerank/transformation.py b/litellm/llms/deepinfra/rerank/transformation.py
index 82069e4e195..87a6ecc7120 100644
--- a/litellm/llms/deepinfra/rerank/transformation.py
+++ b/litellm/llms/deepinfra/rerank/transformation.py
@@ -2,6 +2,7 @@
Translate between Cohere's `/rerank` format and Deepinfra's `/rerank` format.
"""
+from collections.abc import Mapping
from typing import Any, Dict, List, Union
import httpx
@@ -67,6 +68,7 @@ class DeepinfraRerankConfig(BaseRerankConfig):
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> dict:
if api_key is None:
api_key = get_secret_str("DEEPINFRA_API_KEY")
diff --git a/litellm/llms/fireworks_ai/rerank/transformation.py b/litellm/llms/fireworks_ai/rerank/transformation.py
index 393a6c5a8e5..e727f5c1d2b 100644
--- a/litellm/llms/fireworks_ai/rerank/transformation.py
+++ b/litellm/llms/fireworks_ai/rerank/transformation.py
@@ -4,6 +4,7 @@ Fireworks AI Rerank API transformation
Reference: https://docs.fireworks.ai/inference-api-reference/rerank
"""
+from collections.abc import Mapping
from typing import Any, Dict, List, Union
import httpx
@@ -104,6 +105,7 @@ class FireworksAIRerankConfig(FireworksAIMixin, BaseRerankConfig):
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> dict:
api_key = self._get_api_key(api_key)
if api_key is None:
diff --git a/litellm/llms/hosted_vllm/rerank/transformation.py b/litellm/llms/hosted_vllm/rerank/transformation.py
index 77504eba04a..cd35cc72492 100644
--- a/litellm/llms/hosted_vllm/rerank/transformation.py
+++ b/litellm/llms/hosted_vllm/rerank/transformation.py
@@ -2,6 +2,7 @@
Transformation logic for Hosted VLLM rerank
"""
+from collections.abc import Mapping
from typing import Any, Dict, List, Union
import httpx
@@ -107,6 +108,7 @@ class HostedVLLMRerankConfig(BaseRerankConfig):
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> dict:
if api_key is None:
api_key = get_secret_str("HOSTED_VLLM_API_KEY") or "fake-api-key"
diff --git a/litellm/llms/huggingface/rerank/transformation.py b/litellm/llms/huggingface/rerank/transformation.py
index cdad77a9815..245551cf4f2 100644
--- a/litellm/llms/huggingface/rerank/transformation.py
+++ b/litellm/llms/huggingface/rerank/transformation.py
@@ -1,4 +1,5 @@
import os
+from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union
import httpx
@@ -125,6 +126,7 @@ class HuggingFaceRerankConfig(BaseRerankConfig):
api_key: str | None = None,
optional_params: dict | None = None,
api_base: str | None = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> dict:
# Get API credentials
api_key, api_base = self.get_api_credentials(api_key=api_key, api_base=api_base)
diff --git a/litellm/llms/infinity/rerank/transformation.py b/litellm/llms/infinity/rerank/transformation.py
index 94746da4609..7451b06c01a 100644
--- a/litellm/llms/infinity/rerank/transformation.py
+++ b/litellm/llms/infinity/rerank/transformation.py
@@ -4,12 +4,13 @@ Transformation logic from Cohere's /v1/rerank format to Infinity's `/v1/rerank`
Why separate file? Make it easy to see how transformation works
"""
-from litellm._uuid import uuid
+from collections.abc import Mapping
from typing import List, Optional
import httpx
import litellm
+from litellm._uuid import uuid
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.cohere.rerank.transformation import CohereRerankConfig
from litellm.secret_managers.main import get_secret_str
@@ -46,6 +47,7 @@ class InfinityRerankConfig(CohereRerankConfig):
model: str,
api_key: Optional[str] = None,
optional_params: Optional[dict] = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> dict:
if api_key is None:
api_key = get_secret_str("INFINITY_API_KEY") or get_secret_str("INFINITY_API_KEY") or litellm.infinity_key
diff --git a/litellm/llms/jina_ai/rerank/transformation.py b/litellm/llms/jina_ai/rerank/transformation.py
index 7f4c0709bdd..903e629803b 100644
--- a/litellm/llms/jina_ai/rerank/transformation.py
+++ b/litellm/llms/jina_ai/rerank/transformation.py
@@ -6,6 +6,7 @@ Why separate file? Make it easy to see how transformation works
Docs - https://jina.ai/reranker
"""
+from collections.abc import Mapping
from typing import Any, Dict, List, Tuple, Union
from httpx import URL, Response
@@ -139,6 +140,7 @@ class JinaAIRerankConfig(BaseRerankConfig):
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> Dict:
if api_key is None:
raise ValueError("api_key is required. Set via `api_key` parameter or `JINA_API_KEY` environment variable.")
diff --git a/litellm/llms/nvidia_nim/rerank/transformation.py b/litellm/llms/nvidia_nim/rerank/transformation.py
index 2d72d52f991..07b792468c9 100644
--- a/litellm/llms/nvidia_nim/rerank/transformation.py
+++ b/litellm/llms/nvidia_nim/rerank/transformation.py
@@ -1,3 +1,4 @@
+from collections.abc import Mapping
from typing import Any, Dict, List, Literal, Union
import httpx
@@ -148,6 +149,7 @@ class NvidiaNimRerankConfig(BaseRerankConfig):
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> dict:
"""
Validate that the Nvidia NIM API key is present.
diff --git a/litellm/llms/vertex_ai/rerank/transformation.py b/litellm/llms/vertex_ai/rerank/transformation.py
index b9680af20cc..055a02aa40d 100644
--- a/litellm/llms/vertex_ai/rerank/transformation.py
+++ b/litellm/llms/vertex_ai/rerank/transformation.py
@@ -4,6 +4,7 @@ Translates from Cohere's `/v1/rerank` input format to Vertex AI Discovery Engine
Why separate file? Make it easy to see how transformation works
"""
+from collections.abc import Mapping
from typing import Any, Dict, List, Union
import httpx
@@ -74,14 +75,15 @@ class VertexAIRerankConfig(BaseRerankConfig, VertexBase):
model: str,
api_key: str | None = None,
optional_params: Dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> dict:
"""
Validate and set up authentication for Vertex AI Discovery Engine API
"""
# Get credentials and project info from optional_params (which contains vertex_credentials, etc.)
- litellm_params = optional_params.copy() if optional_params else {}
- vertex_credentials = self.safe_get_vertex_ai_credentials(litellm_params)
- vertex_project = self.safe_get_vertex_ai_project(litellm_params)
+ vertex_params = optional_params.copy() if optional_params else {}
+ vertex_credentials = self.safe_get_vertex_ai_credentials(vertex_params)
+ vertex_project = self.safe_get_vertex_ai_project(vertex_params)
# Get access token using the base class method
access_token, project_id = self._ensure_access_token(
diff --git a/litellm/llms/voyage/rerank/transformation.py b/litellm/llms/voyage/rerank/transformation.py
index e426e39962b..df9f32dd96d 100644
--- a/litellm/llms/voyage/rerank/transformation.py
+++ b/litellm/llms/voyage/rerank/transformation.py
@@ -4,6 +4,7 @@ Transformation logic for Voyage AI's /v1/rerank endpoint.
Docs - https://docs.voyageai.com/docs/reranker
"""
+from collections.abc import Mapping
from typing import Any, Dict, List, Tuple, Union
import httpx
@@ -137,6 +138,7 @@ class VoyageRerankConfig(BaseRerankConfig):
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> Dict:
if api_key is None:
api_key = get_secret_str("VOYAGE_API_KEY") or get_secret_str("VOYAGE_AI_API_KEY")
diff --git a/litellm/llms/watsonx/rerank/transformation.py b/litellm/llms/watsonx/rerank/transformation.py
index 25b593f1c0a..549ccca4748 100644
--- a/litellm/llms/watsonx/rerank/transformation.py
+++ b/litellm/llms/watsonx/rerank/transformation.py
@@ -5,6 +5,7 @@ Docs - https://cloud.ibm.com/apidocs/watsonx-ai#text-rerank
"""
import uuid
+from collections.abc import Mapping
from typing import Any, Dict, List, Union, cast
import httpx
@@ -60,6 +61,7 @@ class IBMWatsonXRerankConfig(IBMWatsonXMixin, BaseRerankConfig):
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
) -> Dict:
optional_params = optional_params or {}
diff --git a/litellm/main.py b/litellm/main.py
index acdec7385da..b167a257d18 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -6739,6 +6739,8 @@ def embedding(
aembedding=aembedding,
)
elif custom_llm_provider == "azure_ai":
+ from litellm.llms.azure_ai.common_utils import get_azure_ai_entra_token
+
api_base = (
api_base # for deepinfra/perplexity/anyscale/groq/friendliai we check in get_llm_provider and pass in the api base from there
or litellm.api_base
@@ -6748,8 +6750,8 @@ def embedding(
api_key = (
api_key
or litellm.api_key # for deepinfra/perplexity/anyscale/friendliai we check in get_llm_provider and pass in the api key from there
- or litellm.openai_key
or get_secret_str("AZURE_AI_API_KEY")
+ or get_azure_ai_entra_token(litellm_params=litellm_params_dict)
)
## EMBEDDING CALL
diff --git a/tests/test_litellm/llms/azure/test_azure_common_utils.py b/tests/test_litellm/llms/azure/test_azure_common_utils.py
index a3280b90fe3..450920f1f44 100644
--- a/tests/test_litellm/llms/azure/test_azure_common_utils.py
+++ b/tests/test_litellm/llms/azure/test_azure_common_utils.py
@@ -11,7 +11,12 @@ sys.path.insert(
0, os.path.abspath("../../../..")
) # Adds the parent directory to the system path
import litellm
-from litellm.llms.azure.common_utils import BaseAzureLLM, get_azure_ad_token
+from litellm.llms.azure.common_utils import (
+ BaseAzureLLM,
+ _cached_entra_id_token_provider,
+ get_azure_ad_token,
+ get_azure_ad_token_from_entra_id,
+)
from litellm.secret_managers.get_azure_ad_token_provider import (
get_azure_ad_token_provider,
)
@@ -2034,3 +2039,59 @@ def test_azure_traditional_api_uses_azure_openai_client():
assert isinstance(
async_client, AsyncAzureOpenAI
), f"Expected AsyncAzureOpenAI client for api_version={api_version}"
+
+
+class TestEntraIdTokenProviderCache:
+ def setup_method(self):
+ _cached_entra_id_token_provider.cache_clear()
+
+ def teardown_method(self):
+ _cached_entra_id_token_provider.cache_clear()
+
+ def test_reuses_credential_for_the_same_service_principal(self):
+ with (
+ patch("azure.identity.ClientSecretCredential") as mock_credential,
+ patch("azure.identity.get_bearer_token_provider", side_effect=lambda credential, scope: lambda: "token"),
+ ):
+ first = get_azure_ad_token_from_entra_id(
+ tenant_id="tenant",
+ client_id="client",
+ client_secret="secret",
+ scope="https://cognitiveservices.azure.com/.default",
+ )
+ second = get_azure_ad_token_from_entra_id(
+ tenant_id="tenant",
+ client_id="client",
+ client_secret="secret",
+ scope="https://cognitiveservices.azure.com/.default",
+ )
+
+ assert first is second
+ assert mock_credential.call_count == 1
+
+ @pytest.mark.parametrize(
+ "second_call_kwargs",
+ [
+ {"tenant_id": "other-tenant"},
+ {"client_id": "other-client"},
+ {"client_secret": "other-secret"},
+ {"scope": "https://ai.azure.com/.default"},
+ ],
+ )
+ def test_does_not_share_a_provider_across_credentials_or_scopes(self, second_call_kwargs):
+ base_kwargs = {
+ "tenant_id": "tenant",
+ "client_id": "client",
+ "client_secret": "secret",
+ "scope": "https://cognitiveservices.azure.com/.default",
+ }
+
+ with (
+ patch("azure.identity.ClientSecretCredential") as mock_credential,
+ patch("azure.identity.get_bearer_token_provider", side_effect=lambda credential, scope: lambda: "token"),
+ ):
+ first = get_azure_ad_token_from_entra_id(**base_kwargs)
+ second = get_azure_ad_token_from_entra_id(**{**base_kwargs, **second_call_kwargs})
+
+ assert first is not second
+ assert mock_credential.call_count == 2
diff --git a/tests/test_litellm/llms/azure_ai/image_edit/test_azure_ai_image_edit_transformation.py b/tests/test_litellm/llms/azure_ai/image_edit/test_azure_ai_image_edit_transformation.py
index da1041f3d60..9c9401fa8e9 100644
--- a/tests/test_litellm/llms/azure_ai/image_edit/test_azure_ai_image_edit_transformation.py
+++ b/tests/test_litellm/llms/azure_ai/image_edit/test_azure_ai_image_edit_transformation.py
@@ -5,6 +5,10 @@ sys.path.insert(
0, os.path.abspath("../../../../..")
) # Adds the parent directory to the system path
+import litellm
+from litellm.llms.azure_ai.image_edit.flux2_transformation import (
+ AzureFoundryFlux2ImageEditConfig,
+)
from litellm.llms.azure_ai.image_edit.transformation import (
AzureFoundryFluxImageEditConfig,
)
@@ -32,3 +36,32 @@ def test_azure_ai_url_generation():
)
expected_url = f"{api_base}/openai/deployments/FLUX.1-Kontext-pro/images/edits?api-version=2025-04-01-preview"
assert complete_url == expected_url
+
+
+def test_azure_ai_validate_environment_with_entra_token(monkeypatch):
+ monkeypatch.delenv("AZURE_AI_API_KEY", raising=False)
+ monkeypatch.setattr(litellm, "api_key", None)
+ config = AzureFoundryFluxImageEditConfig()
+
+ headers = config.validate_environment(
+ {},
+ "FLUX.1-Kontext-pro",
+ litellm_params={"azure_ad_token": "entra-token"},
+ )
+
+ assert headers == {"Authorization": "Bearer entra-token"}
+
+
+def test_flux2_validate_environment_with_entra_token(monkeypatch):
+ monkeypatch.delenv("AZURE_AI_API_KEY", raising=False)
+ monkeypatch.setattr(litellm, "api_key", None)
+ config = AzureFoundryFlux2ImageEditConfig()
+
+ headers = config.validate_environment(
+ {},
+ "flux.2-pro",
+ litellm_params={"azure_ad_token": "entra-token"},
+ )
+
+ assert headers["Authorization"] == "Bearer entra-token"
+ assert headers["Content-Type"] == "application/json"
diff --git a/tests/test_litellm/llms/azure_ai/image_edit/test_mai_image_edit_transformation.py b/tests/test_litellm/llms/azure_ai/image_edit/test_mai_image_edit_transformation.py
index d5256be02d7..c4e39a26aeb 100644
--- a/tests/test_litellm/llms/azure_ai/image_edit/test_mai_image_edit_transformation.py
+++ b/tests/test_litellm/llms/azure_ai/image_edit/test_mai_image_edit_transformation.py
@@ -8,6 +8,7 @@ import pytest
sys.path.insert(0, os.path.abspath("../../../../../.."))
+import litellm
from litellm.llms.azure_ai.image_edit import (
AzureFoundryMAIImageEditConfig,
get_azure_ai_image_edit_config,
@@ -169,3 +170,16 @@ class TestAzureMAIImageEdit:
assert image_response.data[0].b64_json == "abc123"
assert image_response.usage.output_tokens == 1024
assert image_response.usage.total_tokens == 1024
+
+
+def test_mai_validate_environment_with_entra_token(monkeypatch):
+ monkeypatch.delenv("AZURE_AI_API_KEY", raising=False)
+ monkeypatch.setattr(litellm, "api_key", None)
+
+ headers = AzureFoundryMAIImageEditConfig().validate_environment(
+ headers={},
+ model="MAI-Image-2.5",
+ litellm_params={"azure_ad_token": "entra-token"},
+ )
+
+ assert headers == {"Authorization": "Bearer entra-token"}
diff --git a/tests/test_litellm/llms/azure_ai/rerank/test_azure_ai_rerank_transformation.py b/tests/test_litellm/llms/azure_ai/rerank/test_azure_ai_rerank_transformation.py
index ffabce6e00c..150f5794ab1 100644
--- a/tests/test_litellm/llms/azure_ai/rerank/test_azure_ai_rerank_transformation.py
+++ b/tests/test_litellm/llms/azure_ai/rerank/test_azure_ai_rerank_transformation.py
@@ -7,6 +7,7 @@ sys.path.insert(
0, os.path.abspath("../../../../..")
) # Adds the parent directory to the system path
+import litellm
from litellm.llms.azure_ai.rerank.transformation import AzureAIRerankConfig
@@ -97,3 +98,26 @@ class TestAzureAIRerankConfigGetCompleteUrl:
model=self.model,
)
assert url == "https://my-resource.services.ai.azure.com/v1/rerank?r=1"
+
+
+class TestAzureAIRerankConfigValidateEnvironment:
+ def test_uses_api_key_when_set(self):
+ headers = AzureAIRerankConfig().validate_environment(
+ headers={},
+ model="azure_ai/cohere-rerank-v3-english",
+ api_key="my-key",
+ )
+
+ assert headers["Authorization"] == "Bearer my-key"
+
+ def test_falls_back_to_entra_token(self, monkeypatch):
+ monkeypatch.delenv("AZURE_AI_API_KEY", raising=False)
+ monkeypatch.setattr(litellm, "azure_key", None)
+
+ headers = AzureAIRerankConfig().validate_environment(
+ headers={},
+ model="azure_ai/cohere-rerank-v3-english",
+ litellm_params={"azure_ad_token": "entra-token"},
+ )
+
+ assert headers["Authorization"] == "Bearer entra-token"
diff --git a/tests/test_litellm/llms/azure_ai/test_azure_ai_entra_auth.py b/tests/test_litellm/llms/azure_ai/test_azure_ai_entra_auth.py
new file mode 100644
index 00000000000..8ac37feee4b
--- /dev/null
+++ b/tests/test_litellm/llms/azure_ai/test_azure_ai_entra_auth.py
@@ -0,0 +1,153 @@
+"""
+Entra ID / OAuth auth for Azure AI Foundry routes.
+
+Every azure_ai route must authenticate with an Entra ID token when no API key is configured,
+instead of requiring an API key.
+"""
+
+from unittest.mock import patch
+
+import pytest
+
+import litellm
+from litellm.llms.azure_ai.common_utils import get_azure_ai_auth_headers
+from litellm.llms.azure_ai.ocr.transformation import AzureAIOCRConfig
+
+ENTRA_PARAMS = {"azure_ad_token": "entra-token"}
+
+
[email protected](autouse=True)
+def clear_azure_env(monkeypatch):
+ for env_var in (
+ "AZURE_AI_API_KEY",
+ "AZURE_API_KEY",
+ "AZURE_AD_TOKEN",
+ "AZURE_TENANT_ID",
+ "AZURE_CLIENT_ID",
+ "AZURE_CLIENT_SECRET",
+ "AZURE_SCOPE",
+ "OPENAI_API_KEY",
+ "AZURE_DOCUMENT_INTELLIGENCE_API_KEY",
+ ):
+ monkeypatch.delenv(env_var, raising=False)
+ monkeypatch.setattr(litellm, "api_key", None)
+ monkeypatch.setattr(litellm, "openai_key", None)
+
+
+def test_api_key_wins_over_entra_credentials():
+ headers = get_azure_ai_auth_headers(api_key="my-key", litellm_params=ENTRA_PARAMS, api_key_header="Api-Key")
+
+ assert headers == {"Api-Key": "my-key"}
+
+
+def test_entra_token_used_when_no_api_key():
+ headers = get_azure_ai_auth_headers(api_key=None, litellm_params=ENTRA_PARAMS, api_key_header="Api-Key")
+
+ assert headers == {"Authorization": "Bearer entra-token"}
+
+
+def test_service_principal_token_is_requested_with_the_configured_scope():
+ with patch("litellm.llms.azure.common_utils.get_azure_ad_token_from_entra_id") as mock_entra_id:
+ mock_entra_id.return_value = lambda: "sp-token"
+
+ headers = get_azure_ai_auth_headers(
+ api_key=None,
+ litellm_params={
+ "tenant_id": "tenant",
+ "client_id": "client",
+ "client_secret": "secret",
+ "azure_scope": "https://ai.azure.com/.default",
+ },
+ )
+
+ mock_entra_id.assert_called_once_with(
+ tenant_id="tenant",
+ client_id="client",
+ client_secret="secret",
+ scope="https://ai.azure.com/.default",
+ )
+ assert headers == {"Authorization": "Bearer sp-token"}
+
+
+def test_error_mentions_both_credential_types_when_nothing_is_configured():
+ with pytest.raises(ValueError) as exc_info:
+ get_azure_ai_auth_headers(api_key=None, litellm_params={})
+
+ message = str(exc_info.value)
+ assert "AZURE_AI_API_KEY" in message
+ assert "client_secret" in message
+
+
+def test_ocr_authenticates_with_entra_token():
+ headers = AzureAIOCRConfig().validate_environment(
+ headers={},
+ model="azure_ai/mistral-ocr",
+ api_base="https://my-resource.services.ai.azure.com",
+ litellm_params=ENTRA_PARAMS,
+ )
+
+ assert headers["Authorization"] == "Bearer entra-token"
+
+
+def test_embedding_falls_back_to_entra_token_instead_of_openai_key(monkeypatch):
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-openai-key")
+
+ with patch.object(litellm.main.azure_ai_embedding, "embedding") as mock_embedding:
+ mock_embedding.return_value = litellm.EmbeddingResponse()
+
+ litellm.embedding(
+ model="azure_ai/cohere-embed-v3-english",
+ input=["hello"],
+ api_base="https://my-resource.services.ai.azure.com",
+ azure_ad_token="entra-token",
+ )
+
+ assert mock_embedding.call_args.kwargs["api_key"] == "entra-token"
+
+
+def test_image_generation_authenticates_with_entra_token():
+ with patch.object(litellm.images.main.azure_chat_completions, "image_generation") as mock_image_generation:
+ mock_image_generation.return_value = litellm.ImageResponse()
+
+ litellm.image_generation(
+ model="azure_ai/FLUX-1.1-pro",
+ prompt="a red circle",
+ api_base="https://my-resource.services.ai.azure.com",
+ azure_ad_token="entra-token",
+ )
+
+ headers = mock_image_generation.call_args.kwargs["headers"]
+ assert headers["Authorization"] == "Bearer entra-token"
+ assert "api-key" not in headers
+
+
+def test_image_generation_keeps_caller_supplied_authorization_header():
+ with patch.object(litellm.images.main.azure_chat_completions, "image_generation") as mock_image_generation:
+ mock_image_generation.return_value = litellm.ImageResponse()
+
+ litellm.image_generation(
+ model="azure_ai/FLUX-1.1-pro",
+ prompt="a red circle",
+ api_base="https://my-resource.services.ai.azure.com",
+ headers={"Authorization": "Bearer caller-token"},
+ )
+
+ headers = mock_image_generation.call_args.kwargs["headers"]
+ assert headers["Authorization"] == "Bearer caller-token"
+ assert "api-key" not in headers
+
+
+def test_image_generation_still_uses_api_key_header():
+ with patch.object(litellm.images.main.azure_chat_completions, "image_generation") as mock_image_generation:
+ mock_image_generation.return_value = litellm.ImageResponse()
+
+ litellm.image_generation(
+ model="azure_ai/FLUX-1.1-pro",
+ prompt="a red circle",
+ api_base="https://my-resource.services.ai.azure.com",
+ api_key="my-key",
+ )
+
+ headers = mock_image_generation.call_args.kwargs["headers"]
+ assert headers["api-key"] == "my-key"
+ assert "Authorization" not in headers
diff --git a/tests/test_litellm/llms/azure_ai/test_azure_document_intelligence_ocr_transformation.py b/tests/test_litellm/llms/azure_ai/test_azure_document_intelligence_ocr_transformation.py
index 39d6f1dc355..b8e11a0bfcb 100644
--- a/tests/test_litellm/llms/azure_ai/test_azure_document_intelligence_ocr_transformation.py
+++ b/tests/test_litellm/llms/azure_ai/test_azure_document_intelligence_ocr_transformation.py
@@ -248,3 +248,30 @@ def test_get_complete_url_combines_pages_and_features():
assert "&pages=1,2,3" in url
assert "&features=keyValuePairs,languages" in url
+
+
+def test_validate_environment_uses_subscription_key(monkeypatch):
+ monkeypatch.delenv("AZURE_DOCUMENT_INTELLIGENCE_API_KEY", raising=False)
+
+ headers = AzureDocumentIntelligenceOCRConfig().validate_environment(
+ headers={},
+ model="prebuilt-layout",
+ api_key="my-key",
+ api_base="https://example.cognitiveservices.azure.com",
+ )
+
+ assert headers["Ocp-Apim-Subscription-Key"] == "my-key"
+
+
+def test_validate_environment_falls_back_to_entra_token(monkeypatch):
+ monkeypatch.delenv("AZURE_DOCUMENT_INTELLIGENCE_API_KEY", raising=False)
+
+ headers = AzureDocumentIntelligenceOCRConfig().validate_environment(
+ headers={},
+ model="prebuilt-layout",
+ api_base="https://example.cognitiveservices.azure.com",
+ litellm_params={"azure_ad_token": "entra-token"},
+ )
+
+ assert headers["Authorization"] == "Bearer entra-token"
+ assert "Ocp-Apim-Subscription-Key" not in headers