The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix: make response api support Azure Authentication method (#11941)
hsuyuminge3ba888c63f3
diff --git a/litellm/llms/azure/common_utils.py b/litellm/llms/azure/common_utils.pyindex ee154d2c8a1..ed62175289c 100644--- a/litellm/llms/azure/common_utils.py+++ b/litellm/llms/azure/common_utils.py@@ -6,6 +6,7 @@ import httpxfrom openai import AsyncAzureOpenAI, AzureOpenAIimport litellm+from litellm.types.router import GenericLiteLLMParamsfrom litellm._logging import verbose_loggerfrom litellm.caching.caching import DualCachefrom litellm.llms.base_llm.chat.transformation import BaseLLMException@@ -264,6 +265,126 @@ def select_azure_base_url_or_endpoint(azure_client_params: dict):return azure_client_params+def get_azure_ad_token(+ litellm_params: GenericLiteLLMParams,+) -> Optional[str]:+ """+ Get Azure AD token from various authentication methods.++ This function tries different methods to obtain an Azure AD token:+ 1. From an existing token provider+ 2. From Entra ID using tenant_id, client_id, and client_secret+ 3. From username and password+ 4. From OIDC token+ 5. From a service principal with secret workflow++ Args:+ litellm_params: Dictionary containing authentication parameters+ - azure_ad_token_provider: Optional callable that returns a token+ - azure_ad_token: Optional existing token+ - tenant_id: Optional Azure tenant ID+ - client_id: Optional Azure client ID+ - client_secret: Optional Azure client secret+ - azure_username: Optional Azure username+ - azure_password: Optional Azure password++ Returns:+ Azure AD token as string if successful, None otherwise+ """+ # Extract parameters+ azure_ad_token_provider = litellm_params.get("azure_ad_token_provider")+ azure_ad_token = litellm_params.get("azure_ad_token", None) or get_secret_str(+ "AZURE_AD_TOKEN"+ )+ tenant_id = litellm_params.get("tenant_id", os.getenv("AZURE_TENANT_ID"))+ client_id = litellm_params.get("client_id", os.getenv("AZURE_CLIENT_ID"))+ client_secret = litellm_params.get(+ "client_secret", os.getenv("AZURE_CLIENT_SECRET")+ )+ azure_username = litellm_params.get("azure_username", os.getenv("AZURE_USERNAME"))+ azure_password = litellm_params.get("azure_password", os.getenv("AZURE_PASSWORD"))+ scope = litellm_params.get(+ "azure_scope",+ os.getenv("AZURE_SCOPE", "https://cognitiveservices.azure.com/.default"),+ )+ if scope is None:+ scope = "https://cognitiveservices.azure.com/.default"++ # Try to get token provider from Entra ID+ if azure_ad_token_provider is None and tenant_id and client_id and client_secret:+ verbose_logger.debug(+ "Using Azure AD Token Provider from Entra ID for Azure Auth"+ )+ azure_ad_token_provider = get_azure_ad_token_from_entra_id(+ tenant_id=tenant_id,+ client_id=client_id,+ client_secret=client_secret,+ scope=scope,+ )++ # Try to get token provider from username and password+ if (+ azure_ad_token_provider is None+ and azure_username+ and azure_password+ and client_id+ ):+ verbose_logger.debug("Using Azure Username and Password for Azure Auth")+ azure_ad_token_provider = get_azure_ad_token_from_username_password(+ azure_username=azure_username,+ azure_password=azure_password,+ client_id=client_id,+ scope=scope,+ )++ # Try to get token from OIDC+ if (+ client_id+ and tenant_id+ and azure_ad_token+ and azure_ad_token.startswith("oidc/")+ ):+ verbose_logger.debug("Using Azure OIDC Token for Azure Auth")+ azure_ad_token = get_azure_ad_token_from_oidc(+ azure_ad_token=azure_ad_token,+ azure_client_id=client_id,+ azure_tenant_id=tenant_id,+ scope=scope,+ )+ # Try to get token provider from service principal+ elif (+ azure_ad_token_provider is None+ and litellm.enable_azure_ad_token_refresh is True+ ):+ verbose_logger.debug(+ "Using Azure AD token provider based on Service Principal with Secret workflow for Azure Auth"+ )+ try:+ azure_ad_token_provider = get_azure_ad_token_provider(azure_scope=scope)+ except ValueError:+ verbose_logger.debug("Azure AD Token Provider could not be used.")++ # Execute the token provider to get the token if available+ if azure_ad_token_provider and callable(azure_ad_token_provider):+ try:+ token = azure_ad_token_provider()+ if not isinstance(token, str):+ verbose_logger.error(+ f"Azure AD token provider returned non-string value: {type(token)}"+ )+ raise TypeError(f"Azure AD token must be a string, got {type(token)}")+ else:+ azure_ad_token = token+ except TypeError:+ # Re-raise TypeError directly+ raise+ except Exception as e:+ verbose_logger.error(f"Error calling Azure AD token provider: {str(e)}")+ raise RuntimeError(f"Failed to get Azure AD token: {str(e)}") from e++ return azure_ad_token++class BaseAzureLLM(BaseOpenAILLM):def get_azure_openai_client(self,diff --git a/litellm/llms/azure/responses/transformation.py b/litellm/llms/azure/responses/transformation.pyindex da80aa3735e..d5425ef4391 100644--- a/litellm/llms/azure/responses/transformation.py+++ b/litellm/llms/azure/responses/transformation.py@@ -4,6 +4,7 @@ import httpximport litellmfrom litellm._logging import verbose_logger+from litellm.llms.azure.common_utils import get_azure_ad_tokenfrom litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfigfrom litellm.secret_managers.main import get_secret_strfrom litellm.types.llms.openai import *@@ -21,24 +22,27 @@ else:class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig):def validate_environment(- self,- headers: dict,- model: str,- api_key: Optional[str] = None,+ self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]) -> dict:+ litellm_params = litellm_params or GenericLiteLLMParams()api_key = (- api_key+ litellm_params.api_keyor litellm.api_keyor litellm.azure_keyor get_secret_str("AZURE_OPENAI_API_KEY")or get_secret_str("AZURE_API_KEY"))- headers.update(- {- "Authorization": f"Bearer {api_key}",- }- )+ if api_key:+ headers["api-key"] = api_key+ return headers++ ### Fallback to Azure AD token-based authentication if no API key is available+ ### Retrieves Azure AD token and adds it to the Authorization header+ azure_ad_token = get_azure_ad_token(litellm_params)+ if azure_ad_token:+ headers["Authorization"] = f"Bearer {azure_ad_token}"+return headersdef get_complete_url(diff --git a/litellm/llms/base_llm/responses/transformation.py b/litellm/llms/base_llm/responses/transformation.pyindex b2a555086d8..e2f89da5e86 100644--- a/litellm/llms/base_llm/responses/transformation.py+++ b/litellm/llms/base_llm/responses/transformation.py@@ -63,10 +63,7 @@ class BaseResponsesAPIConfig(ABC):@abstractmethoddef validate_environment(- self,- headers: dict,- model: str,- api_key: Optional[str] = None,+ self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]) -> dict:return {}diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.pyindex 3a5490eee49..4ed0016d8b2 100644--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@ -1108,18 +1108,21 @@ class BaseLLMHTTPHandler:)# Prepare the request- headers, complete_url, binary_data, json_data = (- self._prepare_audio_transcription_request(- model=model,- audio_file=audio_file,- optional_params=optional_params,- litellm_params=litellm_params,- logging_obj=logging_obj,- api_key=api_key,- api_base=api_base,- headers=headers,- provider_config=provider_config,- )+ (+ headers,+ complete_url,+ binary_data,+ json_data,+ ) = self._prepare_audio_transcription_request(+ model=model,+ audio_file=audio_file,+ optional_params=optional_params,+ litellm_params=litellm_params,+ logging_obj=logging_obj,+ api_key=api_key,+ api_base=api_base,+ headers=headers,+ provider_config=provider_config,)if client is None or not isinstance(client, HTTPHandler):@@ -1170,18 +1173,21 @@ class BaseLLMHTTPHandler:)# Prepare the request- headers, complete_url, binary_data, json_data = (- self._prepare_audio_transcription_request(- model=model,- audio_file=audio_file,- optional_params=optional_params,- litellm_params=litellm_params,- logging_obj=logging_obj,- api_key=api_key,- api_base=api_base,- headers=headers,- provider_config=provider_config,- )+ (+ headers,+ complete_url,+ binary_data,+ json_data,+ ) = self._prepare_audio_transcription_request(+ model=model,+ audio_file=audio_file,+ optional_params=optional_params,+ litellm_params=litellm_params,+ logging_obj=logging_obj,+ api_key=api_key,+ api_base=api_base,+ headers=headers,+ provider_config=provider_config,)if client is None or not isinstance(client, AsyncHTTPHandler):@@ -1437,9 +1443,9 @@ class BaseLLMHTTPHandler:sync_httpx_client = clientheaders = responses_api_provider_config.validate_environment(- api_key=litellm_params.api_key,headers=response_api_optional_request_params.get("extra_headers", {}) or {},model=model,+ litellm_params=litellm_params,)if extra_headers:@@ -1557,9 +1563,9 @@ class BaseLLMHTTPHandler:async_httpx_client = clientheaders = responses_api_provider_config.validate_environment(- api_key=litellm_params.api_key,headers=response_api_optional_request_params.get("extra_headers", {}) or {},model=model,+ litellm_params=litellm_params,)if extra_headers:@@ -1678,9 +1684,7 @@ class BaseLLMHTTPHandler:async_httpx_client = clientheaders = responses_api_provider_config.validate_environment(- api_key=litellm_params.api_key,- headers=extra_headers or {},- model="None",+ headers=extra_headers or {}, model="None", litellm_params=litellm_params)if extra_headers:@@ -1762,9 +1766,7 @@ class BaseLLMHTTPHandler:sync_httpx_client = clientheaders = responses_api_provider_config.validate_environment(- api_key=litellm_params.api_key,- headers=extra_headers or {},- model="None",+ headers=extra_headers or {}, model="None", litellm_params=litellm_params)if extra_headers:@@ -1847,9 +1849,7 @@ class BaseLLMHTTPHandler:sync_httpx_client = clientheaders = responses_api_provider_config.validate_environment(- api_key=litellm_params.api_key,- headers=extra_headers or {},- model="None",+ headers=extra_headers or {}, model="None", litellm_params=litellm_params)if extra_headers:@@ -1915,9 +1915,7 @@ class BaseLLMHTTPHandler:async_httpx_client = clientheaders = responses_api_provider_config.validate_environment(- api_key=litellm_params.api_key,- headers=extra_headers or {},- model="None",+ headers=extra_headers or {}, model="None", litellm_params=litellm_params)if extra_headers:@@ -2008,9 +2006,7 @@ class BaseLLMHTTPHandler:sync_httpx_client = clientheaders = responses_api_provider_config.validate_environment(- api_key=litellm_params.api_key,- headers=extra_headers or {},- model="None",+ headers=extra_headers or {}, model="None", litellm_params=litellm_params)if extra_headers:@@ -2078,9 +2074,7 @@ class BaseLLMHTTPHandler:async_httpx_client = clientheaders = responses_api_provider_config.validate_environment(- api_key=litellm_params.api_key,- headers=extra_headers or {},- model="None",+ headers=extra_headers or {}, model="None", litellm_params=litellm_params)if extra_headers:@@ -2447,10 +2441,7 @@ class BaseLLMHTTPHandler:_is_async: bool = False,fake_stream: bool = False,litellm_metadata: Optional[Dict[str, Any]] = None,- ) -> Union[- ImageResponse,- Coroutine[Any, Any, ImageResponse],- ]:+ ) -> Union[ImageResponse, Coroutine[Any, Any, ImageResponse],]:"""Handles image edit requests.diff --git a/litellm/llms/openai/responses/transformation.py b/litellm/llms/openai/responses/transformation.pyindex 871662eccaf..cf742bc52cb 100644--- a/litellm/llms/openai/responses/transformation.py+++ b/litellm/llms/openai/responses/transformation.py@@ -92,13 +92,11 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig):return ResponsesAPIResponse(**raw_response_json)def validate_environment(- self,- headers: dict,- model: str,- api_key: Optional[str] = None,+ self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]) -> dict:+ litellm_params = litellm_params or GenericLiteLLMParams()api_key = (- api_key+ litellm_params.api_keyor litellm.api_keyor litellm.openai_keyor get_secret_str("OPENAI_API_KEY")diff --git a/tests/test_litellm/llms/azure/response/test_azure_transformation.py b/tests/test_litellm/llms/azure/response/test_azure_transformation.pynew file mode 100644index 00000000000..605c681c4a4--- /dev/null+++ b/tests/test_litellm/llms/azure/response/test_azure_transformation.py@@ -0,0 +1,108 @@+import os+import sys+from unittest.mock import patch++sys.path.insert(+ 0, os.path.abspath("../../../../..")+) # Adds the parent directory to the system path++from litellm.llms.azure.responses.transformation import AzureOpenAIResponsesAPIConfig+from litellm.types.router import GenericLiteLLMParams+++def test_validate_environment_api_key_within_litellm_params():+ azure_openai_responses_apiconfig = AzureOpenAIResponsesAPIConfig()+ litellm_params = GenericLiteLLMParams(api_key="test-api-key")++ result = azure_openai_responses_apiconfig.validate_environment(+ headers={}, model="", litellm_params=litellm_params+ )++ expected = {"api-key": "test-api-key"}++ assert result == expected+++def test_validate_environment_api_key_within_litellm():+ azure_openai_responses_apiconfig = AzureOpenAIResponsesAPIConfig()++ with patch("litellm.api_key", "test-api-key"):+ litellm_params = GenericLiteLLMParams()+ result = azure_openai_responses_apiconfig.validate_environment(+ headers={}, model="", litellm_params=litellm_params+ )++ expected = {"api-key": "test-api-key"}++ assert result == expected+++def test_validate_environment_azure_key_within_litellm():+ azure_openai_responses_apiconfig = AzureOpenAIResponsesAPIConfig()++ with patch("litellm.azure_key", "test-azure-key"):+ litellm_params = GenericLiteLLMParams()+ result = azure_openai_responses_apiconfig.validate_environment(+ headers={}, model="", litellm_params=litellm_params+ )++ expected = {"api-key": "test-azure-key"}++ assert result == expected+++def test_validate_environment_azure_openai_api_key_within_secret_str():+ azure_openai_responses_apiconfig = AzureOpenAIResponsesAPIConfig()++ with patch(+ "litellm.llms.azure.responses.transformation.get_secret_str"+ ) as mock_get_secret_str:+ # Configure the mock to return "test-api-key" when called with "AZURE_OPENAI_API_KEY"+ mock_get_secret_str.side_effect = (+ lambda key: "test-api-key" if key == "AZURE_OPENAI_API_KEY" else None+ )++ litellm_params = GenericLiteLLMParams()+ result = azure_openai_responses_apiconfig.validate_environment(+ headers={}, model="", litellm_params=litellm_params+ )+ expected = {"api-key": "test-api-key"}++ assert result == expected+++def test_validate_environment_azure_api_key_within_secret_str():+ azure_openai_responses_apiconfig = AzureOpenAIResponsesAPIConfig()++ with patch(+ "litellm.llms.azure.responses.transformation.get_secret_str"+ ) as mock_get_secret_str:+ # Configure the mock to return "test-api-key" when called with "AZURE_API_KEY"+ mock_get_secret_str.side_effect = (+ lambda key: "test-api-key" if key == "AZURE_API_KEY" else None+ )++ litellm_params = GenericLiteLLMParams()+ result = azure_openai_responses_apiconfig.validate_environment(+ headers={}, model="", litellm_params=litellm_params+ )+ expected = {"api-key": "test-api-key"}++ assert result == expected+++def test_validate_environment_get_azure_ad_token():+ azure_openai_responses_apiconfig = AzureOpenAIResponsesAPIConfig()++ with patch(+ "litellm.llms.azure.responses.transformation.get_azure_ad_token"+ ) as mock_get_azure_ad_token:+ mock_get_azure_ad_token.side_effect = lambda key: "test-azure-ad-token"++ litellm_params = GenericLiteLLMParams(azure_ad_token="test-azure-ad-token")+ result = azure_openai_responses_apiconfig.validate_environment(+ headers={}, model="", litellm_params=litellm_params+ )+ expected = {"Authorization": "Bearer test-azure-ad-token"}++ assert result == expecteddiff --git a/tests/test_litellm/llms/azure/test_azure_common_utils.py b/tests/test_litellm/llms/azure/test_azure_common_utils.pyindex f304ce43923..c3eab6e1578 100644--- a/tests/test_litellm/llms/azure/test_azure_common_utils.py+++ b/tests/test_litellm/llms/azure/test_azure_common_utils.py@@ -11,8 +11,9 @@ sys.path.insert(0, os.path.abspath("../../../..")) # Adds the parent directory to the system pathimport litellm-from litellm.llms.azure.common_utils import BaseAzureLLM+from litellm.llms.azure.common_utils import BaseAzureLLM, get_azure_ad_tokenfrom litellm.types.utils import CallTypes+from litellm.types.router import GenericLiteLLMParams# Mock the necessary dependencies@@ -994,3 +995,363 @@ def test_scope_always_string_in_initialize_azure_sdk_client(setup_mocks, monkeyp)print("All scope tests passed - scope is always a string")+++def test_with_existing_token_provider(setup_mocks):+ """Test get_azure_ad_token with an existing token provider."""+ token_provider = lambda: "test-token"+ litellm_params = GenericLiteLLMParams(azure_ad_token_provider=token_provider)++ token = get_azure_ad_token(litellm_params)++ assert token == "test-token"+++def test_with_existing_azure_ad_token(setup_mocks):+ """Test get_azure_ad_token with an existing azure ad token."""+ litellm_params = GenericLiteLLMParams(azure_ad_token="test-token")++ token = get_azure_ad_token(litellm_params)++ assert token == "test-token"+++def test_with_existing_azure_ad_token_from_env(setup_mocks):+ """Test get_azure_ad_token with an existing AZURE_AD_TOKEN from env."""++ # mock get_secret_str("AZURE_AD_TOKEN") to "test-token"+ with patch("litellm.llms.azure.common_utils.get_secret_str") as mock_get_secret_str:+ # Configure the mock to return "test-token" when called with "AZURE_AD_TOKEN"+ mock_get_secret_str.side_effect = (+ lambda key: "test-token" if key == "AZURE_AD_TOKEN" else None+ )++ litellm_params = GenericLiteLLMParams()++ token = get_azure_ad_token(litellm_params)++ assert token == "test-token"+ # Verify that get_secret_str was called with "AZURE_AD_TOKEN"+ mock_get_secret_str.assert_called_with("AZURE_AD_TOKEN")+++def test_get_azure_ad_token_with_client_id_and_client_secret(setup_mocks):+ """Test get_azure_ad_token with tenant_id, client_id, and client_secret."""+ # Reset mocks to ensure clean state+ setup_mocks["entra_token"].reset_mock()++ # Create test parameters with username, password, and client_id+ # but no other authentication methods+ litellm_params = GenericLiteLLMParams(+ tenant_id="test-tenant-id",+ client_id="test-client-id",+ client_secret="test-client-secret",+ azure_scope="test-azure-scope",+ )++ # Call the function+ token = get_azure_ad_token(litellm_params)++ # Verify the debug message was logged+ setup_mocks["logger"].debug.assert_any_call(+ "Using Azure AD Token Provider from Entra ID for Azure Auth"+ )++ # Verify get_azure_ad_token_from_entra_id was called with correct params+ setup_mocks["entra_token"].assert_called_once_with(+ tenant_id="test-tenant-id",+ client_id="test-client-id",+ client_secret="test-client-secret",+ scope="test-azure-scope",+ )++ # Verify the token is what we expect from our mock+ assert token == "mock-entra-token"+++def test_get_azure_ad_token_with_client_id_and_client_secret_from_env(+ setup_mocks, monkeypatch+):+ """Test get_azure_ad_token with tenant_id, client_id, and client_secret from env."""+ # Reset mocks to ensure clean state+ setup_mocks["entra_token"].reset_mock()++ # Set environment variables+ monkeypatch.setenv("AZURE_TENANT_ID", "test-tenant-id")+ monkeypatch.setenv("AZURE_CLIENT_ID", "test-client-id")+ monkeypatch.setenv("AZURE_CLIENT_SECRET", "test-client-secret")+ monkeypatch.setenv("AZURE_SCOPE", "test-azure-scope")++ # Create test parameters with username, password, and client_id+ # but no other authentication methods+ litellm_params = GenericLiteLLMParams()++ # Call the function+ token = get_azure_ad_token(litellm_params)++ # Verify the debug message was logged+ setup_mocks["logger"].debug.assert_any_call(+ "Using Azure AD Token Provider from Entra ID for Azure Auth"+ )++ # Verify get_azure_ad_token_from_entra_id was called with correct params+ setup_mocks["entra_token"].assert_called_once_with(+ tenant_id="test-tenant-id",+ client_id="test-client-id",+ client_secret="test-client-secret",+ scope="test-azure-scope",+ )++ # Verify the token is what we expect from our mock+ assert token == "mock-entra-token"+++def test_get_azure_ad_token_with_username_password(setup_mocks):+ """Test get_azure_ad_token with username, password, and client_id."""+ # Reset mocks to ensure clean state+ setup_mocks["username_password_token"].reset_mock()++ # Create test parameters with username, password, and client_id+ # but no other authentication methods+ litellm_params = GenericLiteLLMParams(+ azure_username="test-username",+ azure_password="test-password",+ client_id="test-client-id",+ azure_scope="test-azure-scope",+ # Ensure no other auth methods are available+ azure_ad_token_provider=None,+ azure_ad_token=None,+ tenant_id=None,+ client_secret=None,+ )++ # Call the function+ token = get_azure_ad_token(litellm_params)++ # Verify the debug message was logged+ setup_mocks["logger"].debug.assert_any_call(+ "Using Azure Username and Password for Azure Auth"+ )++ # Verify get_azure_ad_token_from_username_password was called with correct params+ setup_mocks["username_password_token"].assert_called_once_with(+ azure_username="test-username",+ azure_password="test-password",+ client_id="test-client-id",+ scope="test-azure-scope",+ )++ # Verify the token is what we expect from our mock+ assert token == "mock-username-password-token"+++def test_get_azure_ad_token_with_missing_username_password(setup_mocks):+ """Test get_azure_ad_token skips username/password auth when credentials are incomplete."""+ # Reset mocks to ensure clean state+ setup_mocks["username_password_token"].reset_mock()++ # Test cases with missing credentials+ test_cases = [+ # Missing username+ GenericLiteLLMParams(+ azure_username=None,+ azure_password="test-password",+ client_id="test-client-id",+ ),+ # Missing password+ GenericLiteLLMParams(+ azure_username="test-username",+ azure_password=None,+ client_id="test-client-id",+ ),+ # Missing client_id+ GenericLiteLLMParams(+ azure_username="test-username",+ azure_password="test-password",+ client_id=None,+ ),+ ]++ for params in test_cases:+ # Call the function+ get_azure_ad_token(params)++ # Verify username/password auth was not used+ setup_mocks["username_password_token"].assert_not_called()++ # Reset mock for next test case+ setup_mocks["username_password_token"].reset_mock()+++def test_get_azure_ad_token_with_username_password_from_env(setup_mocks, monkeypatch):+ """Test get_azure_ad_token with username, password, and client_id from environment variables."""+ # Reset mocks to ensure clean state+ setup_mocks["username_password_token"].reset_mock()++ # Set environment variables+ monkeypatch.setenv("AZURE_USERNAME", "env-username")+ monkeypatch.setenv("AZURE_PASSWORD", "env-password")+ monkeypatch.setenv("AZURE_CLIENT_ID", "env-client-id")+ monkeypatch.setenv("AZURE_SCOPE", "test-azure-scope")++ # Create test parameters with no explicit credentials+ litellm_params = GenericLiteLLMParams(+ # Ensure no other auth methods are available+ azure_ad_token_provider=None,+ azure_ad_token=None,+ tenant_id=None,+ client_secret=None,+ # Don't set username, password, or client_id directly+ )++ # Call the function+ token = get_azure_ad_token(litellm_params)++ # Verify the debug message was logged+ setup_mocks["logger"].debug.assert_any_call(+ "Using Azure Username and Password for Azure Auth"+ )++ # Verify get_azure_ad_token_from_username_password was called with correct params from env+ setup_mocks["username_password_token"].assert_called_once_with(+ azure_username="env-username",+ azure_password="env-password",+ client_id="env-client-id",+ scope="test-azure-scope",+ )++ # Verify the token is what we expect from our mock+ assert token == "mock-username-password-token"+++def test_get_azure_ad_token_with_oidc_token(setup_mocks):+ """Test get_azure_ad_token with OIDC token."""+ # Reset mocks to ensure clean state+ setup_mocks["oidc_token"].reset_mock()++ # Create test parameters with OIDC token, client_id, and tenant_id+ litellm_params = GenericLiteLLMParams(+ azure_ad_token="oidc/test-token",+ client_id="test-client-id",+ tenant_id="test-tenant-id",+ azure_scope="test-azure-scope",+ # Ensure no other auth methods are available+ azure_ad_token_provider=None,+ )++ # Call the function+ token = get_azure_ad_token(litellm_params)++ # Verify the debug message was logged+ setup_mocks["logger"].debug.assert_any_call("Using Azure OIDC Token for Azure Auth")++ # Verify get_azure_ad_token_from_oidc was called with correct params+ setup_mocks["oidc_token"].assert_called_once_with(+ azure_ad_token="oidc/test-token",+ azure_client_id="test-client-id",+ azure_tenant_id="test-tenant-id",+ scope="test-azure-scope",+ )++ # Verify the token is what we expect from our mock+ assert token == "mock-oidc-token"+++def test_get_azure_ad_token_with_token_refresh(setup_mocks):+ """Test get_azure_ad_token with token refresh enabled."""+ # Reset mocks to ensure clean state+ setup_mocks["token_provider"].reset_mock()++ # Enable token refresh+ setup_mocks["litellm"].enable_azure_ad_token_refresh = True++ # Create test parameters with no other auth methods available+ litellm_params = GenericLiteLLMParams()++ # Call the function+ token = get_azure_ad_token(litellm_params)++ # Verify the debug message was logged+ setup_mocks["logger"].debug.assert_any_call(+ "Using Azure AD token provider based on Service Principal with Secret workflow for Azure Auth"+ )++ # Verify get_azure_ad_token_provider was called+ setup_mocks["token_provider"].assert_called_once()++ # Verify the token is what we expect from our mock+ assert token == "mock-default-token"+++def test_get_azure_ad_token_with_token_refresh_error(setup_mocks):+ """Test get_azure_ad_token with token refresh enabled but raising an error."""+ # Reset mocks to ensure clean state+ setup_mocks["token_provider"].reset_mock()++ # Enable token refresh but make it raise an error+ setup_mocks["litellm"].enable_azure_ad_token_refresh = True+ setup_mocks["token_provider"].side_effect = ValueError("Token provider error")++ # Create test parameters with no other auth methods available+ litellm_params = GenericLiteLLMParams()++ # Call the function+ token = get_azure_ad_token(litellm_params)++ # Verify the debug message was logged+ setup_mocks["logger"].debug.assert_any_call(+ "Using Azure AD token provider based on Service Principal with Secret workflow for Azure Auth"+ )++ # Verify error was logged+ setup_mocks["logger"].debug.assert_any_call(+ "Azure AD Token Provider could not be used."+ )++ # Verify get_azure_ad_token_provider was called+ setup_mocks["token_provider"].assert_called_once()++ # Verify the token is None since the provider raised an error+ assert token is None+++def test_token_provider_returns_non_string(setup_mocks):+ """Test that get_azure_ad_token raises TypeError when token provider returns non-string value."""+ # Create a token provider that returns a non-string value+ non_string_provider = lambda: 123 # Returns an integer instead of a string++ # Create test parameters with the non-string token provider+ litellm_params = GenericLiteLLMParams(azure_ad_token_provider=non_string_provider)++ # Call the function and expect a TypeError+ with pytest.raises(TypeError) as excinfo:+ get_azure_ad_token(litellm_params)++ # Verify the error message+ assert "Azure AD token must be a string" in str(excinfo.value)++ # Verify the error was logged+ setup_mocks["logger"].error.assert_any_call(+ "Azure AD token provider returned non-string value: <class 'int'>"+ )+++def test_token_provider_raises_exception(setup_mocks):+ """Test that get_azure_ad_token raises RuntimeError when token provider raises an exception."""+ # Create a token provider that raises an exception+ error_message = "Test provider error"+ error_provider = lambda: exec('raise ValueError("' + error_message + '")')++ # Create test parameters with the error-raising token provider+ litellm_params = GenericLiteLLMParams(azure_ad_token_provider=error_provider)++ # Call the function and expect a RuntimeError+ with pytest.raises(RuntimeError) as excinfo:+ get_azure_ad_token(litellm_params)++ # Verify the error message+ assert "Failed to get Azure AD token" in str(excinfo.value)+ assert error_message in str(excinfo.value)++ # Verify the error was logged+ setup_mocks["logger"].error.assert_called()diff --git a/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py b/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.pyindex a926c33f53b..db0a69482b2 100644--- a/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py+++ b/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py@@ -153,9 +153,9 @@ class TestOpenAIResponsesAPIConfig:# Test with provided API keyheaders = {}api_key = "test_api_key"-+ litellm_params = GenericLiteLLMParams(api_key=api_key)result = self.config.validate_environment(- headers=headers, model=self.model, api_key=api_key+ headers=headers, model=self.model, litellm_params=litellm_params)assert "Authorization" in result@@ -165,7 +165,10 @@ class TestOpenAIResponsesAPIConfig:headers = {}with patch("litellm.api_key", "litellm_api_key"):- result = self.config.validate_environment(headers=headers, model=self.model)+ litellm_params = GenericLiteLLMParams()+ result = self.config.validate_environment(+ headers=headers, model=self.model, litellm_params=litellm_params+ )assert "Authorization" in resultassert result["Authorization"] == "Bearer litellm_api_key"@@ -175,8 +178,9 @@ class TestOpenAIResponsesAPIConfig:with patch("litellm.openai_key", "openai_key"):with patch("litellm.api_key", None):+ litellm_params = GenericLiteLLMParams()result = self.config.validate_environment(- headers=headers, model=self.model+ headers=headers, model=self.model, litellm_params=litellm_params)assert "Authorization" in result@@ -193,8 +197,9 @@ class TestOpenAIResponsesAPIConfig:"litellm.llms.openai.responses.transformation.get_secret_str",return_value="env_api_key",):+ litellm_params = GenericLiteLLMParams()result = self.config.validate_environment(- headers=headers, model=self.model+ headers=headers, model=self.model, litellm_params=litellm_params)assert "Authorization" in result