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]

fix(azure): cache the remaining per-request Entra credentials and keep token refresh off the event loop (#47348)

Mateo Wangc0d88b46c9b5
diff --git a/litellm/llms/azure/common_utils.py b/litellm/llms/azure/common_utils.py
index f9f636244f4..52e3cdf380e 100644
--- a/litellm/llms/azure/common_utils.py
+++ b/litellm/llms/azure/common_utils.py
@@ -3,13 +3,15 @@ import hashlib
import json
import os
import re
-from collections.abc import Callable, Mapping
+from collections.abc import Awaitable, Callable, Mapping
+from contextlib import closing
from functools import lru_cache
from types import MappingProxyType
from typing import Final, Literal, NamedTuple, cast
import httpx
from openai import AsyncAzureOpenAI, AsyncOpenAI, AzureOpenAI, OpenAI
+from pydantic import ConfigDict, TypeAdapter, with_config
from typing_extensions import ReadOnly, TypedDict
import litellm
@@ -17,6 +19,7 @@ from litellm._logging import verbose_logger
from litellm.caching.caching import DualCache
from litellm.constants import DEFAULT_MAX_RETRIES
from litellm.llms.base_llm.chat.transformation import BaseLLMException
+from litellm.llms.custom_httpx.http_handler import HTTPHandler
from litellm.llms.openai.common_utils import BaseOpenAILLM, OpenAIAsyncHTTPClient, OpenAIHTTPClient
from litellm.secret_managers.get_azure_ad_token_provider import (
get_azure_ad_token_provider,
@@ -38,6 +41,16 @@ class _AzureV1ClientParams(TypedDict, total=False, extra_items=object):
base_url: ReadOnly[str]
+@with_config(ConfigDict(extra="allow"))
+class _AsyncAzureClientParams(TypedDict, total=False, extra_items=object):
+ api_key: ReadOnly[str | None]
+ azure_ad_token: ReadOnly[str | None]
+ azure_ad_token_provider: ReadOnly[Callable[[], str | Awaitable[str]] | None]
+
+
+_ASYNC_AZURE_CLIENT_PARAMS_ADAPTER: Final = TypeAdapter(_AsyncAzureClientParams)
+
+
class _AzureGatewayClientParams(TypedDict, total=False, extra_items=object):
api_version: ReadOnly[str]
base_url: ReadOnly[str]
@@ -98,11 +111,42 @@ def _cached_entra_id_token_provider(
return get_bearer_token_provider(ClientSecretCredential(tenant_id, client_id, client_secret), scope)
+@lru_cache(maxsize=128)
+def _cached_username_password_token_provider(
+ client_id: str,
+ azure_username: str,
+ azure_password: str,
+ scope: str,
+) -> Callable[[], str]:
+ from azure.identity import UsernamePasswordCredential, get_bearer_token_provider
+
+ credential: Final = UsernamePasswordCredential(
+ client_id=client_id,
+ username=azure_username,
+ password=azure_password,
+ )
+ return get_bearer_token_provider(credential, scope)
+
+
@lru_cache(maxsize=128)
def _cached_azure_ad_token_refresh_provider(scope: str) -> Callable[[], str]:
return get_azure_ad_token_provider(azure_scope=scope)
+def cached_azure_ad_token_refresh_provider(scope: str) -> Callable[[], str]:
+ return _cached_azure_ad_token_refresh_provider(scope)
+
+
+def _async_azure_ad_token_provider(
+ provider: Callable[[], str | Awaitable[str]],
+) -> Callable[[], Awaitable[str]]:
+ async def async_provider() -> str:
+ token: Final = await asyncio.to_thread(provider)
+ return token if isinstance(token, str) else await token
+
+ return async_provider
+
+
def get_azure_ad_token_from_entra_id(
tenant_id: str,
client_id: str,
@@ -177,22 +221,19 @@ def get_azure_ad_token_from_username_password(
Returns:
callable that returns a bearer token.
"""
- from azure.identity import UsernamePasswordCredential, get_bearer_token_provider
-
verbose_logger.debug(
"client_id=%s, azure_username=[set=%s], azure_password=[set=%s]",
client_id,
azure_username is not None,
azure_password is not None,
)
- credential: Final = UsernamePasswordCredential(
+ token_provider: Final = _cached_username_password_token_provider(
client_id=client_id,
- username=azure_username,
- password=azure_password,
+ azure_username=azure_username,
+ azure_password=azure_password,
+ scope=scope,
)
- token_provider: Final = get_bearer_token_provider(credential, scope)
-
verbose_logger.debug("token_provider %s", token_provider)
return token_provider
@@ -248,18 +289,17 @@ def get_azure_ad_token_from_oidc(
if azure_ad_token_access_token is not None:
return azure_ad_token_access_token
- client: Final = litellm.module_level_client
-
- req_token: Final = client.post(
- f"{azure_authority_host}/{azure_tenant_id}/oauth2/v2.0/token",
- data={
- "client_id": azure_client_id,
- "grant_type": "client_credentials",
- "scope": scope,
- "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
- "client_assertion": oidc_token,
- },
- )
+ with closing(HTTPHandler(timeout=litellm.request_timeout)) as client:
+ req_token: Final = client.post(
+ f"{azure_authority_host}/{azure_tenant_id}/oauth2/v2.0/token",
+ data={
+ "client_id": azure_client_id,
+ "grant_type": "client_credentials",
+ "scope": scope,
+ "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
+ "client_assertion": oidc_token,
+ },
+ )
if req_token.status_code != 200:
raise AzureOpenAIError(
@@ -560,22 +600,19 @@ class BaseAzureLLM(BaseOpenAILLM):
# on every request (via `_refresh_api_key`), so passing
# `azure_ad_token_provider` directly preserves Azure AD token refresh
# behavior that the regular AzureOpenAI client provides.
- v1_api_key: str | Callable[[], object] | None = (
- azure_client_params.get("api_key")
- or azure_client_params.get("azure_ad_token_provider")
- or azure_client_params.get("azure_ad_token")
+ v1_client_params: Final[_AsyncAzureClientParams] = _ASYNC_AZURE_CLIENT_PARAMS_ADAPTER.validate_python(
+ azure_client_params
+ )
+ v1_token_provider: Final = (
+ v1_client_params.get("api_key")
+ or v1_client_params.get("azure_ad_token_provider")
+ or v1_client_params.get("azure_ad_token")
+ )
+ v1_api_key: Final[str | Callable[[], str | Awaitable[str]] | None] = (
+ _async_azure_ad_token_provider(v1_token_provider)
+ if _is_async is True and callable(v1_token_provider)
+ else v1_token_provider
)
- if _is_async is True and callable(v1_api_key):
- # AsyncOpenAI expects an async provider; wrap the sync provider
- # returned by azure-identity. Offload to a thread so a token
- # refresh (blocking HTTP call to AAD on cache miss) does not
- # stall the event loop.
- _sync_provider: Final = v1_api_key
-
- async def _async_v1_api_key() -> str:
- return await asyncio.to_thread(_sync_provider)
-
- v1_api_key = _async_v1_api_key
v1_params: Final[_AzureV1ClientParams] = {
"api_key": v1_api_key,
@@ -597,7 +634,19 @@ class BaseAzureLLM(BaseOpenAILLM):
else:
# Traditional Azure API uses AzureOpenAI client
if _is_async is True:
- openai_client = AsyncAzureOpenAI(**azure_client_params)
+ async_azure_client_params: Final[_AsyncAzureClientParams] = (
+ _ASYNC_AZURE_CLIENT_PARAMS_ADAPTER.validate_python(azure_client_params)
+ )
+ async_token_provider_candidate: Final = async_azure_client_params.get("azure_ad_token_provider")
+ async_azure_client_params_with_threaded_provider: Final[_AsyncAzureClientParams] = (
+ {
+ **async_azure_client_params,
+ "azure_ad_token_provider": _async_azure_ad_token_provider(async_token_provider_candidate),
+ }
+ if async_token_provider_candidate is not None
+ else async_azure_client_params
+ )
+ openai_client = AsyncAzureOpenAI(**async_azure_client_params_with_threaded_provider)
else:
openai_client = AzureOpenAI(**azure_client_params)
diff --git a/litellm/llms/azure/search/transformation.py b/litellm/llms/azure/search/transformation.py
index 4264dae018a..f2bb2ecc68c 100644
--- a/litellm/llms/azure/search/transformation.py
+++ b/litellm/llms/azure/search/transformation.py
@@ -35,6 +35,7 @@ from typing import TYPE_CHECKING, Final, Literal
import httpx
from pydantic import ConfigDict, ValidationError
+from litellm.llms.azure.common_utils import cached_azure_ad_token_refresh_provider
from litellm.llms.base_llm.chat.transformation import BaseLLMException
from litellm.llms.base_llm.search.transformation import (
BaseSearchConfig,
@@ -263,9 +264,7 @@ def _search_tool(optional_params: Mapping[str, object]) -> _BingGroundingTool |
def _default_entra_token_minter() -> str:
- from litellm.secret_managers.get_azure_ad_token_provider import get_azure_ad_token_provider
-
- return get_azure_ad_token_provider(azure_scope=ENTRA_SCOPE)()
+ return cached_azure_ad_token_refresh_provider(ENTRA_SCOPE)()
class BingGroundingSearchConfig(BaseSearchConfig):
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index b03b8050299..48858dfa441 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -2953,14 +2953,15 @@ class BaseLLMHTTPHandler:
else:
async_httpx_client = client
- headers = responses_api_provider_config.validate_environment(
- headers=response_api_optional_request_params.get("extra_headers", {}) or {},
- model=model,
- litellm_params=litellm_params,
- )
-
- if extra_headers:
- headers.update(extra_headers)
+ validated_headers: Final = {
+ **await asyncio.to_thread(
+ responses_api_provider_config.validate_environment,
+ headers=response_api_optional_request_params.get("extra_headers", {}) or {},
+ model=model,
+ litellm_params=litellm_params,
+ ),
+ **(extra_headers or {}),
+ }
# Check if streaming is requested
stream = response_api_optional_request_params.get("stream", False)
@@ -2976,7 +2977,7 @@ class BaseLLMHTTPHandler:
input=input,
response_api_optional_request_params=response_api_optional_request_params,
litellm_params=litellm_params,
- headers=headers,
+ headers=validated_headers,
)
data = BaseResponsesAPIConfig.normalize_responses_api_request_dict(data)
@@ -3011,7 +3012,7 @@ class BaseLLMHTTPHandler:
headers, signed_body = await sign_request_off_loop_if_aws(
responses_api_provider_config,
responses_api_provider_config.sign_request,
- headers=headers,
+ headers=validated_headers,
optional_params=dict(litellm_params),
request_data=data,
api_base=api_base,
@@ -3145,8 +3146,11 @@ class BaseLLMHTTPHandler:
else:
async_httpx_client = client
- headers: Final = responses_api_provider_config.validate_environment(
- headers=extra_headers or {}, model="None", litellm_params=litellm_params
+ headers: Final = await asyncio.to_thread(
+ responses_api_provider_config.validate_environment,
+ headers=extra_headers or {},
+ model="None",
+ litellm_params=litellm_params,
)
if extra_headers:
@@ -3399,8 +3403,11 @@ class BaseLLMHTTPHandler:
else:
async_httpx_client = client
- headers: Final = responses_api_provider_config.validate_environment(
- headers=extra_headers or {}, model="None", litellm_params=litellm_params
+ headers: Final = await asyncio.to_thread(
+ responses_api_provider_config.validate_environment,
+ headers=extra_headers or {},
+ model="None",
+ litellm_params=litellm_params,
)
if extra_headers:
@@ -3563,8 +3570,11 @@ class BaseLLMHTTPHandler:
else:
async_httpx_client = client
- headers: Final = responses_api_provider_config.validate_environment(
- headers=extra_headers or {}, model="None", litellm_params=litellm_params
+ headers: Final = await asyncio.to_thread(
+ responses_api_provider_config.validate_environment,
+ headers=extra_headers or {},
+ model="None",
+ litellm_params=litellm_params,
)
if extra_headers:
@@ -4620,8 +4630,11 @@ class BaseLLMHTTPHandler:
else:
async_httpx_client = client
- headers: Final = responses_api_provider_config.validate_environment(
- headers=extra_headers or {}, model="None", litellm_params=litellm_params
+ headers: Final = await asyncio.to_thread(
+ responses_api_provider_config.validate_environment,
+ headers=extra_headers or {},
+ model="None",
+ litellm_params=litellm_params,
)
if extra_headers:
@@ -4795,12 +4808,15 @@ class BaseLLMHTTPHandler:
else:
async_httpx_client = client
- headers = responses_api_provider_config.validate_environment(
- headers=extra_headers or {}, model=model, litellm_params=litellm_params
- )
-
- if extra_headers:
- headers.update(extra_headers)
+ validated_headers: Final = {
+ **await asyncio.to_thread(
+ responses_api_provider_config.validate_environment,
+ headers=extra_headers or {},
+ model=model,
+ litellm_params=litellm_params,
+ ),
+ **(extra_headers or {}),
+ }
api_base: Final = responses_api_provider_config.get_complete_url(
api_base=litellm_params.api_base,
@@ -4816,14 +4832,14 @@ class BaseLLMHTTPHandler:
response_api_optional_request_params=response_api_optional_request_params,
api_base=api_base,
litellm_params=litellm_params,
- headers=headers,
+ headers=validated_headers,
)
data = BaseResponsesAPIConfig.normalize_responses_api_request_dict(data)
headers, signed_body = await sign_request_off_loop_if_aws(
responses_api_provider_config,
responses_api_provider_config.sign_request,
- headers=headers,
+ headers=validated_headers,
optional_params=dict(litellm_params),
request_data=data,
api_base=url,
@@ -6991,7 +7007,8 @@ class BaseLLMHTTPHandler:
**kwargs,
}
)
- headers: Final = responses_api_provider_config.validate_environment(
+ headers: Final = await asyncio.to_thread(
+ responses_api_provider_config.validate_environment,
headers={},
model=model,
litellm_params=litellm_params,
diff --git a/litellm/realtime_api/main.py b/litellm/realtime_api/main.py
index 96b4b081c05..ea47d744cae 100644
--- a/litellm/realtime_api/main.py
+++ b/litellm/realtime_api/main.py
@@ -562,7 +562,12 @@ async def _arealtime(
configured_realtime_protocol, query_params=query_params, websocket=websocket
)
resolved_azure_ad_token: Final = (
- None if api_key else get_azure_ad_token(GenericLiteLLMParams(**kwargs, azure_ad_token=azure_ad_token))
+ None
+ if api_key
+ else await asyncio.to_thread(
+ get_azure_ad_token,
+ GenericLiteLLMParams(**kwargs, azure_ad_token=azure_ad_token),
+ )
)
await azure_realtime.async_realtime(
model=model,
@@ -743,15 +748,21 @@ def _azure_realtime_health_protocol(
return "GA", query_params
-def _realtime_health_check_auth_headers(
+async def _realtime_health_check_auth_headers(
custom_llm_provider: str, api_key: str | None, model_params: Mapping[str, object]
) -> Mapping[str, str]:
if custom_llm_provider == "azure":
+ azure_ad_token: Final = (
+ None
+ if api_key
+ else await asyncio.to_thread(
+ get_azure_ad_token,
+ GenericLiteLLMParams.model_validate(dict(model_params)),
+ )
+ )
return azure_realtime.get_auth_headers(
api_key=api_key,
- azure_ad_token=(
- None if api_key else get_azure_ad_token(GenericLiteLLMParams.model_validate(dict(model_params)))
- ),
+ azure_ad_token=azure_ad_token,
)
if api_key is None:
return _EMPTY_AUTH_HEADERS
@@ -807,7 +818,7 @@ async def realtime_health_check(
if custom_llm_provider == LlmProviders.OPENAI.value
else resolved_api_key
)
- auth_headers: Final = _realtime_health_check_auth_headers(
+ auth_headers: Final = await _realtime_health_check_auth_headers(
custom_llm_provider=custom_llm_provider,
api_key=health_check_api_key,
model_params=resolved_params,
diff --git a/litellm/secret_managers/main.py b/litellm/secret_managers/main.py
index 716407d6def..d12e200772f 100644
--- a/litellm/secret_managers/main.py
+++ b/litellm/secret_managers/main.py
@@ -3,6 +3,8 @@ import base64
import os
import time
import traceback
+from collections.abc import Callable
+from functools import lru_cache
from typing import Final
import httpx
@@ -23,6 +25,11 @@ oidc_cache: Final = DualCache()
_PARSED_LITERAL: Final = TypeAdapter(object)
+@lru_cache(maxsize=128)
+def _cached_azure_oidc_token_provider(audience: str) -> Callable[[], str]:
+ return get_azure_ad_token_provider(azure_scope=audience)
+
+
_OIDC_TOKEN_EXPIRY_MARGIN_SECONDS: Final = 60
@@ -283,7 +290,7 @@ def get_secret(
verbose_logger.warning(
"AZURE_FEDERATED_TOKEN_FILE not found in environment will use Azure AD token provider"
)
- azure_token_provider: Final = get_azure_ad_token_provider(azure_scope=oidc_aud)
+ azure_token_provider: Final = _cached_azure_oidc_token_provider(oidc_aud)
try:
oidc_token = azure_token_provider()
if oidc_token is None:
diff --git a/tests/unit/litellm_core_utils/test_health_check_helpers.py b/tests/unit/litellm_core_utils/test_health_check_helpers.py
index 4f62c6fb096..c23749f7a20 100644
--- a/tests/unit/litellm_core_utils/test_health_check_helpers.py
+++ b/tests/unit/litellm_core_utils/test_health_check_helpers.py
@@ -534,12 +534,12 @@ async def test_ocr_health_check_sends_the_document_kind_the_provider_config_acce
assert document[expected_document_type].startswith(expected_uri_prefix)
-def test_realtime_health_check_azure_ad_params_drop_reserved_keys():
+async def test_realtime_health_check_azure_ad_params_drop_reserved_keys():
from litellm.realtime_api import main as realtime_main
seen = []
with patch.object(realtime_main, "get_azure_ad_token", lambda params: seen.append(params) or "ad-token"):
- headers = realtime_main._realtime_health_check_auth_headers(
+ headers = await realtime_main._realtime_health_check_auth_headers(
"azure",
None,
MappingProxyType({"api_base": "https://x.openai.azure.com", "self": 1, "params": 2, "__class__": 3}),
diff --git a/tests/unit/llms/azure/search/test_bing_grounding_search_transformation.py b/tests/unit/llms/azure/search/test_bing_grounding_search_transformation.py
index f8d042c14fd..dfd1474211f 100644
--- a/tests/unit/llms/azure/search/test_bing_grounding_search_transformation.py
+++ b/tests/unit/llms/azure/search/test_bing_grounding_search_transformation.py
@@ -1,5 +1,6 @@
import json, litellm
from pathlib import Path
+from typing import Final
from unittest.mock import AsyncMock, Mock, patch
import pytest
@@ -110,6 +111,27 @@ def test_validate_environment_entra_minter_failure_names_the_options():
assert "no az login" in message
+def test_default_entra_minter_reuses_provider(monkeypatch: pytest.MonkeyPatch) -> None:
+ import importlib
+
+ from litellm.llms.azure import common_utils
+ from litellm.llms.azure.search.transformation import _default_entra_token_minter
+
+ provider_module: Final = importlib.import_module("litellm.secret_managers.get_azure_ad_token_provider")
+ provider_factory: Final = Mock(side_effect=lambda **_: lambda: "entra-token")
+ common_utils._cached_azure_ad_token_refresh_provider.cache_clear()
+ monkeypatch.setattr(common_utils, "get_azure_ad_token_provider", provider_factory)
+ monkeypatch.setattr(provider_module, "get_azure_ad_token_provider", provider_factory)
+
+ try:
+ first: Final = _default_entra_token_minter()
+ second: Final = _default_entra_token_minter()
+ assert first == second == "entra-token"
+ assert provider_factory.call_count == 1
+ finally:
+ common_utils._cached_azure_ad_token_refresh_provider.cache_clear()
+
+
def test_validate_environment_does_not_mutate_and_is_idempotent():
config = _config()
caller_headers = {"X-Custom": "keep-me"}
diff --git a/tests/unit/llms/azure/test_azure_common_utils.py b/tests/unit/llms/azure/test_azure_common_utils.py
index 80449909b3f..41ad27d6f40 100644
--- a/tests/unit/llms/azure/test_azure_common_utils.py
+++ b/tests/unit/llms/azure/test_azure_common_utils.py
@@ -1,9 +1,12 @@
import json
import os
+import threading
import traceback
-from typing import Callable, Optional
+from typing import Callable, Final, Optional
+from urllib.parse import parse_qs
from unittest.mock import MagicMock, patch
+import httpx
import pytest
import litellm
@@ -13,6 +16,8 @@ from litellm.llms.azure.common_utils import (
_cached_entra_id_token_provider,
get_azure_ad_token,
get_azure_ad_token_from_entra_id,
+ get_azure_ad_token_from_oidc,
+ get_azure_ad_token_from_username_password,
)
from litellm.secret_managers.get_azure_ad_token_provider import (
get_azure_ad_token_provider,
@@ -2141,6 +2146,132 @@ class TestEntraIdTokenProviderCache:
assert mock_credential.call_count == 2
+def test_username_password_token_provider_reuses_same_credentials_and_separates_passwords() -> None:
+ with (
+ patch("azure.identity.UsernamePasswordCredential") as mock_credential,
+ patch(
+ "azure.identity.get_bearer_token_provider",
+ side_effect=lambda credential, scope: lambda: "token",
+ ),
+ ):
+ first: Final = get_azure_ad_token_from_username_password(
+ client_id="client",
+ azure_username="user",
+ azure_password="password",
+ scope="https://cognitiveservices.azure.com/.default",
+ )
+ second: Final = get_azure_ad_token_from_username_password(
+ client_id="client",
+ azure_username="user",
+ azure_password="password",
+ scope="https://cognitiveservices.azure.com/.default",
+ )
+ changed_password: Final = get_azure_ad_token_from_username_password(
+ client_id="client",
+ azure_username="user",
+ azure_password="different-password",
+ scope="https://cognitiveservices.azure.com/.default",
+ )
+
+ assert first() == second() == changed_password() == "token"
+ assert mock_credential.call_count == 2
+
+
+async def test_non_v1_azure_token_refresh_runs_off_the_event_loop_thread() -> None:
+ from openai import AsyncAzureOpenAI
+
+ def token_provider_naming_its_thread() -> str:
+ return str(threading.get_ident())
+
+ client: Final = BaseAzureLLM().get_azure_openai_client(
+ api_key=None,
+ api_base="https://test.openai.azure.com",
+ api_version="2024-02-01",
+ litellm_params={"azure_ad_token_provider": token_provider_naming_its_thread},
+ _is_async=True,
+ )
+
+ assert isinstance(client, AsyncAzureOpenAI)
+ try:
+ token_thread: Final = await client._get_azure_ad_token()
+ finally:
+ await client.close()
+
+ assert token_thread is not None
+ assert token_thread != str(threading.get_ident())
+
+
[email protected]("api_version", ["2024-02-01", "v1"])
+async def test_async_azure_ad_token_provider_reaches_azure_as_bearer_token(
+ monkeypatch: pytest.MonkeyPatch, api_version: str
+) -> None:
+ def echo_authorization(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ json={
+ "id": "chatcmpl-1",
+ "object": "chat.completion",
+ "created": 0,
+ "model": "gpt",
+ "choices": [
+ {
+ "index": 0,
+ "finish_reason": "stop",
+ "message": {"role": "assistant", "content": request.headers["authorization"]},
+ }
+ ],
+ },
+ )
+
+ async def async_token_provider() -> str:
+ return "async-token"
+
+ monkeypatch.setattr(
+ litellm, "aclient_session", httpx.AsyncClient(transport=httpx.MockTransport(echo_authorization))
+ )
+ client: Final = BaseAzureLLM().get_azure_openai_client(
+ api_key=None,
+ api_base=f"https://async-token-provider-{api_version}.openai.azure.com",
+ api_version=api_version,
+ litellm_params={"azure_ad_token_provider": async_token_provider},
+ _is_async=True,
+ )
+
+ response: Final = await client.chat.completions.create(model="gpt", messages=[{"role": "user", "content": "hi"}])
+
+ assert response.choices[0].message.content == "Bearer async-token"
+
+
+def test_oidc_token_exchange_closes_its_own_http_client(monkeypatch: pytest.MonkeyPatch) -> None:
+ class TokenEndpoint(httpx.BaseTransport):
+ def __init__(self) -> None:
+ self.closed = False
+
+ def handle_request(self, request: httpx.Request) -> httpx.Response:
+ form: Final = parse_qs(request.read().decode())
+ return httpx.Response(
+ 200, json={"access_token": f"minted-for-{form['client_assertion'][0]}", "expires_in": 3600}
+ )
+
+ def close(self) -> None:
+ self.closed = True
+
+ token_endpoint: Final = TokenEndpoint()
+ monkeypatch.setattr(litellm, "sync_transport", token_endpoint, raising=False)
+ monkeypatch.setenv("AZURE_TEST_OIDC_ASSERTION", "workload-jwt")
+
+ token: Final = get_azure_ad_token_from_oidc(
+ azure_ad_token="os.environ/AZURE_TEST_OIDC_ASSERTION",
+ azure_client_id="client",
+ azure_tenant_id="tenant-closes-its-client",
+ )
+
+ assert token == "minted-for-workload-jwt"
+ assert token_endpoint.closed
+
+
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.
diff --git a/tests/unit/llms/custom_httpx/test_llm_http_handler.py b/tests/unit/llms/custom_httpx/test_llm_http_handler.py
index 23c142b61ab..4e529764229 100644
--- a/tests/unit/llms/custom_httpx/test_llm_http_handler.py
+++ b/tests/unit/llms/custom_httpx/test_llm_http_handler.py
@@ -476,6 +476,42 @@ async def test_async_response_api_handler_streams_when_provider_transform_adds_s
assert client.post.call_args.kwargs["json"]["stream"] is True
+async def test_async_response_api_handler_validates_environment_off_the_event_loop() -> None:
+ def validate_environment(**_kwargs: object) -> dict[str, str]:
+ return {"validated-on-thread": str(threading.get_ident()), "x-override": "provider"}
+
+ config: Final = Mock()
+ config.validate_environment.side_effect = validate_environment
+ config.get_complete_url.return_value = "https://responses.example.com/v1/responses"
+ config.async_transform_responses_api_request = AsyncMock(return_value={"model": "model", "input": "hi"})
+ config.sign_request.return_value = ({}, None)
+ client: Final = AsyncMock(spec=AsyncHTTPHandler)
+ client.post.return_value = httpx.Response(
+ 200,
+ request=httpx.Request("POST", "https://responses.example.com/v1/responses"),
+ )
+ logging_obj: Final = Mock()
+ logging_obj.dynamic_success_callbacks = None
+
+ await BaseLLMHTTPHandler().async_response_api_handler(
+ model="model",
+ input="hi",
+ responses_api_provider_config=config,
+ response_api_optional_request_params={},
+ custom_llm_provider="test",
+ litellm_params=GenericLiteLLMParams(),
+ logging_obj=logging_obj,
+ client=client,
+ extra_headers={"x-override": "caller"},
+ )
+
+ validated_headers: Final = config.async_transform_responses_api_request.await_args.kwargs["headers"]
+ assert validated_headers["validated-on-thread"] != str(threading.get_ident())
+ assert validated_headers["x-override"] == "caller"
+ client.post.assert_awaited_once()
+
+
_CHATGPT_SSE_BODY = (
"event: response.output_item.done\n"
'data: {"type": "response.output_item.done", "output_index": 0, "item": {"type": "message", '