Build Azure AI Foundry agents using the Microsoft Agent Framework Python SDK (agent-framework-azure-ai). Use when creating persistent agents with AzureAIAgentsProvider, using hosted tools (code interpreter, file search, web search), integrating MCP servers, managing conversation threads, or implementing streaming responses. Covers function tools, structured outputs, and multi-tool agents.
Add this skill
npx mdskills install sickn33/agent-framework-azure-ai-pyComprehensive Azure AI agent SDK guide with clear examples, structured outputs, and multi-tool integration
1---2name: agent-framework-azure-ai-py3description: Build Azure AI Foundry agents using the Microsoft Agent Framework Python SDK (agent-framework-azure-ai). Use when creating persistent agents with AzureAIAgentsProvider, using hosted tools (code interpreter, file search, web search), integrating MCP servers, managing conversation threads, or implementing streaming responses. Covers function tools, structured outputs, and multi-tool agents.4package: agent-framework-azure-ai5---67# Agent Framework Azure Hosted Agents89Build persistent agents on Azure AI Foundry using the Microsoft Agent Framework Python SDK.1011## Architecture1213```14User Query → AzureAIAgentsProvider → Azure AI Agent Service (Persistent)15 ↓16 Agent.run() / Agent.run_stream()17 ↓18 Tools: Functions | Hosted (Code/Search/Web) | MCP19 ↓20 AgentThread (conversation persistence)21```2223## Installation2425```bash26# Full framework (recommended)27pip install agent-framework --pre2829# Or Azure-specific package only30pip install agent-framework-azure-ai --pre31```3233## Environment Variables3435```bash36export AZURE_AI_PROJECT_ENDPOINT="https://<project>.services.ai.azure.com/api/projects/<project-id>"37export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"38export BING_CONNECTION_ID="your-bing-connection-id" # For web search39```4041## Authentication4243```python44from azure.identity.aio import AzureCliCredential, DefaultAzureCredential4546# Development47credential = AzureCliCredential()4849# Production50credential = DefaultAzureCredential()51```5253## Core Workflow5455### Basic Agent5657```python58import asyncio59from agent_framework.azure import AzureAIAgentsProvider60from azure.identity.aio import AzureCliCredential6162async def main():63 async with (64 AzureCliCredential() as credential,65 AzureAIAgentsProvider(credential=credential) as provider,66 ):67 agent = await provider.create_agent(68 name="MyAgent",69 instructions="You are a helpful assistant.",70 )7172 result = await agent.run("Hello!")73 print(result.text)7475asyncio.run(main())76```7778### Agent with Function Tools7980```python81from typing import Annotated82from pydantic import Field83from agent_framework.azure import AzureAIAgentsProvider84from azure.identity.aio import AzureCliCredential8586def get_weather(87 location: Annotated[str, Field(description="City name to get weather for")],88) -> str:89 """Get the current weather for a location."""90 return f"Weather in {location}: 72°F, sunny"9192def get_current_time() -> str:93 """Get the current UTC time."""94 from datetime import datetime, timezone95 return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")9697async def main():98 async with (99 AzureCliCredential() as credential,100 AzureAIAgentsProvider(credential=credential) as provider,101 ):102 agent = await provider.create_agent(103 name="WeatherAgent",104 instructions="You help with weather and time queries.",105 tools=[get_weather, get_current_time], # Pass functions directly106 )107108 result = await agent.run("What's the weather in Seattle?")109 print(result.text)110```111112### Agent with Hosted Tools113114```python115from agent_framework import (116 HostedCodeInterpreterTool,117 HostedFileSearchTool,118 HostedWebSearchTool,119)120from agent_framework.azure import AzureAIAgentsProvider121from azure.identity.aio import AzureCliCredential122123async def main():124 async with (125 AzureCliCredential() as credential,126 AzureAIAgentsProvider(credential=credential) as provider,127 ):128 agent = await provider.create_agent(129 name="MultiToolAgent",130 instructions="You can execute code, search files, and search the web.",131 tools=[132 HostedCodeInterpreterTool(),133 HostedWebSearchTool(name="Bing"),134 ],135 )136137 result = await agent.run("Calculate the factorial of 20 in Python")138 print(result.text)139```140141### Streaming Responses142143```python144async def main():145 async with (146 AzureCliCredential() as credential,147 AzureAIAgentsProvider(credential=credential) as provider,148 ):149 agent = await provider.create_agent(150 name="StreamingAgent",151 instructions="You are a helpful assistant.",152 )153154 print("Agent: ", end="", flush=True)155 async for chunk in agent.run_stream("Tell me a short story"):156 if chunk.text:157 print(chunk.text, end="", flush=True)158 print()159```160161### Conversation Threads162163```python164from agent_framework.azure import AzureAIAgentsProvider165from azure.identity.aio import AzureCliCredential166167async def main():168 async with (169 AzureCliCredential() as credential,170 AzureAIAgentsProvider(credential=credential) as provider,171 ):172 agent = await provider.create_agent(173 name="ChatAgent",174 instructions="You are a helpful assistant.",175 tools=[get_weather],176 )177178 # Create thread for conversation persistence179 thread = agent.get_new_thread()180181 # First turn182 result1 = await agent.run("What's the weather in Seattle?", thread=thread)183 print(f"Agent: {result1.text}")184185 # Second turn - context is maintained186 result2 = await agent.run("What about Portland?", thread=thread)187 print(f"Agent: {result2.text}")188189 # Save thread ID for later resumption190 print(f"Conversation ID: {thread.conversation_id}")191```192193### Structured Outputs194195```python196from pydantic import BaseModel, ConfigDict197from agent_framework.azure import AzureAIAgentsProvider198from azure.identity.aio import AzureCliCredential199200class WeatherResponse(BaseModel):201 model_config = ConfigDict(extra="forbid")202203 location: str204 temperature: float205 unit: str206 conditions: str207208async def main():209 async with (210 AzureCliCredential() as credential,211 AzureAIAgentsProvider(credential=credential) as provider,212 ):213 agent = await provider.create_agent(214 name="StructuredAgent",215 instructions="Provide weather information in structured format.",216 response_format=WeatherResponse,217 )218219 result = await agent.run("Weather in Seattle?")220 weather = WeatherResponse.model_validate_json(result.text)221 print(f"{weather.location}: {weather.temperature}°{weather.unit}")222```223224## Provider Methods225226| Method | Description |227|--------|-------------|228| `create_agent()` | Create new agent on Azure AI service |229| `get_agent(agent_id)` | Retrieve existing agent by ID |230| `as_agent(sdk_agent)` | Wrap SDK Agent object (no HTTP call) |231232## Hosted Tools Quick Reference233234| Tool | Import | Purpose |235|------|--------|---------|236| `HostedCodeInterpreterTool` | `from agent_framework import HostedCodeInterpreterTool` | Execute Python code |237| `HostedFileSearchTool` | `from agent_framework import HostedFileSearchTool` | Search vector stores |238| `HostedWebSearchTool` | `from agent_framework import HostedWebSearchTool` | Bing web search |239| `HostedMCPTool` | `from agent_framework import HostedMCPTool` | Service-managed MCP |240| `MCPStreamableHTTPTool` | `from agent_framework import MCPStreamableHTTPTool` | Client-managed MCP |241242## Complete Example243244```python245import asyncio246from typing import Annotated247from pydantic import BaseModel, Field248from agent_framework import (249 HostedCodeInterpreterTool,250 HostedWebSearchTool,251 MCPStreamableHTTPTool,252)253from agent_framework.azure import AzureAIAgentsProvider254from azure.identity.aio import AzureCliCredential255256257def get_weather(258 location: Annotated[str, Field(description="City name")],259) -> str:260 """Get weather for a location."""261 return f"Weather in {location}: 72°F, sunny"262263264class AnalysisResult(BaseModel):265 summary: str266 key_findings: list[str]267 confidence: float268269270async def main():271 async with (272 AzureCliCredential() as credential,273 MCPStreamableHTTPTool(274 name="Docs MCP",275 url="https://learn.microsoft.com/api/mcp",276 ) as mcp_tool,277 AzureAIAgentsProvider(credential=credential) as provider,278 ):279 agent = await provider.create_agent(280 name="ResearchAssistant",281 instructions="You are a research assistant with multiple capabilities.",282 tools=[283 get_weather,284 HostedCodeInterpreterTool(),285 HostedWebSearchTool(name="Bing"),286 mcp_tool,287 ],288 )289290 thread = agent.get_new_thread()291292 # Non-streaming293 result = await agent.run(294 "Search for Python best practices and summarize",295 thread=thread,296 )297 print(f"Response: {result.text}")298299 # Streaming300 print("\nStreaming: ", end="")301 async for chunk in agent.run_stream("Continue with examples", thread=thread):302 if chunk.text:303 print(chunk.text, end="", flush=True)304 print()305306 # Structured output307 result = await agent.run(308 "Analyze findings",309 thread=thread,310 response_format=AnalysisResult,311 )312 analysis = AnalysisResult.model_validate_json(result.text)313 print(f"\nConfidence: {analysis.confidence}")314315316if __name__ == "__main__":317 asyncio.run(main())318```319320## Conventions321322- Always use async context managers: `async with provider:`323- Pass functions directly to `tools=` parameter (auto-converted to AIFunction)324- Use `Annotated[type, Field(description=...)]` for function parameters325- Use `get_new_thread()` for multi-turn conversations326- Prefer `HostedMCPTool` for service-managed MCP, `MCPStreamableHTTPTool` for client-managed327328## Reference Files329330- [references/tools.md](references/tools.md): Detailed hosted tool patterns331- [references/mcp.md](references/mcp.md): MCP integration (hosted + local)332- [references/threads.md](references/threads.md): Thread and conversation management333- [references/advanced.md](references/advanced.md): OpenAPI, citations, structured outputs334
Full transparency — inspect the skill content before installing.