agent-framework-azure-ai-py
microsoft/skills
Créez des agents persistants sur Azure AI Foundry à l'aide du SDK Python de Microsoft Agent Framework, qui prend en charge les outils de fonction, les outils hébergés, les serveurs MCP, les fils de conversation et les réponses en continu.
...Développer toutAgent Framework : agents hébergés sur Azure
Créez des agents persistants sur Azure AI Foundry à l'aide du SDK Python du Microsoft Agent Framework.
Architecture
Requête utilisateur → AzureAIAgentsProvider → Service d’agent Azure AI (persistant)
↓
Agent.run() / Agent.run_stream()
↓
Outils : Fonctions | Hébergés (Code/Recherche/Web) | MCP
↓
AgentThread (persistance de la conversation)
Installation
# Framework complet (recommandé)
pip install agent-framework --pre
# Ou uniquement le package spécifique à Azure
pip install agent-framework-azure-ai --pre
Variables d’environnement
export AZURE_AI_PROJECT_ENDPOINT="https://.services.ai.azure.com/api/projects/" # Requis pour toutes les méthodes d’authentification
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Requis pour toutes les méthodes d'authentification
export BING_CONNECTION_ID="votre-identifiant-de-connexion-bing" # Pour la recherche Web
export AZURE_TOKEN_CREDENTIALS=prod # Requis uniquement si DefaultAzureCredential est utilisé en production
Authentification et cycle de vie
🔑 Deux règles s’appliquent à tous les exemples de code ci-dessous :
- Privilégiez
DefaultAzureCredential. Elle fonctionne en local (CLI Azure / VS Code / CLI développeur) et dans Azure (identité gérée, identité de charge de travail) sans modification du code. Évitez les chaînes de connexion, les identifiants de compte et les clés API : ils contournent l’audit et la rotation Entra.
- Développement local :
DefaultAzureCredentialfonctionne tel quel.- Production : définissez
AZURE_TOKEN_CREDENTIALS=prod(ouAZURE_TOKEN_CREDENTIALS=) pour limiter la chaîne d’identifiants aux identifiants sécurisés pour la production.- Enveloppez chaque client dans un gestionnaire de contexte afin que les transports HTTP, les sockets et les caches de jetons soient libérés de manière déterministe :
- Synchrone :
avec(...) comme client : - Asynchrone :
async avecet(...) comme client : async avec DefaultAzureCredential() comme identifiant :(deazure.identity.aio)Les extraits de code peuvent simplifier cette configuration, mais le code de production doit toujours respecter ces deux règles.
from azure.identity.aio import AzureCliCredential, DefaultAzureCredential, ManagedIdentityCredential
# Développement
credential = AzureCliCredential()
# Production
# Développement local : DefaultAzureCredential. Production : définir AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=
credential = DefaultAzureCredential(require_envvar=True)
# Ou utilisez directement des informations d’identification spécifiques en production :
# Voir https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
Workflow principal
Agent de base
import asyncio
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyAgent",
instructions="Tu es un assistant très utile.",
)
result = await agent.run("Bonjour !")
print(result.text)
asyncio.run(main())
Agent avec des outils de fonction
from typing import Annotated
from pydantic import Field
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
def get_weather(
location: Annotated[str, Field(description="Nom de la ville pour laquelle obtenir la météo")],
) -> str:
"""Récupère la météo actuelle pour un lieu."""
return f"Météo à {location} : 72 °F, ensoleillé"
def get_current_time() -> str:
"""Récupère l'heure UTC actuelle."""
from datetime import datetime, timezone
return 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="Tu aides à répondre aux requêtes concernant la météo et l'heure.",
tools=[get_weather, get_current_time], # Passe les fonctions directement
)
result = await agent.run("Quel temps fait-il à Seattle ?")
print(result.text)
Agent avec outils hébergés
from agent_framework import (
HostedCodeInterpreterTool,
HostedFileSearchTool,
HostedWebSearchTool,
)
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MultiToolAgent",
instructions="Vous pouvez exécuter du code, rechercher des fichiers et effectuer des recherches sur le Web.",
tools=[
HostedCodeInterpreterTool(),
HostedWebSearchTool(name="Bing"),
],
)
result = await agent.run("Calculer la factorielle de 20 en Python")
print(result.text)
Réponses en continu
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="StreamingAgent",
instructions="Tu es un assistant serviable.",
)
print("Agent : ", end="", flush=True)
async for chunk in agent.run_stream("Raconte-moi une petite histoire"):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
Fils de conversation
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="ChatAgent",
instructions="Tu es un assistant serviable.",
tools=[get_weather],
)
# Création d’un thread pour la persistance de la conversation
thread = agent.get_new_thread()
# Premier tour
result1 = await agent.run("Quel temps fait-il à Seattle ?", thread=thread)
print(f"Agent : {result1.text}")
# Deuxième tour – le contexte est conservé
result2 = await agent.run("Et à Portland ?", thread=thread)
print(f"Agent : {result2.text}")
# Enregistrement de l’ID du fil de discussion pour une reprise ultérieure
print(f"ID de la conversation : {thread.conversation_id}")
Sorties structurées
from pydantic import BaseModel, ConfigDict
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
class WeatherResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
location : str
temperature : float
unit : str
conditions : str
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="StructuredAgent",
instructions="Fournir des informations météorologiques au format structuré.",
response_format=WeatherResponse,
)
result = await agent.run("Quel temps fait-il à Seattle ?")
weather = WeatherResponse.model_validate_json(result.text)
print(f"{weather.location} : {weather.temperature} °{weather.unit}")
Méthodes du fournisseur
| Méthode | Description |
|---|---|
create_agent() |
Créer un nouvel agent sur le service Azure AI |
get_agent(agent_id) |
Récupérer un agent existant par son ID |
as_agent(sdk_agent) |
Envelopper l'objet SDK Agent (sans appel HTTP) |
Guide de référence rapide des outils hébergés
| Outil | Importation | Objectif |
|---|---|---|
HostedCodeInterpreterTool |
from agent_framework import HostedCodeInterpreterTool |
Exécuter du code Python |
HostedFileSearchTool |
from agent_framework import HostedFileSearchTool |
Rechercher dans des bases de vecteurs |
HostedWebSearchTool |
from agent_framework import HostedWebSearchTool |
Recherche Web Bing |
HostedMCPTool |
from agent_framework import HostedMCPTool |
MCP géré par le service |
MCPStreamableHTTPTool |
from agent_framework import MCPStreamableHTTPTool |
MCP géré par le client |
Exemple complet
import asyncio
from typing import Annotated
from pydantic import BaseModel, Field
from agent_framework import (
HostedCodeInterpreterTool,
HostedWebSearchTool,
MCPStreamableHTTPTool,
)
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
def get_weather(
location: Annotated[str, Field(description="Nom de la ville")],
) -> str:
"""Récupère la météo pour un lieu."""
return f"Météo à {location} : 72 °F, ensoleillé"
class AnalysisResult(BaseModel) :
summary : str
key_findings : list[str]
confidence : float
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="Vous êtes un assistant de recherche doté de multiples compétences.",
tools=[
get_weather,
HostedCodeInterpreterTool(),
HostedWebSearchTool(name="Bing"),
mcp_tool,
],
)
thread = agent.get_new_thread()
# Sans streaming
result = await agent.run(
"Rechercher les meilleures pratiques Python et en faire un résumé",
thread=thread,
)
print(f"Réponse : {result.text}")
# En continu
print("\nEn continu : ", end="")
async for chunk in agent.run_stream("Poursuivre avec des exemples", thread=thread):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
# Sortie structurée
result = await agent.run(
"Analyser les résultats",
thread=thread,
response_format=AnalysisResult,
)
analysis = AnalysisResult.model_validate_json(result.text)
print(f"\nConfiance : {analysis.confidence}")
if __name__ == "__main__":
asyncio.run(main())
Conventions
- Utilisez toujours des gestionnaires de contexte asynchrones :
async avec provider : - Passez les fonctions directement au paramètre
tools=(converties automatiquement en AIFunction) - Utilisez
Annotated[type, Field(description=...)]pour les paramètres de fonction - Utilisez `
get_new_thread()` pour les conversations à plusieurs tours - Privilégiez
HostedMCPToolpour les MCP gérés par le service, etMCPStreamableHTTPToolpour ceux gérés par le client
Bonnes pratiques
- Ce SDK privilégie l’asynchrone: utilisez des gestionnaires
de définition asynchronesetl’asynchrone debout en bout. - Utilisez toujours des gestionnaires de contexte pour les clients et les informations d’identification asynchrones. Enveloppez chaque client
dans Client(...) as client:(synchrone) ouasync avec Client(...) as client:(asynchrone). Pour les informations d’identification asynchronesDefaultAzureCredentialissues deazure.identity.aio, utilisez égalementasync avec credential:afin que les jetons et les transports soient nettoyés.
Fichiers de référence
- references/tools.md : Modèles détaillés d’outils hébergés
- references/mcp.md : intégration MCP (hébergée + locale)
- references/threads.md : gestion des fils de discussion et des conversations
- references/advanced.md : OpenAPI, citations, sorties structurées
---
name: agent-framework-azure-ai-py
description: Build persistent agents on Azure AI Foundry using the Microsoft Agent Framework Python SDK, with support for function tools, hosted tools, MCP servers, conversation threads, and streaming responses.
license: MIT
---
# 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)
```
## Installation
```bash
# Full framework (recommended)
pip install agent-framework --pre
# Or Azure-specific package only
pip install agent-framework-azure-ai --pre
```
## Environment Variables
```bash
export AZURE_AI_PROJECT_ENDPOINT="https://<project>.services.ai.azure.com/api/projects/<project-id>" # Required for all auth methods
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Required for all auth methods
export BING_CONNECTION_ID="your-bing-connection-id" # For web search
export AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Authentication & Lifecycle
> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
> - Local dev: `DefaultAzureCredential` works as-is.
> - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
> - Sync: `with <Client>(...) as client:`
> - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.
```python
from azure.identity.aio import AzureCliCredential, DefaultAzureCredential, ManagedIdentityCredential
# Development
credential = AzureCliCredential()
# Production
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
```
## Core Workflow
### Basic Agent
```python
import asyncio
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async 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
```python
from typing import Annotated
from pydantic import Field
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
def get_weather(
location: Annotated[str, Field(description="City name to get weather for")],
) -> str:
"""Get the current weather for a location."""
return f"Weather in {location}: 72°F, sunny"
def get_current_time() -> str:
"""Get the current UTC time."""
from datetime import datetime, timezone
return 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
```python
from agent_framework import (
HostedCodeInterpreterTool,
HostedFileSearchTool,
HostedWebSearchTool,
)
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async 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
```python
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
```python
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async 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 persistence
thread = agent.get_new_thread()
# First turn
result1 = await agent.run("What's the weather in Seattle?", thread=thread)
print(f"Agent: {result1.text}")
# Second turn - context is maintained
result2 = await agent.run("What about Portland?", thread=thread)
print(f"Agent: {result2.text}")
# Save thread ID for later resumption
print(f"Conversation ID: {thread.conversation_id}")
```
### Structured Outputs
```python
from pydantic import BaseModel, ConfigDict
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
class WeatherResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
location: str
temperature: float
unit: str
conditions: str
async 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 |
## Complete Example
```python
import asyncio
from typing import Annotated
from pydantic import BaseModel, Field
from agent_framework import (
HostedCodeInterpreterTool,
HostedWebSearchTool,
MCPStreamableHTTPTool,
)
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
def get_weather(
location: Annotated[str, Field(description="City name")],
) -> str:
"""Get weather for a location."""
return f"Weather in {location}: 72°F, sunny"
class AnalysisResult(BaseModel):
summary: str
key_findings: list[str]
confidence: float
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-streaming
result = await agent.run(
"Search for Python best practices and summarize",
thread=thread,
)
print(f"Response: {result.text}")
# Streaming
print("\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 output
result = await agent.run(
"Analyze findings",
thread=thread,
response_format=AnalysisResult,
)
analysis = AnalysisResult.model_validate_json(result.text)
print(f"\nConfidence: {analysis.confidence}")
if __name__ == "__main__":
asyncio.run(main())
```
## 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 `HostedMCPTool` for service-managed MCP, `MCPStreamableHTTPTool` for client-managed
## Best Practices
1. **This SDK is async-first** — use `async def` handlers and `async with` throughout.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with Client(...) as client:` (sync) or `async with Client(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
## Reference Files
- [references/tools.md](references/tools.md): Detailed hosted tool patterns
- [references/mcp.md](references/mcp.md): MCP integration (hosted + local)
- [references/threads.md](references/threads.md): Thread and conversation management
- [references/advanced.md](references/advanced.md): OpenAPI, citations, structured outputs
Tous les fichiers
0 fichiersInstaller agent-framework-azure-ai-py
Téléchargez et décompressez les fichiers de compétences dans votre répertoire .claude/skills/.
Télécharger le ZIPClonez le dépôt et copiez les fichiers de compétence dans votre projet.
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/agent-framework-azure-ai-py # Copy SKILL.md to your .claude/skills/ directory
Copier





Maison
