agent-framework-azure-ai-py

Créez des agents Azure AI Foundry à l'aide du SDK Python Microsoft Agent Framework (agent-framework-azure-ai). À utiliser lors de la création d'agents persistants avec `AzureAIAgentsProvider`, de l'utilisation d'outils hébergés (interpréteur de code, recherche de fichiers, recherche web), de l'intégration de serveurs MCP, de la gestion de threads de conversation ou de l'implémentation de réponses en streaming. Couvre les function tools, les structured outputs et les agents multi-outils.

npx skills add https://github.com/microsoft/skills --skill agent-framework-azure-ai-py

Framework d'agent Azure Hosted Agents

Construisez des agents persistants sur Azure AI Foundry en utilisant le SDK Microsoft Agent Framework Python.

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

# Framework complet (recommandé)
pip install agent-framework --pre

# Ou package spécifique à Azure uniquement
pip install agent-framework-azure-ai --pre

Variables d'environnement

export AZURE_AI_PROJECT_ENDPOINT="https://<project>.services.ai.azure.com/api/projects/<project-id>"  # 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="your-bing-connection-id"  # Pour la recherche web
export AZURE_TOKEN_CREDENTIALS=prod # Requis uniquement si DefaultAzureCredential est utilisé en production

Authentification

from azure.identity.aio import AzureCliCredential, DefaultAzureCredential, ManagedIdentityCredential

# Développement
credential = AzureCliCredential()

# Production
# Dev local : DefaultAzureCredential. Production : définir AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Ou utiliser directement une authentification spécifique en production :
# Voir https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

Flux de travail principal

Agent basique

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 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="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],  # Passez les fonctions directement
        )

        result = await agent.run("What's the weather in 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="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)

Diffusion de réponses

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()

Threads 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="You are a helpful assistant.",
            tools=[get_weather],
        )

        # Créer un thread pour la persistance de conversation
        thread = agent.get_new_thread()

        # Premier tour
        result1 = await agent.run("What's the weather in Seattle?", thread=thread)
        print(f"Agent: {result1.text}")

        # Deuxième tour - le contexte est maintenu
        result2 = await agent.run("What about Portland?", thread=thread)
        print(f"Agent: {result2.text}")

        # Sauvegarder l'ID du thread pour une reprise ultérieure
        print(f"Conversation ID: {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="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}")

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 ID
as_agent(sdk_agent) Envelopper un objet Agent SDK (sans appel HTTP)

Référence rapide des outils hébergés

Outil Import Objectif
HostedCodeInterpreterTool from agent_framework import HostedCodeInterpreterTool Exécuter du code Python
HostedFileSearchTool from agent_framework import HostedFileSearchTool Rechercher dans les magasins vectoriels
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="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()

        # Sans diffusion
        result = await agent.run(
            "Search for Python best practices and summarize",
            thread=thread,
        )
        print(f"Response: {result.text}")

        # Avec diffusion
        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()

        # Sortie structurée
        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

  • Toujours utiliser les gestionnaires de contexte asynchrone : async with provider:
  • Passer les fonctions directement au paramètre tools= (conversion automatique en AIFunction)
  • Utiliser Annotated[type, Field(description=...)] pour les paramètres de fonction
  • Utiliser get_new_thread() pour les conversations multi-tours
  • Préférer HostedMCPTool pour les MCP gérés par le service, MCPStreamableHTTPTool pour les MCP gérés par le client

Fichiers de référence

Skills similaires