Python: Create/Get Agent API for Azure V1 (#3192)

* Added provider implementation for Azure AI V1

* Small fixes

* Fixed OpenAPI example

* Fixed local MCP example

* Fixed hosted MCP example

* Fixed file search sample

* Small fixes

* Resolved comments

* Doc updates
This commit is contained in:
Dmytro Struk
2026-01-15 22:19:03 +00:00
committed by GitHub
parent 6e9420f614
commit 48d124efbe
32 changed files with 2119 additions and 640 deletions
@@ -2,9 +2,10 @@
import importlib.metadata
from ._agent_provider import AzureAIAgentsProvider
from ._chat_client import AzureAIAgentClient, AzureAIAgentOptions
from ._client import AzureAIClient
from ._provider import AzureAIProjectAgentProvider
from ._project_provider import AzureAIProjectAgentProvider
from ._shared import AzureAISettings
try:
@@ -15,6 +16,7 @@ except importlib.metadata.PackageNotFoundError:
__all__ = [
"AzureAIAgentClient",
"AzureAIAgentOptions",
"AzureAIAgentsProvider",
"AzureAIClient",
"AzureAIProjectAgentProvider",
"AzureAISettings",
@@ -0,0 +1,519 @@
# Copyright (c) Microsoft. All rights reserved.
import sys
from collections.abc import Callable, MutableMapping, Sequence
from typing import TYPE_CHECKING, Any, Generic, TypedDict, cast
from agent_framework import (
AGENT_FRAMEWORK_USER_AGENT,
AIFunction,
ChatAgent,
ContextProvider,
Middleware,
ToolProtocol,
normalize_tools,
)
from agent_framework._mcp import MCPTool
from agent_framework.exceptions import ServiceInitializationError
from azure.ai.agents.aio import AgentsClient
from azure.ai.agents.models import Agent, ResponseFormatJsonSchema, ResponseFormatJsonSchemaType
from azure.core.credentials_async import AsyncTokenCredential
from pydantic import BaseModel, ValidationError
from ._chat_client import AzureAIAgentClient
from ._shared import AzureAISettings, from_azure_ai_agent_tools, to_azure_ai_agent_tools
if TYPE_CHECKING:
from ._chat_client import AzureAIAgentOptions
if sys.version_info >= (3, 13):
from typing import Self, TypeVar # pragma: no cover
else:
from typing_extensions import Self, TypeVar # pragma: no cover
# Type variable for options - allows typed ChatAgent[TOptions] returns
# Default matches AzureAIAgentClient's default options type
TOptions_co = TypeVar(
"TOptions_co",
bound=TypedDict, # type: ignore[valid-type]
default="AzureAIAgentOptions",
covariant=True,
)
class AzureAIAgentsProvider(Generic[TOptions_co]):
"""Provider for Azure AI Agent Service V1 (Persistent Agents API).
This provider enables creating, retrieving, and wrapping Azure AI agents as ChatAgent
instances. It manages the underlying AgentsClient lifecycle and provides a high-level
interface for agent operations.
The provider can be initialized with either:
- An existing AgentsClient instance
- Azure credentials and endpoint for automatic client creation
Examples:
Using credentials (auto-creates client):
.. code-block:: python
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyAgent",
instructions="You are a helpful assistant.",
)
result = await agent.run("Hello!")
Using existing AgentsClient:
.. code-block:: python
from agent_framework.azure import AzureAIAgentsProvider
from azure.ai.agents.aio import AgentsClient
async with AgentsClient(endpoint=endpoint, credential=credential) as client:
provider = AzureAIAgentsProvider(agents_client=client)
agent = await provider.create_agent(name="MyAgent", instructions="...")
"""
def __init__(
self,
agents_client: AgentsClient | None = None,
*,
project_endpoint: str | None = None,
credential: AsyncTokenCredential | None = None,
env_file_path: str | None = None,
env_file_encoding: str | None = None,
) -> None:
"""Initialize the Azure AI Agents Provider.
Args:
agents_client: An existing AgentsClient to use. If provided, the provider
will not manage its lifecycle.
Keyword Args:
project_endpoint: The Azure AI Project endpoint URL.
Can also be set via AZURE_AI_PROJECT_ENDPOINT environment variable.
credential: Azure async credential for authentication.
Required if agents_client is not provided.
env_file_path: Path to .env file for loading settings.
env_file_encoding: Encoding of the .env file.
Raises:
ServiceInitializationError: If required parameters are missing or invalid.
"""
try:
self._settings = AzureAISettings(
project_endpoint=project_endpoint,
env_file_path=env_file_path,
env_file_encoding=env_file_encoding,
)
except ValidationError as ex:
raise ServiceInitializationError("Failed to create Azure AI settings.", ex) from ex
self._should_close_client = False
if agents_client is not None:
self._agents_client = agents_client
else:
if not self._settings.project_endpoint:
raise ServiceInitializationError(
"Azure AI project endpoint is required. Provide 'project_endpoint' parameter "
"or set 'AZURE_AI_PROJECT_ENDPOINT' environment variable."
)
if not credential:
raise ServiceInitializationError("Azure credential is required when agents_client is not provided.")
self._agents_client = AgentsClient(
endpoint=self._settings.project_endpoint,
credential=credential,
user_agent=AGENT_FRAMEWORK_USER_AGENT,
)
self._should_close_client = True
async def __aenter__(self) -> "Self":
"""Async context manager entry."""
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: Any,
) -> None:
"""Async context manager exit."""
await self.close()
async def close(self) -> None:
"""Close the provider and release resources.
Only closes the AgentsClient if it was created by this provider.
"""
if self._should_close_client:
await self._agents_client.close()
async def create_agent(
self,
name: str,
*,
model: str | None = None,
instructions: str | None = None,
description: str | None = None,
tools: ToolProtocol
| Callable[..., Any]
| MutableMapping[str, Any]
| Sequence[ToolProtocol | Callable[..., Any] | MutableMapping[str, Any]]
| None = None,
default_options: TOptions_co | None = None,
middleware: Sequence[Middleware] | None = None,
context_provider: ContextProvider | None = None,
) -> "ChatAgent[TOptions_co]":
"""Create a new agent on the Azure AI service and return a ChatAgent.
This method creates a persistent agent on the Azure AI service with the specified
configuration and returns a local ChatAgent instance for interaction.
Args:
name: The name for the agent.
Keyword Args:
model: The model deployment name to use. Falls back to
AZURE_AI_MODEL_DEPLOYMENT_NAME environment variable if not provided.
instructions: Instructions for the agent's behavior.
description: A description of the agent's purpose.
tools: Tools to make available to the agent.
default_options: A TypedDict containing default chat options for the agent.
These options are applied to every run unless overridden.
middleware: List of middleware to intercept agent and function invocations.
context_provider: Context provider to include during agent invocation.
Returns:
ChatAgent: A ChatAgent instance configured with the created agent.
Raises:
ServiceInitializationError: If model deployment name is not available.
Examples:
.. code-block:: python
agent = await provider.create_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather,
)
"""
resolved_model = model or self._settings.model_deployment_name
if not resolved_model:
raise ServiceInitializationError(
"Model deployment name is required. Provide 'model' parameter "
"or set 'AZURE_AI_MODEL_DEPLOYMENT_NAME' environment variable."
)
# Extract response_format from default_options if present
opts = dict(default_options) if default_options else {}
response_format = opts.get("response_format")
args: dict[str, Any] = {
"model": resolved_model,
"name": name,
}
if description:
args["description"] = description
if instructions:
args["instructions"] = instructions
# Handle response format
if response_format and isinstance(response_format, type) and issubclass(response_format, BaseModel):
args["response_format"] = self._create_response_format_config(response_format)
# Normalize and convert tools
# Local MCP tools (MCPTool) are handled by ChatAgent at runtime, not stored on the Azure agent
normalized_tools = normalize_tools(tools)
if normalized_tools:
# Only convert non-MCP tools to Azure AI format
non_mcp_tools = [t for t in normalized_tools if not isinstance(t, MCPTool)]
if non_mcp_tools:
# Pass run_options to capture tool_resources (e.g., for file search vector stores)
run_options: dict[str, Any] = {}
args["tools"] = to_azure_ai_agent_tools(non_mcp_tools, run_options)
if "tool_resources" in run_options:
args["tool_resources"] = run_options["tool_resources"]
# Create the agent on the service
created_agent = await self._agents_client.create_agent(**args)
# Create ChatAgent wrapper
return self._to_chat_agent_from_agent(
created_agent,
normalized_tools,
default_options=default_options,
middleware=middleware,
context_provider=context_provider,
)
async def get_agent(
self,
id: str,
*,
tools: ToolProtocol
| Callable[..., Any]
| MutableMapping[str, Any]
| Sequence[ToolProtocol | Callable[..., Any] | MutableMapping[str, Any]]
| None = None,
default_options: TOptions_co | None = None,
middleware: Sequence[Middleware] | None = None,
context_provider: ContextProvider | None = None,
) -> "ChatAgent[TOptions_co]":
"""Retrieve an existing agent from the service and return a ChatAgent.
This method fetches an agent by ID from the Azure AI service
and returns a local ChatAgent instance for interaction.
Args:
id: The ID of the agent to retrieve from the service.
Keyword Args:
tools: Tools to make available to the agent. Required if the agent
has function tools that need implementations.
default_options: A TypedDict containing default chat options for the agent.
These options are applied to every run unless overridden.
middleware: List of middleware to intercept agent and function invocations.
context_provider: Context provider to include during agent invocation.
Returns:
ChatAgent: A ChatAgent instance configured with the retrieved agent.
Raises:
ServiceInitializationError: If required function tools are not provided.
Examples:
.. code-block:: python
agent = await provider.get_agent("agent-123")
# With function tools
agent = await provider.get_agent("agent-123", tools=my_function)
"""
agent = await self._agents_client.get_agent(id)
# Validate function tools
normalized_tools = normalize_tools(tools)
self._validate_function_tools(agent.tools, normalized_tools)
return self._to_chat_agent_from_agent(
agent,
normalized_tools,
default_options=default_options,
middleware=middleware,
context_provider=context_provider,
)
def as_agent(
self,
agent: Agent,
tools: ToolProtocol
| Callable[..., Any]
| MutableMapping[str, Any]
| Sequence[ToolProtocol | Callable[..., Any] | MutableMapping[str, Any]]
| None = None,
default_options: TOptions_co | None = None,
middleware: Sequence[Middleware] | None = None,
context_provider: ContextProvider | None = None,
) -> "ChatAgent[TOptions_co]":
"""Wrap an existing Agent SDK object as a ChatAgent without making HTTP calls.
Use this method when you already have an Agent object from a previous
SDK operation and want to use it with the Agent Framework.
Args:
agent: The Agent object to wrap.
tools: Tools to make available to the agent. Required if the agent
has function tools that need implementations.
default_options: A TypedDict containing default chat options for the agent.
These options are applied to every run unless overridden.
middleware: List of middleware to intercept agent and function invocations.
context_provider: Context provider to include during agent invocation.
Returns:
ChatAgent: A ChatAgent instance configured with the agent.
Raises:
ServiceInitializationError: If required function tools are not provided.
Examples:
.. code-block:: python
# Create agent directly with SDK
sdk_agent = await agents_client.create_agent(
model="gpt-4",
name="MyAgent",
instructions="...",
)
# Wrap as ChatAgent
chat_agent = provider.as_agent(sdk_agent)
"""
# Validate function tools
normalized_tools = normalize_tools(tools)
self._validate_function_tools(agent.tools, normalized_tools)
return self._to_chat_agent_from_agent(
agent,
normalized_tools,
default_options=default_options,
middleware=middleware,
context_provider=context_provider,
)
def _to_chat_agent_from_agent(
self,
agent: Agent,
provided_tools: Sequence[ToolProtocol | MutableMapping[str, Any]] | None = None,
default_options: TOptions_co | None = None,
middleware: Sequence[Middleware] | None = None,
context_provider: ContextProvider | None = None,
) -> "ChatAgent[TOptions_co]":
"""Create a ChatAgent from an Agent SDK object.
Args:
agent: The Agent SDK object.
provided_tools: User-provided tools (including function implementations).
default_options: A TypedDict containing default chat options for the agent.
These options are applied to every run unless overridden.
middleware: List of middleware to intercept agent and function invocations.
context_provider: Context provider to include during agent invocation.
"""
# Create the underlying client
client = AzureAIAgentClient(
agents_client=self._agents_client,
agent_id=agent.id,
agent_name=agent.name,
agent_description=agent.description,
should_cleanup_agent=False, # Provider manages agent lifecycle
)
# Merge tools: convert agent's hosted tools + user-provided function tools
merged_tools = self._merge_tools(agent.tools, provided_tools)
return ChatAgent( # type: ignore[return-value]
chat_client=client,
id=agent.id,
name=agent.name,
description=agent.description,
instructions=agent.instructions,
model_id=agent.model,
tools=merged_tools,
default_options=default_options, # type: ignore[arg-type]
middleware=middleware,
context_provider=context_provider,
)
def _merge_tools(
self,
agent_tools: Sequence[Any] | None,
provided_tools: Sequence[ToolProtocol | MutableMapping[str, Any]] | None,
) -> list[ToolProtocol | dict[str, Any]]:
"""Merge hosted tools from agent with user-provided function tools.
Args:
agent_tools: Tools from the agent definition (Azure AI format).
provided_tools: User-provided tools (Agent Framework format).
Returns:
Combined list of tools for the ChatAgent.
"""
merged: list[ToolProtocol | dict[str, Any]] = []
# Convert hosted tools from agent definition
hosted_tools = from_azure_ai_agent_tools(agent_tools)
for hosted_tool in hosted_tools:
# Skip function tool dicts - they don't have implementations
# Skip OpenAPI tool dicts - they're defined on the agent, not needed at runtime
if isinstance(hosted_tool, dict):
tool_type = hosted_tool.get("type")
if tool_type == "function" or tool_type == "openapi":
continue
merged.append(hosted_tool)
# Add user-provided function tools and MCP tools
if provided_tools:
for provided_tool in provided_tools:
# AIFunction - has implementation for function calling
# MCPTool - ChatAgent handles MCP connection and tool discovery at runtime
if isinstance(provided_tool, (AIFunction, MCPTool)):
merged.append(provided_tool) # type: ignore[reportUnknownArgumentType]
return merged
def _validate_function_tools(
self,
agent_tools: Sequence[Any] | None,
provided_tools: Sequence[ToolProtocol | MutableMapping[str, Any]] | None,
) -> None:
"""Validate that required function tools are provided.
Raises:
ServiceInitializationError: If agent has function tools but user
didn't provide implementations.
"""
if not agent_tools:
return
# Get function tool names from agent definition
function_tool_names: set[str] = set()
for tool in agent_tools:
if isinstance(tool, dict):
tool_dict = cast(dict[str, Any], tool)
if tool_dict.get("type") == "function":
func_def = cast(dict[str, Any], tool_dict.get("function", {}))
name = func_def.get("name")
if isinstance(name, str):
function_tool_names.add(name)
elif hasattr(tool, "type") and tool.type == "function":
func_attr = getattr(tool, "function", None)
if func_attr and hasattr(func_attr, "name"):
function_tool_names.add(str(func_attr.name))
if not function_tool_names:
return
# Get provided function names
provided_names: set[str] = set()
if provided_tools:
for tool in provided_tools:
if isinstance(tool, AIFunction):
provided_names.add(tool.name)
# Check for missing implementations
missing = function_tool_names - provided_names
if missing:
raise ServiceInitializationError(
f"Agent has function tools that require implementations: {missing}. "
"Provide these functions via the 'tools' parameter."
)
def _create_response_format_config(
self,
response_format: type[BaseModel],
) -> ResponseFormatJsonSchemaType:
"""Create response format configuration for Azure AI.
Args:
response_format: Pydantic model for structured output.
Returns:
Azure AI response format configuration.
"""
return ResponseFormatJsonSchemaType(
json_schema=ResponseFormatJsonSchema(
name=response_format.__name__,
schema=response_format.model_json_schema(),
)
)
@@ -2,7 +2,6 @@
import ast
import json
import os
import re
import sys
from collections.abc import AsyncIterable, Mapping, MutableMapping, MutableSequence, Sequence
@@ -10,7 +9,6 @@ from typing import Any, ClassVar, Generic, TypedDict
from agent_framework import (
AGENT_FRAMEWORK_USER_AGENT,
AIFunction,
BaseChatClient,
ChatMessage,
ChatOptions,
@@ -23,12 +21,8 @@ from agent_framework import (
FunctionApprovalResponseContent,
FunctionCallContent,
FunctionResultContent,
HostedCodeInterpreterTool,
HostedFileContent,
HostedFileSearchTool,
HostedMCPTool,
HostedVectorStoreContent,
HostedWebSearchTool,
Role,
TextContent,
TextSpanRegion,
@@ -52,14 +46,9 @@ from azure.ai.agents.models import (
AgentStreamEvent,
AsyncAgentEventHandler,
AsyncAgentRunStream,
BingCustomSearchTool,
BingGroundingTool,
CodeInterpreterToolDefinition,
FileSearchTool,
FunctionName,
FunctionToolDefinition,
ListSortOrder,
McpTool,
MessageDeltaChunk,
MessageDeltaTextContent,
MessageDeltaTextFileCitationAnnotation,
@@ -91,7 +80,7 @@ from azure.ai.agents.models import (
from azure.core.credentials_async import AsyncTokenCredential
from pydantic import BaseModel, ValidationError
from ._shared import AzureAISettings
from ._shared import AzureAISettings, to_azure_ai_agent_tools
if sys.version_info >= (3, 13):
from typing import TypeVar # type: ignore # pragma: no cover
@@ -1007,7 +996,7 @@ class AzureAIAgentClient(BaseChatClient[TAzureAIAgentOptions], Generic[TAzureAIA
tool_choice = options.get("tool_choice")
tools = options.get("tools")
if tool_choice is not None and tool_choice != "none" and tools:
tool_definitions.extend(await self._prepare_tools_for_azure_ai(tools, run_options))
tool_definitions.extend(to_azure_ai_agent_tools(tools, run_options))
# Handle MCP tool resources
mcp_resources = self._prepare_mcp_resources(tools)
@@ -1106,82 +1095,6 @@ class AzureAIAgentClient(BaseChatClient[TAzureAIAgentOptions], Generic[TAzureAIA
return additional_messages, instructions, required_action_results
async def _prepare_tools_for_azure_ai(
self, tools: Sequence["ToolProtocol | MutableMapping[str, Any]"], run_options: dict[str, Any] | None = None
) -> list[ToolDefinition | dict[str, Any]]:
"""Prepare tool definitions for the Azure AI Agents API."""
tool_definitions: list[ToolDefinition | dict[str, Any]] = []
for tool in tools:
match tool:
case AIFunction():
tool_definitions.append(tool.to_json_schema_spec()) # type: ignore[reportUnknownArgumentType]
case HostedWebSearchTool():
additional_props = tool.additional_properties or {}
config_args: dict[str, Any] = {}
if count := additional_props.get("count"):
config_args["count"] = count
if freshness := additional_props.get("freshness"):
config_args["freshness"] = freshness
if market := additional_props.get("market"):
config_args["market"] = market
if set_lang := additional_props.get("set_lang"):
config_args["set_lang"] = set_lang
# Bing Grounding
connection_id = additional_props.get("connection_id") or os.getenv("BING_CONNECTION_ID")
# Custom Bing Search
custom_connection_id = additional_props.get("custom_connection_id") or os.getenv(
"BING_CUSTOM_CONNECTION_ID"
)
custom_instance_name = additional_props.get("custom_instance_name") or os.getenv(
"BING_CUSTOM_INSTANCE_NAME"
)
bing_search: BingGroundingTool | BingCustomSearchTool | None = None
if (connection_id) and not custom_connection_id and not custom_instance_name:
if connection_id:
conn_id = connection_id
else:
raise ServiceInitializationError("Parameter connection_id is not provided.")
bing_search = BingGroundingTool(connection_id=conn_id, **config_args)
if custom_connection_id and custom_instance_name:
bing_search = BingCustomSearchTool(
connection_id=custom_connection_id,
instance_name=custom_instance_name,
**config_args,
)
if not bing_search:
raise ServiceInitializationError(
"Bing search tool requires either 'connection_id' for Bing Grounding "
"or both 'custom_connection_id' and 'custom_instance_name' for Custom Bing Search. "
"These can be provided via additional_properties or environment variables: "
"'BING_CONNECTION_ID', 'BING_CUSTOM_CONNECTION_ID', "
"'BING_CUSTOM_INSTANCE_NAME'"
)
tool_definitions.extend(bing_search.definitions)
case HostedCodeInterpreterTool():
tool_definitions.append(CodeInterpreterToolDefinition())
case HostedMCPTool():
mcp_tool = McpTool(
server_label=tool.name.replace(" ", "_"),
server_url=str(tool.url),
allowed_tools=list(tool.allowed_tools) if tool.allowed_tools else [],
)
tool_definitions.extend(mcp_tool.definitions)
case HostedFileSearchTool():
vector_stores = [inp for inp in tool.inputs or [] if isinstance(inp, HostedVectorStoreContent)]
if vector_stores:
file_search = FileSearchTool(vector_store_ids=[vs.vector_store_id for vs in vector_stores])
tool_definitions.extend(file_search.definitions)
# Set tool_resources for file search to work properly with Azure AI
if run_options is not None and "tool_resources" not in run_options:
run_options["tool_resources"] = file_search.resources
case ToolDefinition():
tool_definitions.append(tool)
case dict():
tool_definitions.append(tool)
case _:
raise ServiceInitializationError(f"Unsupported tool type: {type(tool)}")
return tool_definitions
def _prepare_tool_outputs_for_azure_ai(
self,
required_action_results: list[FunctionResultContent | FunctionApprovalResponseContent] | None,
@@ -24,7 +24,7 @@ from azure.ai.projects.models import (
PromptAgentDefinitionText,
)
from azure.core.credentials_async import AsyncTokenCredential
from pydantic import BaseModel, ValidationError
from pydantic import ValidationError
from ._client import AzureAIClient
from ._shared import AzureAISettings, create_text_format_config, from_azure_ai_tools, to_azure_ai_tools
@@ -156,7 +156,6 @@ class AzureAIProjectAgentProvider(Generic[TOptions_co]):
model: str | None = None,
instructions: str | None = None,
description: str | None = None,
response_format: type[BaseModel] | MutableMapping[str, Any] | None = None,
tools: ToolProtocol
| Callable[..., Any]
| MutableMapping[str, Any]
@@ -174,8 +173,6 @@ class AzureAIProjectAgentProvider(Generic[TOptions_co]):
environment variable if not provided.
instructions: Instructions for the agent.
description: A description of the agent.
response_format: The format of the response. Can be a Pydantic model for structured
output, or a dict with JSON schema configuration.
tools: Tools to make available to the agent.
default_options: A TypedDict containing default chat options for the agent.
These options are applied to every run unless overridden.
@@ -196,12 +193,18 @@ class AzureAIProjectAgentProvider(Generic[TOptions_co]):
"or set 'AZURE_AI_MODEL_DEPLOYMENT_NAME' environment variable."
)
# Extract response_format from default_options if present
opts = dict(default_options) if default_options else {}
response_format = opts.get("response_format")
args: dict[str, Any] = {"model": resolved_model}
if instructions:
args["instructions"] = instructions
if response_format:
args["text"] = PromptAgentDefinitionText(format=create_text_format_config(response_format))
if response_format and isinstance(response_format, (type, dict)):
args["text"] = PromptAgentDefinitionText(
format=create_text_format_config(response_format) # type: ignore[arg-type]
)
# Normalize tools once and reuse for both Azure AI API and ChatAgent
normalized_tools = normalize_tools(tools)
@@ -217,7 +220,6 @@ class AzureAIProjectAgentProvider(Generic[TOptions_co]):
return self._to_chat_agent_from_details(
created_agent,
normalized_tools,
response_format=response_format,
default_options=default_options,
middleware=middleware,
context_provider=context_provider,
@@ -333,7 +335,6 @@ class AzureAIProjectAgentProvider(Generic[TOptions_co]):
self,
details: AgentVersionDetails,
provided_tools: Sequence[ToolProtocol | MutableMapping[str, Any]] | None = None,
response_format: type[BaseModel] | MutableMapping[str, Any] | None = None,
default_options: TOptions_co | None = None,
middleware: Sequence[Middleware] | None = None,
context_provider: ContextProvider | None = None,
@@ -344,8 +345,6 @@ class AzureAIProjectAgentProvider(Generic[TOptions_co]):
details: The AgentVersionDetails containing the agent definition.
provided_tools: User-provided tools (including function implementations).
These are merged with hosted tools from the definition.
response_format: The response format. Can be a Pydantic model for structured
output parsing, or a dict with JSON schema for service-side formatting.
default_options: A TypedDict containing default chat options for the agent.
These options are applied to every run unless overridden.
middleware: List of middleware to intercept agent and function invocations.
@@ -374,7 +373,6 @@ class AzureAIProjectAgentProvider(Generic[TOptions_co]):
instructions=details.definition.instructions,
model_id=details.definition.model,
tools=merged_tools,
response_format=response_format,
default_options=default_options, # type: ignore[arg-type]
middleware=middleware,
context_provider=context_provider,
@@ -1,5 +1,6 @@
# Copyright (c) Microsoft. All rights reserved.
import os
from collections.abc import Mapping, MutableMapping, Sequence
from typing import Any, ClassVar, Literal, cast
@@ -16,12 +17,19 @@ from agent_framework import (
get_logger,
)
from agent_framework._pydantic import AFBaseSettings
from agent_framework.exceptions import ServiceInvalidRequestError
from agent_framework.exceptions import ServiceInitializationError, ServiceInvalidRequestError
from azure.ai.agents.models import (
BingCustomSearchTool,
BingGroundingTool,
CodeInterpreterToolDefinition,
McpTool,
ToolDefinition,
)
from azure.ai.agents.models import FileSearchTool as AgentsFileSearchTool
from azure.ai.projects.models import (
ApproximateLocation,
CodeInterpreterTool,
CodeInterpreterToolAuto,
FileSearchTool,
FunctionTool,
MCPTool,
ResponseTextFormatConfigurationJsonObject,
@@ -30,6 +38,9 @@ from azure.ai.projects.models import (
Tool,
WebSearchPreviewTool,
)
from azure.ai.projects.models import (
FileSearchTool as ProjectsFileSearchTool,
)
from pydantic import BaseModel
logger = get_logger("agent_framework.azure")
@@ -76,6 +87,207 @@ class AzureAISettings(AFBaseSettings):
model_deployment_name: str | None = None
def to_azure_ai_agent_tools(
tools: Sequence[ToolProtocol | MutableMapping[str, Any]] | None,
run_options: dict[str, Any] | None = None,
) -> list[ToolDefinition | dict[str, Any]]:
"""Convert Agent Framework tools to Azure AI V1 SDK tool definitions.
Args:
tools: Sequence of Agent Framework tools to convert.
run_options: Optional dict with run options.
Returns:
List of Azure AI V1 SDK tool definitions.
Raises:
ServiceInitializationError: If tool configuration is invalid.
"""
if not tools:
return []
tool_definitions: list[ToolDefinition | dict[str, Any]] = []
for tool in tools:
match tool:
case AIFunction():
tool_definitions.append(tool.to_json_schema_spec()) # type: ignore[reportUnknownArgumentType]
case HostedWebSearchTool():
additional_props = tool.additional_properties or {}
config_args: dict[str, Any] = {}
if count := additional_props.get("count"):
config_args["count"] = count
if freshness := additional_props.get("freshness"):
config_args["freshness"] = freshness
if market := additional_props.get("market"):
config_args["market"] = market
if set_lang := additional_props.get("set_lang"):
config_args["set_lang"] = set_lang
# Bing Grounding
connection_id = additional_props.get("connection_id") or os.getenv("BING_CONNECTION_ID")
# Custom Bing Search
custom_connection_id = additional_props.get("custom_connection_id") or os.getenv(
"BING_CUSTOM_CONNECTION_ID"
)
custom_instance_name = additional_props.get("custom_instance_name") or os.getenv(
"BING_CUSTOM_INSTANCE_NAME"
)
bing_search: BingGroundingTool | BingCustomSearchTool | None = None
if connection_id and not custom_connection_id and not custom_instance_name:
bing_search = BingGroundingTool(connection_id=connection_id, **config_args)
if custom_connection_id and custom_instance_name:
bing_search = BingCustomSearchTool(
connection_id=custom_connection_id,
instance_name=custom_instance_name,
**config_args,
)
if not bing_search:
raise ServiceInitializationError(
"Bing search tool requires either 'connection_id' for Bing Grounding "
"or both 'custom_connection_id' and 'custom_instance_name' for Custom Bing Search. "
"These can be provided via additional_properties or environment variables: "
"'BING_CONNECTION_ID', 'BING_CUSTOM_CONNECTION_ID', 'BING_CUSTOM_INSTANCE_NAME'"
)
tool_definitions.extend(bing_search.definitions)
case HostedCodeInterpreterTool():
tool_definitions.append(CodeInterpreterToolDefinition())
case HostedMCPTool():
mcp_tool = McpTool(
server_label=tool.name.replace(" ", "_"),
server_url=str(tool.url),
allowed_tools=list(tool.allowed_tools) if tool.allowed_tools else [],
)
tool_definitions.extend(mcp_tool.definitions)
case HostedFileSearchTool():
vector_stores = [inp for inp in tool.inputs or [] if isinstance(inp, HostedVectorStoreContent)]
if vector_stores:
file_search = AgentsFileSearchTool(vector_store_ids=[vs.vector_store_id for vs in vector_stores])
tool_definitions.extend(file_search.definitions)
# Set tool_resources for file search to work properly with Azure AI
if run_options is not None and "tool_resources" not in run_options:
run_options["tool_resources"] = file_search.resources
case ToolDefinition():
tool_definitions.append(tool)
case dict():
tool_definitions.append(tool)
case _:
raise ServiceInitializationError(f"Unsupported tool type: {type(tool)}")
return tool_definitions
def from_azure_ai_agent_tools(
tools: Sequence[ToolDefinition | dict[str, Any]] | None,
) -> list[ToolProtocol | dict[str, Any]]:
"""Convert Azure AI V1 SDK tool definitions to Agent Framework tools.
Args:
tools: Sequence of Azure AI V1 SDK tool definitions.
Returns:
List of Agent Framework tools.
"""
if not tools:
return []
result: list[ToolProtocol | dict[str, Any]] = []
for tool in tools:
# Handle SDK objects
if isinstance(tool, CodeInterpreterToolDefinition):
result.append(HostedCodeInterpreterTool())
elif isinstance(tool, dict):
# Handle dict format
converted = _convert_dict_tool(tool)
if converted is not None:
result.append(converted)
elif hasattr(tool, "type"):
# Handle other SDK objects by type
converted = _convert_sdk_tool(tool)
if converted is not None:
result.append(converted)
return result
def _convert_dict_tool(tool: dict[str, Any]) -> ToolProtocol | dict[str, Any] | None:
"""Convert a dict-format Azure AI tool to Agent Framework tool."""
tool_type = tool.get("type")
if tool_type == "code_interpreter":
return HostedCodeInterpreterTool()
if tool_type == "file_search":
file_search_config = tool.get("file_search", {})
vector_store_ids = file_search_config.get("vector_store_ids", [])
inputs = [HostedVectorStoreContent(vector_store_id=vs_id) for vs_id in vector_store_ids]
return HostedFileSearchTool(inputs=inputs if inputs else None) # type: ignore
if tool_type == "bing_grounding":
bing_config = tool.get("bing_grounding", {})
connection_id = bing_config.get("connection_id")
return HostedWebSearchTool(additional_properties={"connection_id": connection_id} if connection_id else None)
if tool_type == "bing_custom_search":
bing_config = tool.get("bing_custom_search", {})
return HostedWebSearchTool(
additional_properties={
"custom_connection_id": bing_config.get("connection_id"),
"custom_instance_name": bing_config.get("instance_name"),
}
)
if tool_type == "mcp":
# Hosted MCP tools are defined on the Azure agent, no local handling needed
# Azure may not return full server_url, so skip conversion
return None
if tool_type == "function":
# Function tools are returned as dicts - users must provide implementations
return tool
# Unknown tool type - pass through
return tool
def _convert_sdk_tool(tool: ToolDefinition) -> ToolProtocol | dict[str, Any] | None:
"""Convert an SDK-object Azure AI tool to Agent Framework tool."""
tool_type = getattr(tool, "type", None)
if tool_type == "code_interpreter":
return HostedCodeInterpreterTool()
if tool_type == "file_search":
file_search_config = getattr(tool, "file_search", None)
vector_store_ids = getattr(file_search_config, "vector_store_ids", []) if file_search_config else []
inputs = [HostedVectorStoreContent(vector_store_id=vs_id) for vs_id in vector_store_ids]
return HostedFileSearchTool(inputs=inputs if inputs else None) # type: ignore
if tool_type == "bing_grounding":
bing_config = getattr(tool, "bing_grounding", None)
connection_id = getattr(bing_config, "connection_id", None) if bing_config else None
return HostedWebSearchTool(additional_properties={"connection_id": connection_id} if connection_id else None)
if tool_type == "bing_custom_search":
bing_config = getattr(tool, "bing_custom_search", None)
return HostedWebSearchTool(
additional_properties={
"custom_connection_id": getattr(bing_config, "connection_id", None) if bing_config else None,
"custom_instance_name": getattr(bing_config, "instance_name", None) if bing_config else None,
}
)
if tool_type == "mcp":
# Hosted MCP tools are defined on the Azure agent, no local handling needed
# Azure may not return full server_url, so skip conversion
return None
if tool_type == "function":
# Function tools from SDK don't have implementations - skip
return None
# Unknown tool type - convert to dict if possible
if hasattr(tool, "as_dict"):
return tool.as_dict() # type: ignore[union-attr]
return {"type": tool_type} if tool_type else {}
def from_azure_ai_tools(tools: Sequence[Tool | dict[str, Any]] | None) -> list[ToolProtocol | dict[str, Any]]:
"""Parses and converts a sequence of Azure AI tools into Agent Framework compatible tools.
@@ -130,7 +342,7 @@ def from_azure_ai_tools(tools: Sequence[Tool | dict[str, Any]] | None) -> list[T
agent_tools.append(HostedCodeInterpreterTool(inputs=ci_inputs if ci_inputs else None)) # type: ignore
elif tool_type == "file_search":
fs_tool = cast(FileSearchTool, tool_dict)
fs_tool = cast(ProjectsFileSearchTool, tool_dict)
fs_inputs: list[Contents] = []
if "vector_store_ids" in fs_tool:
for vs_id in fs_tool["vector_store_ids"]:
@@ -210,7 +422,7 @@ def to_azure_ai_tools(
raise ValueError(
"HostedFileSearchTool requires inputs to be of type `HostedVectorStoreContent`."
)
fs_tool: FileSearchTool = FileSearchTool(vector_store_ids=vector_store_ids)
fs_tool: ProjectsFileSearchTool = ProjectsFileSearchTool(vector_store_ids=vector_store_ids)
if tool.max_results:
fs_tool["max_num_results"] = tool.max_results
azure_tools.append(fs_tool)