@@ -394,10 +394,46 @@ def test_azure_raises_error_when_api_key_missing():
394394
395395 # Clear environment variables
396396 with patch .dict (os .environ , {}, clear = True ):
397- with pytest .raises (ValueError , match = "Azure API key is required" ):
397+ with pytest .raises (ValueError , match = "Azure credentials required" ):
398398 AzureCompletion (model = "gpt-4" , endpoint = "https://test.openai.azure.com" )
399399
400400
401+ def test_azure_prefers_az_ad_token_over_env_api_key ():
402+ """
403+ Ensure AZURE_AD_TOKEN takes precedence over AZURE_API_KEY env var when no explicit api_key param is provided
404+ """
405+ pytest .importorskip ("azure.ai.inference" )
406+ from crewai .llms .providers .azure .completion import AzureCompletion
407+ from azure .core .credentials import AzureKeyCredential
408+
409+ env = {
410+ "AZURE_AD_TOKEN" : "test-ad-token" ,
411+ "AZURE_API_KEY" : "env-test-key" ,
412+ "AZURE_ENDPOINT" : "https://test.openai.azure.com" ,
413+ }
414+ with patch .dict (os .environ , env , clear = True ):
415+ completion = AzureCompletion (model = "gpt-4" , endpoint = os .environ ["AZURE_ENDPOINT" ])
416+ assert not isinstance (completion ._credential , AzureKeyCredential )
417+
418+
419+ def test_explicit_api_key_precedence_over_az_ad_token ():
420+ """
421+ Explicit `api_key` parameter should take precedence over AZURE_AD_TOKEN env var
422+ """
423+ pytest .importorskip ("azure.ai.inference" )
424+ from crewai .llms .providers .azure .completion import AzureCompletion
425+ from azure .core .credentials import AzureKeyCredential
426+
427+ env = {
428+ "AZURE_AD_TOKEN" : "test-ad-token" ,
429+ "AZURE_API_KEY" : "env-test-key" ,
430+ "AZURE_ENDPOINT" : "https://test.openai.azure.com" ,
431+ }
432+ with patch .dict (os .environ , env , clear = True ):
433+ completion = AzureCompletion (model = "gpt-4" , api_key = "explicit-key" , endpoint = os .environ ["AZURE_ENDPOINT" ])
434+ assert isinstance (completion ._credential , AzureKeyCredential )
435+
436+
401437def test_azure_endpoint_configuration ():
402438 """
403439 Test that Azure endpoint configuration works with multiple environment variable names
0 commit comments