Skip to content

Commit e6bbbbe

Browse files
Unify Azure credential handling across all Python packages
Replace ad_token, ad_token_provider, and get_entra_auth_token with a unified credential parameter across all Azure-related packages. Core changes: - Add AzureCredentialTypes (TokenCredential | AsyncTokenCredential) and AzureTokenProvider (Callable[[], str | Awaitable[str]]) type aliases - Add resolve_credential_to_token_provider() using azure.identity's get_bearer_token_provider for automatic token caching/refresh - Update AzureOpenAIChatClient, AzureOpenAIResponsesClient, and AzureOpenAIAssistantsClient to accept credential: AzureCredentialTypes | AzureTokenProvider - Remove ad_token, ad_token_provider params and get_entra_auth_token helpers Package updates: - azure-ai: Accept AzureCredentialTypes on AzureAIClient, AzureAIAgentClient, AzureAIProjectAgentProvider, AzureAIAgentsProvider - azure-ai-search: Accept AzureCredentialTypes on AzureAISearchContextProvider - purview: Accept AzureCredentialTypes | AzureTokenProvider on PurviewClient, PurviewPolicyMiddleware, PurviewChatPolicyMiddleware Fixes microsoft#3449 Fixes microsoft#3500 Co-authored-by: Copilot <[email protected]>
1 parent b05fc9e commit e6bbbbe

16 files changed

Lines changed: 196 additions & 344 deletions

File tree

