Skill v1.0.1
currentAutomated scan100/100+10 new
name: agent-framework-azure-ai-py description: "Build persistent agents on Azure AI Foundry using the Microsoft Agent Framework Python SDK." risk: critical source: community date_added: "2026-02-27" metadata: version: "1.0.1"
Bundled upstream support
Supporting files are included at skill-relative paths. See UPSTREAM-NOTICE.md for their pinned sources, licenses, hashes, and import changes.
Agent Framework Azure Hosted Agents
Build persistent agents on Azure AI Foundry using the Microsoft Agent Framework Python SDK.
Architecture
User Query → AzureAIAgentsProvider → Azure AI Agent Service (Persistent)↓Agent.run() / Agent.run_stream()↓Tools: Functions | Hosted (Code/Search/Web) | MCP↓AgentThread (conversation persistence)
SDK generation and execution scope
The examples below preserve an older Agent Framework generation (AzureAIAgentsProvider, AgentThread, Hosted*Tool). They are not verified against the current package. Current Microsoft documentation separates model providers from agent services, and the Python README lists agent-framework-foundry. Before adapting these snippets, identify the installed version and use its matching official API/sample; no compatible legacy version is established here. Do not combine the old classes with an unpinned latest install and assume it works.
Choose the exact Azure tenant/project/deployment, principal and least-privilege role. Creating agents, uploading files, enabling code/web/MCP tools and running prompts sends data to services, can persist records and incur charges. Scope authorization, budget, timeout, tool allowlist and resource cleanup first. Closing clients does not delete hosted agents/files/vector stores/threads. Treat retrieved/tool text as untrusted and enforce tenant/resource/action authorization in tools; prompts are not access controls.
Installation
# Current package discovery only; pin reviewed versions in your project lockfile.# These installs do not make the legacy snippets below compatible.pip install agent-framework# Selective current Foundry integration:pip install agent-framework-foundry
Environment Variables
export AZURE_AI_PROJECT_ENDPOINT="https://<project>.services.ai.azure.com/api/projects/<project-id>"export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"export BING_CONNECTION_ID="your-bing-connection-id" # For web search
Authentication
from azure.identity.aio import AzureCliCredential, DefaultAzureCredential# Developmentcredential = AzureCliCredential()# Productioncredential = DefaultAzureCredential()
Core Workflow
Basic Agent
import asynciofrom agent_framework.azure import AzureAIAgentsProviderfrom azure.identity.aio import AzureCliCredentialasync def main():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!")print(result.text)asyncio.run(main())
Agent with Function Tools
from typing import Annotatedfrom pydantic import Fieldfrom agent_framework.azure import AzureAIAgentsProviderfrom azure.identity.aio import AzureCliCredentialdef get_weather(location: Annotated[str, Field(description="City name to get weather for")],) -> str:"""Return fixture weather (not a live observation)."""return f"Weather in {location}: 72°F, sunny"def get_current_time() -> str:"""Get the current UTC time."""from datetime import datetime, timezonereturn datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")async def main():async with (AzureCliCredential() as credential,AzureAIAgentsProvider(credential=credential) as provider,):agent = await provider.create_agent(name="WeatherAgent",instructions="You help with weather and time queries.",tools=[get_weather, get_current_time], # Pass functions directly)result = await agent.run("What's the weather in Seattle?")print(result.text)
Agent with Hosted Tools
from agent_framework import (HostedCodeInterpreterTool,HostedFileSearchTool,HostedWebSearchTool,)from agent_framework.azure import AzureAIAgentsProviderfrom azure.identity.aio import AzureCliCredentialasync def main():async with (AzureCliCredential() as credential,AzureAIAgentsProvider(credential=credential) as provider,):agent = await provider.create_agent(name="MultiToolAgent",instructions="You can execute code, search files, and search the web.",tools=[HostedCodeInterpreterTool(),HostedWebSearchTool(name="Bing"),],)result = await agent.run("Calculate the factorial of 20 in Python")print(result.text)
Streaming Responses
async def main():async with (AzureCliCredential() as credential,AzureAIAgentsProvider(credential=credential) as provider,):agent = await provider.create_agent(name="StreamingAgent",instructions="You are a helpful assistant.",)print("Agent: ", end="", flush=True)async for chunk in agent.run_stream("Tell me a short story"):if chunk.text:print(chunk.text, end="", flush=True)print()
Conversation Threads
from agent_framework.azure import AzureAIAgentsProviderfrom azure.identity.aio import AzureCliCredentialasync def main():async with (AzureCliCredential() as credential,AzureAIAgentsProvider(credential=credential) as provider,):agent = await provider.create_agent(name="ChatAgent",instructions="You are a helpful assistant.",tools=[get_weather],)# Create thread for conversation persistencethread = agent.get_new_thread()# First turnresult1 = await agent.run("What's the weather in Seattle?", thread=thread)print(f"Agent: {result1.text}")# Second turn - context is maintainedresult2 = await agent.run("What about Portland?", thread=thread)print(f"Agent: {result2.text}")# Save thread ID for later resumptionprint(f"Conversation ID: {thread.conversation_id}")
Structured Outputs
from pydantic import BaseModel, ConfigDictfrom agent_framework.azure import AzureAIAgentsProviderfrom azure.identity.aio import AzureCliCredentialclass WeatherResponse(BaseModel):model_config = ConfigDict(extra="forbid")location: strtemperature: floatunit: strconditions: strasync def main():async with (AzureCliCredential() as credential,AzureAIAgentsProvider(credential=credential) as provider,):agent = await provider.create_agent(name="StructuredAgent",instructions="Provide weather information in structured format.",response_format=WeatherResponse,)result = await agent.run("Weather in Seattle?")weather = WeatherResponse.model_validate_json(result.text)print(f"{weather.location}: {weather.temperature}°{weather.unit}")
Provider Methods
| Method | Description | |
|---|---|---|
create_agent() | Create new agent on Azure AI service | |
get_agent(agent_id) | Retrieve existing agent by ID | |
as_agent(sdk_agent) | Wrap SDK Agent object (no HTTP call) |
Hosted Tools Quick Reference
| Tool | Import | Purpose | |
|---|---|---|---|
HostedCodeInterpreterTool | from agent_framework import HostedCodeInterpreterTool | Execute Python code | |
HostedFileSearchTool | from agent_framework import HostedFileSearchTool | Search vector stores | |
HostedWebSearchTool | from agent_framework import HostedWebSearchTool | Bing web search | |
HostedMCPTool | from agent_framework import HostedMCPTool | Service-managed MCP | |
MCPStreamableHTTPTool | from agent_framework import MCPStreamableHTTPTool | Client-managed MCP |
Composite Legacy Example (requires migration/compatibility validation)
import asynciofrom typing import Annotatedfrom pydantic import BaseModel, Fieldfrom agent_framework import (HostedCodeInterpreterTool,HostedWebSearchTool,MCPStreamableHTTPTool,)from agent_framework.azure import AzureAIAgentsProviderfrom azure.identity.aio import AzureCliCredentialdef get_weather(location: Annotated[str, Field(description="City name")],) -> str:"""Return fixture weather (not a live observation)."""return f"Weather in {location}: 72°F, sunny"class AnalysisResult(BaseModel):summary: strkey_findings: list[str]confidence: float = Field(ge=0.0, le=1.0)async def main():async with (AzureCliCredential() as credential,MCPStreamableHTTPTool(name="Docs MCP",url="https://learn.microsoft.com/api/mcp",) as mcp_tool,AzureAIAgentsProvider(credential=credential) as provider,):agent = await provider.create_agent(name="ResearchAssistant",instructions="You are a research assistant with multiple capabilities.",tools=[get_weather,HostedCodeInterpreterTool(),HostedWebSearchTool(name="Bing"),mcp_tool,],)thread = agent.get_new_thread()# Non-streamingresult = await agent.run("Search for Python best practices and summarize",thread=thread,)print(f"Response: {result.text}")# Streamingprint("\nStreaming: ", end="")async for chunk in agent.run_stream("Continue with examples", thread=thread):if chunk.text:print(chunk.text, end="", flush=True)print()# Structured outputresult = await agent.run("Analyze findings",thread=thread,response_format=AnalysisResult,)analysis = AnalysisResult.model_validate_json(result.text)print(f"\nModel self-rating (not calibrated reliability): {analysis.confidence}")if __name__ == "__main__":asyncio.run(main())
Current references: Microsoft provider model, Python installation and samples.
Conventions
- Always use async context managers:
async with provider: - Pass functions directly to
tools=parameter (auto-converted to AIFunction) - Use
Annotated[type, Field(description=...)]for function parameters - Use
get_new_thread()for multi-turn conversations - Prefer
HostedMCPToolfor service-managed MCP,MCPStreamableHTTPToolfor client-managed
Reference Files
- references/tools.md: Detailed hosted tool patterns
- references/mcp.md: MCP integration (hosted + local)
- references/threads.md: Thread and conversation management
- references/advanced.md: OpenAPI, citations, structured outputs
When to Use
This skill is applicable to execute the workflow or actions described in the overview.
Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.