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 origin/litellm_internal_staging into litellm_azure_ai_entra_auth

mateo-berri37f8b9600ad9
diff --cc litellm/images/main.py
index 3bee6000d3f,ae4818b1967..e4398bb32f5
--- a/litellm/images/main.py
+++ b/litellm/images/main.py
@@@ -440,22 -429,17 +432,22 @@@ def image_generation
if extra_headers is not None:
optional_params["extra_headers"] = extra_headers
- default_headers = {
+ caller_header_names = frozenset(name.lower() for name in headers)
+ caller_set_auth = "api-key" in caller_header_names or "authorization" in caller_header_names
+ 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 = {
++ request_headers: Final = {
"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,
@@@ -471,7 -455,7 +463,7 @@@
api_version=api_version,
aimg_generation=aimg_generation,
client=client,
-- headers=headers,
++ headers=request_headers,
litellm_params=litellm_params_dict,
)
elif (
diff --cc litellm/llms/azure/common_utils.py
index 85100e595e6,b77ba2f9460..2c34851d275
--- a/litellm/llms/azure/common_utils.py
+++ b/litellm/llms/azure/common_utils.py
@@@ -2,8 -2,8 +2,9 @@@ import asynci
import hashlib
import json
import os
+ from collections.abc import Callable, Mapping
+from functools import lru_cache
- from typing import Any, Callable, Dict, Literal, NamedTuple, Optional, Union, cast
+ from typing import Any, Final, Literal, NamedTuple, cast
import httpx
from openai import AsyncAzureOpenAI, AsyncOpenAI, AzureOpenAI, OpenAI
@@@ -119,13 -120,9 +137,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: Final = ClientSecretCredential(_tenant_id, _client_id, _client_secret)
- token_provider = _cached_entra_id_token_provider(
- token_provider: Final = get_bearer_token_provider(credential, scope)
++ token_provider: Final = _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 --cc litellm/llms/azure_ai/common_utils.py
index 5dd5f5c78cc,d25a8fd6561..d09055d7671
--- a/litellm/llms/azure_ai/common_utils.py
+++ b/litellm/llms/azure_ai/common_utils.py
@@@ -1,54 -1,9 +1,54 @@@
+from collections.abc import Mapping
- from typing import List, Literal, Optional
+ from typing import Final, Literal
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]:
++) -> 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`)"
+ )
class AzureFoundryModelInfo(BaseLLMModelInfo):
@@@ -87,11 -42,11 +87,11 @@@
return api_base or litellm.api_base or get_secret_str("AZURE_AI_API_BASE")
@staticmethod
- def get_api_key(api_key: Optional[str] = None) -> Optional[str]:
+ def get_api_key(api_key: str | None = None) -> str | None:
- 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]:
+ def api_version(self, api_version: str | None = None) -> str | None:
api_version = api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION")
return api_version
diff --cc litellm/llms/azure_ai/image_edit/mai_transformation.py
index fdac9912193,73bd9957b8f..e639c20292b
--- a/litellm/llms/azure_ai/image_edit/mai_transformation.py
+++ b/litellm/llms/azure_ai/image_edit/mai_transformation.py
@@@ -90,17 -87,19 +90,17 @@@ class AzureFoundryMAIImageEditConfig(Op
self,
headers: dict,
model: str,
- api_key: Optional[str] = None,
- litellm_params: Optional[dict] = None,
- api_base: Optional[str] = None,
+ api_key: str | None = None,
+ litellm_params: dict | None = None,
+ api_base: str | None = 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 --cc litellm/llms/azure_ai/ocr/document_intelligence/transformation.py
index 4db4472dfc2,e7b94b3812b..a0e427eab9a
--- a/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py
+++ b/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py
@@@ -24,9 -24,10 +24,11 @@@ from litellm.constants import
AZURE_DOCUMENT_INTELLIGENCE_DEFAULT_DPI,
AZURE_OPERATION_POLLING_TIMEOUT,
)
- from litellm.litellm_core_utils.url_utils import encode_url_path_segment
+ from litellm.exceptions import UnsupportedParamsError
+ from litellm.litellm_core_utils.url_utils import SSRFError, assert_same_origin, 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 (
+ OCR_REQUEST_FORMAT_PARAM,
BaseOCRConfig,
DocumentType,
OCRPage,
diff --cc litellm/llms/azure_ai/rerank/transformation.py
index 24cdc67a23b,1212d2c1689..64372c53f09
--- a/litellm/llms/azure_ai/rerank/transformation.py
+++ b/litellm/llms/azure_ai/rerank/transformation.py
@@@ -2,8 -2,7 +2,8 @@@
Translate between Cohere's `/rerank` format and Azure AI's `/rerank` format.
"""
+from collections.abc import Mapping
- from typing import Optional
+ from typing import Final
import httpx
@@@ -64,15 -62,17 +64,15 @@@ class AzureAIRerankConfig(CohereRerankC
self,
headers: dict,
model: str,
- api_key: Optional[str] = None,
- optional_params: Optional[dict] = None,
+ 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("AZURE_AI_API_KEY") or litellm.azure_key
- default_headers = {
- 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: Final = {
- "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 --cc litellm/llms/base_llm/rerank/transformation.py
index e9f210fb31c,3a946fb4af4..5d2f92b5e82
--- a/litellm/llms/base_llm/rerank/transformation.py
+++ b/litellm/llms/base_llm/rerank/transformation.py
@@@ -1,6 -1,5 +1,6 @@@
from abc import ABC, abstractmethod
+from collections.abc import Mapping
- from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union
+ from typing import TYPE_CHECKING, Any, Final
import httpx
diff --cc litellm/llms/cohere/rerank/transformation.py
index 86d9a3d224d,76386252b79..a8e755406d8
--- a/litellm/llms/cohere/rerank/transformation.py
+++ b/litellm/llms/cohere/rerank/transformation.py
@@@ -1,5 -1,4 +1,5 @@@
+from collections.abc import Mapping
- from typing import Any, Dict, List, Union
+ from typing import Any, Final
import httpx
diff --cc litellm/llms/dashscope/rerank/transformation.py
index b8c369b892c,3c7801d4d3c..98be4e4f2e7
--- a/litellm/llms/dashscope/rerank/transformation.py
+++ b/litellm/llms/dashscope/rerank/transformation.py
@@@ -22,8 -22,7 +22,8 @@@ as supported only for gte-rerank-v2 / q
Docs - https://help.aliyun.com/zh/model-studio/text-rerank-api
"""
+from collections.abc import Mapping
- from typing import Any, Dict, List, Union
+ from typing import Any, Final
import httpx
diff --cc litellm/llms/deepinfra/rerank/transformation.py
index 87a6ecc7120,366b82e1dcf..e52c56af82b
--- a/litellm/llms/deepinfra/rerank/transformation.py
+++ b/litellm/llms/deepinfra/rerank/transformation.py
@@@ -2,8 -2,7 +2,8 @@@
Translate between Cohere's `/rerank` format and Deepinfra's `/rerank` format.
"""
+from collections.abc import Mapping
- from typing import Any, Dict, List, Union
+ from typing import Any, Final
import httpx
diff --cc litellm/llms/fireworks_ai/rerank/transformation.py
index e727f5c1d2b,fde4f55e75b..8ef2c9acccb
--- a/litellm/llms/fireworks_ai/rerank/transformation.py
+++ b/litellm/llms/fireworks_ai/rerank/transformation.py
@@@ -4,8 -4,7 +4,8 @@@ Fireworks AI Rerank API transformatio
Reference: https://docs.fireworks.ai/inference-api-reference/rerank
"""
+from collections.abc import Mapping
- from typing import Any, Dict, List, Union
+ from typing import Any, Final
import httpx
diff --cc litellm/llms/hosted_vllm/rerank/transformation.py
index cd35cc72492,74c13b450f5..0e8fa294f5d
--- a/litellm/llms/hosted_vllm/rerank/transformation.py
+++ b/litellm/llms/hosted_vllm/rerank/transformation.py
@@@ -2,8 -2,7 +2,8 @@@
Transformation logic for Hosted VLLM rerank
"""
+from collections.abc import Mapping
- from typing import Any, Dict, List, Union
+ from typing import Any, Final
import httpx
diff --cc litellm/llms/huggingface/rerank/transformation.py
index 245551cf4f2,d56a76c933f..334c60ee848
--- a/litellm/llms/huggingface/rerank/transformation.py
+++ b/litellm/llms/huggingface/rerank/transformation.py
@@@ -1,6 -1,5 +1,6 @@@
import os
+from collections.abc import Mapping
- from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union
+ from typing import TYPE_CHECKING, Any, Final
import httpx
from typing_extensions import TypedDict
@@@ -125,8 -123,7 +124,8 @@@ class HuggingFaceRerankConfig(BaseReran
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
- api_base: str | None = None,
+ litellm_params: Mapping[str, object] | None = None,
+ api_base: str | None = None,
) -> dict:
# Get API credentials
api_key, api_base = self.get_api_credentials(api_key=api_key, api_base=api_base)
diff --cc litellm/llms/infinity/rerank/transformation.py
index 7451b06c01a,ebcbf1b5a07..2526eb3b6a4
--- a/litellm/llms/infinity/rerank/transformation.py
+++ b/litellm/llms/infinity/rerank/transformation.py
@@@ -4,8 -4,7 +4,8 @@@ Transformation logic from Cohere's /v1/
Why separate file? Make it easy to see how transformation works
"""
+from collections.abc import Mapping
- from typing import List, Optional
+ from typing import Final
import httpx
@@@ -45,9 -44,8 +45,9 @@@ class InfinityRerankConfig(CohereRerank
self,
headers: dict,
model: str,
- api_key: Optional[str] = None,
- optional_params: Optional[dict] = None,
+ 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("INFINITY_API_KEY") or get_secret_str("INFINITY_API_KEY") or litellm.infinity_key
diff --cc litellm/llms/jina_ai/rerank/transformation.py
index 903e629803b,25607443292..199599d6b9c
--- a/litellm/llms/jina_ai/rerank/transformation.py
+++ b/litellm/llms/jina_ai/rerank/transformation.py
@@@ -6,8 -6,7 +6,8 @@@ Why separate file? Make it easy to see
Docs - https://jina.ai/reranker
"""
+from collections.abc import Mapping
- from typing import Any, Dict, List, Tuple, Union
+ from typing import Any, Final
from httpx import URL, Response
@@@ -140,8 -139,7 +140,8 @@@ class JinaAIRerankConfig(BaseRerankConf
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
- ) -> Dict:
+ ) -> dict:
if api_key is None:
raise ValueError("api_key is required. Set via `api_key` parameter or `JINA_API_KEY` environment variable.")
return {
diff --cc litellm/llms/nvidia_nim/rerank/transformation.py
index 07b792468c9,bb07f9ec74f..93e00dad9a1
--- a/litellm/llms/nvidia_nim/rerank/transformation.py
+++ b/litellm/llms/nvidia_nim/rerank/transformation.py
@@@ -1,5 -1,4 +1,5 @@@
+from collections.abc import Mapping
- from typing import Any, Dict, List, Literal, Union
+ from typing import Any, Final, Literal
import httpx
from typing_extensions import Required, TypedDict
diff --cc litellm/llms/vertex_ai/rerank/transformation.py
index 055a02aa40d,36876f67afc..2ec4f2da79b
--- a/litellm/llms/vertex_ai/rerank/transformation.py
+++ b/litellm/llms/vertex_ai/rerank/transformation.py
@@@ -4,8 -4,7 +4,8 @@@ Translates from Cohere's `/v1/rerank` i
Why separate file? Make it easy to see how transformation works
"""
+from collections.abc import Mapping
- from typing import Any, Dict, List, Union
+ from typing import Any, Final
import httpx
@@@ -74,16 -73,15 +74,16 @@@ class VertexAIRerankConfig(BaseRerankCo
headers: dict,
model: str,
api_key: str | None = None,
- optional_params: Dict | 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.)
- 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)
- litellm_params: Final = optional_params.copy() if optional_params else {}
- vertex_credentials: Final = self.safe_get_vertex_ai_credentials(litellm_params)
- vertex_project: Final = self.safe_get_vertex_ai_project(litellm_params)
++ vertex_params: Final = optional_params.copy() if optional_params else {}
++ vertex_credentials: Final = self.safe_get_vertex_ai_credentials(vertex_params)
++ vertex_project: Final = 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 --cc litellm/llms/voyage/rerank/transformation.py
index df9f32dd96d,497b2f62a97..ee330c92f1a
--- a/litellm/llms/voyage/rerank/transformation.py
+++ b/litellm/llms/voyage/rerank/transformation.py
@@@ -4,8 -4,7 +4,8 @@@ Transformation logic for Voyage AI's /v
Docs - https://docs.voyageai.com/docs/reranker
"""
+from collections.abc import Mapping
- from typing import Any, Dict, List, Tuple, Union
+ from typing import Any, Final
import httpx
@@@ -138,8 -137,7 +138,8 @@@ class VoyageRerankConfig(BaseRerankConf
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
- ) -> Dict:
+ ) -> dict:
if api_key is None:
api_key = get_secret_str("VOYAGE_API_KEY") or get_secret_str("VOYAGE_AI_API_KEY")
if api_key is None:
diff --cc litellm/llms/watsonx/rerank/transformation.py
index 549ccca4748,32b96db2817..293880b188d
--- a/litellm/llms/watsonx/rerank/transformation.py
+++ b/litellm/llms/watsonx/rerank/transformation.py
@@@ -5,8 -5,7 +5,8 @@@ Docs - https://cloud.ibm.com/apidocs/wa
"""
import uuid
+from collections.abc import Mapping
- from typing import Any, Dict, List, Union, cast
+ from typing import Any, Final, cast
import httpx
@@@ -61,11 -60,10 +61,11 @@@ class IBMWatsonXRerankConfig(IBMWatsonX
model: str,
api_key: str | None = None,
optional_params: dict | None = None,
+ litellm_params: Mapping[str, object] | None = None,
- ) -> Dict:
+ ) -> dict:
optional_params = optional_params or {}
- default_headers = {
+ default_headers: Final = {
"Content-Type": "application/json",
"Accept": "application/json",
}
diff --cc tests/test_litellm/llms/azure/test_azure_common_utils.py
index 450920f1f44,f2c852e9509..e69e0f1fe1e
--- a/tests/test_litellm/llms/azure/test_azure_common_utils.py
+++ b/tests/test_litellm/llms/azure/test_azure_common_utils.py
@@@ -7,16 -6,8 +6,13 @@@ from unittest.mock import MagicMock, pa
import pytest
- 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,
)
@@@ -2041,57 -2001,72 +2006,128 @@@ def test_azure_traditional_api_uses_azu
), 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
++
++
+ def test_evicting_an_azure_client_built_on_the_callers_session_leaves_it_open(monkeypatch):
+ """`initialize_azure_sdk_client` puts `litellm.aclient_session` on the SDK client.
+
+ That session belongs to the caller. `AsyncAzureOpenAI.close()` closes whatever
+ http client it was handed, so treating the wrapper as litellm's to close would
+ close the caller's shared session out from under them.
+ """
+ import httpx
+
+ from litellm.caching.evicted_client_closer import EvictedClientCloser
+ from litellm.caching.llm_caching_handler import LLMClientCache
+
+ shared_session = httpx.AsyncClient()
+ closer = EvictedClientCloser(grace_seconds=0.0)
+ monkeypatch.setattr(litellm, "aclient_session", shared_session)
+ monkeypatch.setattr(
+ litellm,
+ "in_memory_llm_clients_cache",
+ LLMClientCache(evicted_client_closer=closer),
+ )
+
+ wrapper = BaseAzureLLM().get_azure_openai_client(
+ api_key="not-a-real-key",
+ api_base="https://litellm.openai.azure.com",
+ api_version="2024-02-01",
+ litellm_params={},
+ _is_async=True,
+ )
+
+ assert wrapper is not None
+ assert wrapper._client is shared_session, "the wrapper should be built on the caller's session"
+
+ closer.schedule(wrapper)
+ closer.reap()
+
+ assert closer.pending_count == 0, "a wrapper around the caller's session must never be queued"
+ assert shared_session.is_closed is False, "closed the session the caller configured"
+
+
+ def test_an_azure_client_litellm_built_its_own_http_client_for_is_still_closed(monkeypatch):
+ """The ownership check must not turn the reclaim off for the ordinary case."""
+ from litellm.caching.evicted_client_closer import EvictedClientCloser
+ from litellm.caching.llm_caching_handler import LLMClientCache
+
+ closer = EvictedClientCloser(grace_seconds=0.0)
+ monkeypatch.setattr(litellm, "aclient_session", None)
+ monkeypatch.setattr(litellm, "client_session", None)
+ monkeypatch.setattr(
+ litellm,
+ "in_memory_llm_clients_cache",
+ LLMClientCache(evicted_client_closer=closer),
+ )
+
+ wrapper = BaseAzureLLM().get_azure_openai_client(
+ api_key="not-a-real-key",
+ api_base="https://litellm.openai.azure.com",
+ api_version="2024-02-01",
+ litellm_params={},
+ _is_async=False,
+ )
+
+ assert wrapper is not None
+ closer.schedule(wrapper)
+
+ assert closer.pending_count == 1, "litellm built this client's http client, so it owns it"
+
+ closer.reap()
+
+ assert wrapper.is_closed() is True
diff --cc tests/test_litellm/llms/azure_ai/image_edit/test_azure_ai_image_edit_transformation.py
index 9c9401fa8e9,667552dcf60..b6cb7ea9b54
--- 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
@@@ -1,14 -1,5 +1,9 @@@
- import os
- import sys
- 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,
)
diff --cc tests/test_litellm/llms/azure_ai/image_edit/test_mai_image_edit_transformation.py
index c4e39a26aeb,b948e46093a..284a912d9a4
--- 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
@@@ -6,9 -4,7 +4,8 @@@ from unittest.mock import MagicMoc
import httpx
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,
diff --cc tests/test_litellm/llms/azure_ai/rerank/test_azure_ai_rerank_transformation.py
index 150f5794ab1,ab497d06ca7..91bf665f18d
--- 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
@@@ -1,13 -1,7 +1,8 @@@
import pytest
- 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
diff --cc tests/test_litellm/llms/azure_ai/test_azure_ai_entra_auth.py
index 1145439a7b4,00000000000..c55bb2c3c36
mode 100644,000000..100644
--- 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
@@@ -1,154 -1,0 +1,154 @@@
+"""
+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:
++ with patch("litellm.llms.azure.common_utils.get_azure_ad_token_from_entra_id") as mock_entra_id: # test-quality-ok: stubs the Entra token fetch to assert the SP credential+scope plumbing and the returned Bearer header; live SP path proven by the PR's Azure Foundry e2e QA
+ 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:
++ with pytest.raises(ValueError, match="AZURE_AI_API_KEY") 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):
++def test_embedding_falls_back_to_entra_token_instead_of_openai_key(monkeypatch): # test-quality-ok: asserts the embedding handler is authed with the Entra token, not the OpenAI key fallback; live path proven by the PR's Azure Foundry e2e QA
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-openai-key")
+
- with patch.object(litellm.main.azure_ai_embedding, "embedding") as mock_embedding:
++ with patch.object(litellm.main.azure_ai_embedding, "embedding") as mock_embedding: # test-quality-ok: no injection seam for the embedding handler through the public embedding() API; live path proven by the PR's Azure Foundry e2e QA
+ 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:
++ with patch.object(litellm.images.main.azure_chat_completions, "image_generation") as mock_image_generation: # test-quality-ok: asserts image_generation forwards the computed Entra bearer header; no injection seam through the public API; live path proven by the PR's Azure Foundry e2e QA
+ 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
+
+
[email protected]("header_name", ["Authorization", "authorization", "api-key", "API-KEY"])
+def test_image_generation_keeps_caller_supplied_auth_header(header_name):
- with patch.object(litellm.images.main.azure_chat_completions, "image_generation") as mock_image_generation:
++ with patch.object(litellm.images.main.azure_chat_completions, "image_generation") as mock_image_generation: # test-quality-ok: asserts a caller-supplied auth header is preserved over Entra; no injection seam through the public API; live path proven by the PR's Azure Foundry e2e QA
+ 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={header_name: "caller-credential"},
+ )
+
+ headers = mock_image_generation.call_args.kwargs["headers"]
+ assert headers[header_name] == "caller-credential"
+ assert len(headers) == 2
+
+
+def test_image_generation_still_uses_api_key_header():
- with patch.object(litellm.images.main.azure_chat_completions, "image_generation") as mock_image_generation:
++ with patch.object(litellm.images.main.azure_chat_completions, "image_generation") as mock_image_generation: # test-quality-ok: asserts the api-key header path still works alongside Entra; no injection seam through the public API; live path proven by the PR's Azure Foundry e2e QA
+ 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