‎python/packages/azure-ai-search/agent_framework_azure_ai_search/_context_provider.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from agent_framework import AGENT_FRAMEWORK_USER_AGENT, Message
1717
from agent_framework._sessions import AgentSession, BaseContextProvider, SessionContext
1818
from agent_framework._settings import SecretString, load_settings
19+
from agent_framework.azure._entra_id_authentication import AzureCredentialTypes
1920
from agent_framework.exceptions import ServiceInitializationError
2021
from azure.core.credentials import AzureKeyCredential
2122
from azure.core.credentials_async import AsyncTokenCredential
@@ -148,7 +149,7 @@ def __init__(
148149
endpoint: str | None = None,
149150
index_name: str | None = None,
150151
api_key: str | AzureKeyCredential | None = None,
151-
credential: AsyncTokenCredential | None = None,
152+
credential: AzureCredentialTypes | None = None,
152153
*,
153154
mode: Literal["semantic", "agentic"] = "semantic",
154155
top_k: int = 5,
@@ -175,7 +176,8 @@ def __init__(
175176
endpoint: Azure AI Search endpoint URL.
176177
index_name: Name of the search index to query.
177178
api_key: API key for authentication.
178-
credential: AsyncTokenCredential for managed identity authentication.
179+
credential: Azure credential for managed identity authentication.
180+
Accepts a TokenCredential, AsyncTokenCredential, or a callable token provider.
179181
mode: Search mode - "semantic" or "agentic". Default: "semantic".
180182
top_k: Maximum number of documents to retrieve. Default: 5.
181183
semantic_configuration_name: Name of semantic configuration in the index.
@@ -223,7 +225,7 @@ def __init__(
223225

224226
resolved_credential: AzureKeyCredential | AsyncTokenCredential
225227
if credential:
226-
resolved_credential = credential
228+
resolved_credential = credential # type: ignore[assignment]
227229
elif isinstance(api_key, AzureKeyCredential):
228230
resolved_credential = api_key
229231
elif settings.get("api_key"):

‎python/packages/azure-ai/agent_framework_azure_ai/_agent_provider.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@
1717
from agent_framework._mcp import MCPTool
1818
from agent_framework._settings import load_settings
1919
from agent_framework._tools import ToolTypes
20+
from agent_framework.azure._entra_id_authentication import AzureCredentialTypes
2021
from agent_framework.exceptions import ServiceInitializationError
2122
from azure.ai.agents.aio import AgentsClient
2223
from azure.ai.agents.models import Agent as AzureAgent
2324
from azure.ai.agents.models import ResponseFormatJsonSchema, ResponseFormatJsonSchemaType
24-
from azure.core.credentials_async import AsyncTokenCredential
2525
from pydantic import BaseModel
2626

2727
from ._chat_client import AzureAIAgentClient, AzureAIAgentOptions
@@ -93,7 +93,7 @@ def __init__(
9393
agents_client: AgentsClient | None = None,
9494
*,
9595
project_endpoint: str | None = None,
96-
credential: AsyncTokenCredential | None = None,
96+
credential: AzureCredentialTypes | None = None,
9797
env_file_path: str | None = None,
9898
env_file_encoding: str | None = None,
9999
) -> None:
@@ -106,7 +106,8 @@ def __init__(
106106
Keyword Args:
107107
project_endpoint: The Azure AI Project endpoint URL.
108108
Can also be set via AZURE_AI_PROJECT_ENDPOINT environment variable.
109-
credential: Azure async credential for authentication.
109+
credential: Azure credential for authentication. Accepts a TokenCredential,
110+
AsyncTokenCredential, or a callable token provider.
110111
Required if agents_client is not provided.
111112
env_file_path: Path to .env file for loading settings.
112113
env_file_encoding: Encoding of the .env file.
@@ -137,7 +138,7 @@ def __init__(
137138
raise ServiceInitializationError("Azure credential is required when agents_client is not provided.")
138139
self._agents_client = AgentsClient(
139140
endpoint=resolved_endpoint,
140-
credential=credential,
141+
credential=credential, # type: ignore[arg-type]
141142
user_agent=AGENT_FRAMEWORK_USER_AGENT,
142143
)
143144
self._should_close_client = True

‎python/packages/azure-ai/agent_framework_azure_ai/_chat_client.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
)
3636
from agent_framework._settings import load_settings
3737
from agent_framework._tools import ToolTypes
38+
from agent_framework.azure._entra_id_authentication import AzureCredentialTypes
3839
from agent_framework.exceptions import ServiceInitializationError, ServiceInvalidRequestError, ServiceResponseException
3940
from agent_framework.observability import ChatTelemetryLayer
4041
from azure.ai.agents.aio import AgentsClient
@@ -84,7 +85,6 @@
8485
ToolDefinition,
8586
ToolOutput,
8687
)
87-
from azure.core.credentials_async import AsyncTokenCredential
8888
from pydantic import BaseModel
8989

9090
from ._shared import AzureAISettings, to_azure_ai_agent_tools
@@ -415,7 +415,7 @@ def __init__(
415415
thread_id: str | None = None,
416416
project_endpoint: str | None = None,
417417
model_deployment_name: str | None = None,
418-
credential: AsyncTokenCredential | None = None,
418+
credential: AzureCredentialTypes | None = None,
419419
should_cleanup_agent: bool = True,
420420
middleware: Sequence[ChatAndFunctionMiddlewareTypes] | None = None,
421421
function_invocation_configuration: FunctionInvocationConfiguration | None = None,
@@ -439,7 +439,8 @@ def __init__(
439439
Ignored when a agents_client is passed.
440440
model_deployment_name: The model deployment name to use for agent creation.
441441
Can also be set via environment variable AZURE_AI_MODEL_DEPLOYMENT_NAME.
442-
credential: Azure async credential to use for authentication.
442+
credential: Azure credential for authentication. Accepts a TokenCredential,
443+
AsyncTokenCredential, or a callable token provider.
443444
should_cleanup_agent: Whether to cleanup (delete) agents created by this client when
444445
the client is closed or context is exited. Defaults to True. Only affects agents
445446
created by this client instance; existing agents passed via agent_id are never deleted.
@@ -513,7 +514,7 @@ class MyOptions(AzureAIAgentOptions, total=False):
513514
raise ServiceInitializationError("Azure credential is required when agents_client is not provided.")
514515
agents_client = AgentsClient(
515516
endpoint=resolved_endpoint,
516-
credential=credential,
517+
credential=credential, # type: ignore[arg-type]
517518
user_agent=AGENT_FRAMEWORK_USER_AGENT,
518519
)
519520
should_close_client = True

‎python/packages/azure-ai/agent_framework_azure_ai/_client.py‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
)
2424
from agent_framework._settings import load_settings
2525
from agent_framework._tools import ToolTypes
26+
from agent_framework.azure._entra_id_authentication import AzureCredentialTypes
2627
from agent_framework.exceptions import ServiceInitializationError
2728
from agent_framework.observability import ChatTelemetryLayer
2829
from agent_framework.openai import OpenAIResponsesOptions
@@ -41,7 +42,6 @@
4142
WebSearchPreviewTool,
4243
)
4344
from azure.ai.projects.models import FileSearchTool as ProjectsFileSearchTool
44-
from azure.core.credentials_async import AsyncTokenCredential
4545
from azure.core.exceptions import ResourceNotFoundError
4646

4747
from ._shared import AzureAISettings, create_text_format_config
@@ -109,7 +109,7 @@ def __init__(
109109
conversation_id: str | None = None,
110110
project_endpoint: str | None = None,
111111
model_deployment_name: str | None = None,
112-
credential: AsyncTokenCredential | None = None,
112+
credential: AzureCredentialTypes | None = None,
113113
use_latest_version: bool | None = None,
114114
env_file_path: str | None = None,
115115
env_file_encoding: str | None = None,
@@ -132,7 +132,8 @@ def __init__(
132132
Ignored when a project_client is passed.
133133
model_deployment_name: The model deployment name to use for agent creation.
134134
Can also be set via environment variable AZURE_AI_MODEL_DEPLOYMENT_NAME.
135-
credential: Azure async credential to use for authentication.
135+
credential: Azure credential for authentication. Accepts a TokenCredential,
136+
AsyncTokenCredential, or a callable token provider.
136137
use_latest_version: Boolean flag that indicates whether to use latest agent version
137138
if it exists in the service.
138139
env_file_path: Path to environment file for loading settings.
@@ -197,7 +198,7 @@ class MyOptions(ChatOptions, total=False):
197198
raise ServiceInitializationError("Azure credential is required when project_client is not provided.")
198199
project_client = AIProjectClient(
199200
endpoint=resolved_endpoint,
200-
credential=credential,
201+
credential=credential, # type: ignore[arg-type]
201202
user_agent=AGENT_FRAMEWORK_USER_AGENT,
202203
)
203204
should_close_client = True
@@ -950,7 +951,7 @@ def __init__(
950951
conversation_id: str | None = None,
951952
project_endpoint: str | None = None,
952953
model_deployment_name: str | None = None,
953-
credential: AsyncTokenCredential | None = None,
954+
credential: AzureCredentialTypes | None = None,
954955
use_latest_version: bool | None = None,
955956
middleware: Sequence[ChatAndFunctionMiddlewareTypes] | None = None,
956957
function_invocation_configuration: FunctionInvocationConfiguration | None = None,
@@ -972,7 +973,8 @@ def __init__(
972973
Ignored when a project_client is passed.
973974
model_deployment_name: The model deployment name to use for agent creation.
974975
Can also be set via environment variable AZURE_AI_MODEL_DEPLOYMENT_NAME.
975-
credential: Azure async credential to use for authentication.
976+
credential: Azure credential for authentication. Accepts a TokenCredential
977+
or AsyncTokenCredential.
976978
use_latest_version: Boolean flag that indicates whether to use latest agent version
977979
if it exists in the service.
978980
middleware: Optional sequence of chat middlewares to include.

‎python/packages/azure-ai/agent_framework_azure_ai/_project_provider.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from agent_framework._mcp import MCPTool
1919
from agent_framework._settings import load_settings
2020
from agent_framework._tools import ToolTypes
21+
from agent_framework.azure._entra_id_authentication import AzureCredentialTypes
2122
from agent_framework.exceptions import ServiceInitializationError
2223
from azure.ai.projects.aio import AIProjectClient
2324
from azure.ai.projects.models import (
@@ -29,7 +30,6 @@
2930
from azure.ai.projects.models import (
3031
FunctionTool as AzureFunctionTool,
3132
)
32-
from azure.core.credentials_async import AsyncTokenCredential
3333

3434
from ._client import AzureAIClient, AzureAIProjectAgentOptions
3535
from ._shared import AzureAISettings, create_text_format_config, from_azure_ai_tools, to_azure_ai_tools
@@ -103,7 +103,7 @@ def __init__(
103103
*,
104104
project_endpoint: str | None = None,
105105
model: str | None = None,
106-
credential: AsyncTokenCredential | None = None,
106+
credential: AzureCredentialTypes | None = None,
107107
env_file_path: str | None = None,
108108
env_file_encoding: str | None = None,
109109
) -> None:
@@ -116,7 +116,8 @@ def __init__(
116116
Ignored when a project_client is passed.
117117
model: The default model deployment name to use for agent creation.
118118
Can also be set via environment variable AZURE_AI_MODEL_DEPLOYMENT_NAME.
119-
credential: Azure async credential to use for authentication.
119+
credential: Azure credential for authentication. Accepts a TokenCredential,
120+
AsyncTokenCredential, or a callable token provider.
120121
Required when project_client is not provided.
121122
env_file_path: Path to environment file for loading settings.
122123
env_file_encoding: Encoding of the environment file.
@@ -149,7 +150,7 @@ def __init__(
149150

150151
project_client = AIProjectClient(
151152
endpoint=resolved_endpoint,
152-
credential=credential,
153+
credential=credential, # type: ignore[arg-type]
153154
user_agent=AGENT_FRAMEWORK_USER_AGENT,
154155
)
155156
self._should_close_client = True

‎python/packages/core/agent_framework/azure/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@
3030
"AzureAISearchSettings": ("agent_framework_azure_ai_search", "agent-framework-azure-ai-search"),
3131
"AzureAISettings": ("agent_framework_azure_ai", "agent-framework-azure-ai"),
3232
"AzureAIAgentsProvider": ("agent_framework_azure_ai", "agent-framework-azure-ai"),
33+
"AzureCredentialTypes": ("agent_framework.azure._entra_id_authentication", "agent-framework-core"),
34+
"AzureTokenProvider": ("agent_framework.azure._entra_id_authentication", "agent-framework-core"),
3335
"AzureOpenAIAssistantsClient": ("agent_framework.azure._assistants_client", "agent-framework-core"),
3436
"AzureOpenAIAssistantsOptions": ("agent_framework.azure._assistants_client", "agent-framework-core"),
3537
"AzureOpenAIChatClient": ("agent_framework.azure._chat_client", "agent-framework-core"),
@@ -42,7 +44,6 @@
4244
"DurableAIAgentClient": ("agent_framework_durabletask", "agent-framework-durabletask"),
4345
"DurableAIAgentOrchestrationContext": ("agent_framework_durabletask", "agent-framework-durabletask"),
4446
"DurableAIAgentWorker": ("agent_framework_durabletask", "agent-framework-durabletask"),
45-
"get_entra_auth_token": ("agent_framework.azure._entra_id_authentication", "agent-framework-core"),
4647
}
4748

4849

‎python/packages/core/agent_framework/azure/__init__.pyi‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ from agent_framework_durabletask import (
2121

2222
from agent_framework.azure._assistants_client import AzureOpenAIAssistantsClient
2323
from agent_framework.azure._chat_client import AzureOpenAIChatClient
24-
from agent_framework.azure._entra_id_authentication import get_entra_auth_token
24+
from agent_framework.azure._entra_id_authentication import AzureCredentialTypes, AzureTokenProvider
2525
from agent_framework.azure._responses_client import AzureOpenAIResponsesClient
2626
from agent_framework.azure._shared import AzureOpenAISettings
2727

@@ -37,13 +37,14 @@ __all__ = [
3737
"AzureAISearchContextProvider",
3838
"AzureAISearchSettings",
3939
"AzureAISettings",
40+
"AzureCredentialTypes",
4041
"AzureOpenAIAssistantsClient",
4142
"AzureOpenAIChatClient",
4243
"AzureOpenAIResponsesClient",
4344
"AzureOpenAISettings",
45+
"AzureTokenProvider",
4446
"DurableAIAgent",
4547
"DurableAIAgentClient",
4648
"DurableAIAgentOrchestrationContext",
4749
"DurableAIAgentWorker",
48-
"get_entra_auth_token",
4950
]

‎python/packages/core/agent_framework/azure/_assistants_client.py‎

Lines changed: 18 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,16 @@
44

55
import sys
66
from collections.abc import Mapping
7-
from typing import TYPE_CHECKING, Any, ClassVar, Generic
7+
from typing import Any, ClassVar, Generic
88

9-
from openai.lib.azure import AsyncAzureADTokenProvider, AsyncAzureOpenAI
9+
from openai.lib.azure import AsyncAzureOpenAI
1010

1111
from .._settings import load_settings
1212
from ..exceptions import ServiceInitializationError
1313
from ..openai import OpenAIAssistantsClient
1414
from ..openai._assistants_client import OpenAIAssistantsOptions
15-
from ._entra_id_authentication import get_entra_auth_token
16-
from ._shared import DEFAULT_AZURE_TOKEN_ENDPOINT, AzureOpenAISettings, _apply_azure_defaults
17-
18-
if TYPE_CHECKING:
19-
from azure.core.credentials import TokenCredential
15+
from ._entra_id_authentication import AzureCredentialTypes, AzureTokenProvider, resolve_credential_to_token_provider
16+
from ._shared import AzureOpenAISettings, _apply_azure_defaults
2017

2118
if sys.version_info >= (3, 13):
2219
from typing import TypeVar # type: ignore # pragma: no cover
@@ -61,10 +58,8 @@ def __init__(
6158
endpoint: str | None = None,
6259
base_url: str | None = None,
6360
api_version: str | None = None,
64-
ad_token: str | None = None,
65-
ad_token_provider: AsyncAzureADTokenProvider | None = None,
6661
token_endpoint: str | None = None,
67-
credential: TokenCredential | None = None,
62+
credential: AzureCredentialTypes | AzureTokenProvider | None = None,
6863
default_headers: Mapping[str, str] | None = None,
6964
async_client: AsyncAzureOpenAI | None = None,
7065
env_file_path: str | None = None,
@@ -93,11 +88,12 @@ def __init__(
9388
api_version: The deployment API version. If provided will override the value
9489
in the env vars or .env file.
9590
Can also be set via environment variable AZURE_OPENAI_API_VERSION.
96-
ad_token: The Azure Active Directory token.
97-
ad_token_provider: The Azure Active Directory token provider.
9891
token_endpoint: The token endpoint to request an Azure token.
9992
Can also be set via environment variable AZURE_OPENAI_TOKEN_ENDPOINT.
100-
credential: The Azure credential to use for authentication.
93+
credential: Azure credential or token provider for authentication. Accepts a
94+
``TokenCredential``, ``AsyncTokenCredential``, or a callable that returns a
95+
bearer token string (sync or async), for example from
96+
``azure.identity.get_bearer_token_provider()``.
10197
default_headers: The default headers mapping of string keys to
10298
string values for HTTP requests.
10399
async_client: An existing client to use.
@@ -156,20 +152,15 @@ class MyOptions(AzureOpenAIAssistantsOptions, total=False):
156152
"or 'AZURE_OPENAI_CHAT_DEPLOYMENT_NAME' environment variable."
157153
)
158154

159-
# Handle authentication: try API key first, then AD token, then Entra ID
160-
if (
161-
not async_client
162-
and not azure_openai_settings["api_key"]
163-
and not ad_token
164-
and not ad_token_provider
165-
and azure_openai_settings["token_endpoint"]
166-
and credential
167-
):
168-
token_ep = azure_openai_settings["token_endpoint"] or DEFAULT_AZURE_TOKEN_ENDPOINT
169-
ad_token = get_entra_auth_token(credential, token_ep)
170-
171-
if not async_client and not azure_openai_settings["api_key"] and not ad_token and not ad_token_provider:
172-
raise ServiceInitializationError("The Azure OpenAI API key, ad_token, or ad_token_provider is required.")
155+
# Resolve credential to token provider
156+
ad_token_provider = None
157+
if not async_client and not azure_openai_settings["api_key"] and credential:
158+
ad_token_provider = resolve_credential_to_token_provider(
159+
credential, azure_openai_settings["token_endpoint"]
160+
)
161+
162+
if not async_client and not azure_openai_settings["api_key"] and not ad_token_provider:
163+
raise ServiceInitializationError("Please provide either api_key, credential, or a client.")
173164

174165
# Create Azure client if not provided
175166
if not async_client:
@@ -180,8 +171,6 @@ class MyOptions(AzureOpenAIAssistantsOptions, total=False):
180171

181172
if azure_openai_settings["api_key"]:
182173
client_params["api_key"] = azure_openai_settings["api_key"].get_secret_value()
183-
elif ad_token:
184-
client_params["azure_ad_token"] = ad_token
185174
elif ad_token_provider:
186175
client_params["azure_ad_token_provider"] = ad_token_provider
187176

0 commit comments

Comments
 (0)