Communitygithub.com

SamuelChien/mega-skills-collection

Construisez des agents Azure AI Foundry persistants en utilisant le 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 fils de conversation ou de l'implémentation de réponses en streaming. Couvre les outils de fonction, les sorties structurées et les agents multi-outils.

Qu'est-ce que mega-skills-collection ?

Cette compétence fournit un guide complet pour construire des agents IA persistants sur Azure AI Foundry en utilisant le SDK Python Microsoft Agent Framework. Elle est idéale pour les développeurs qui souhaitent créer des agents capables de maintenir un contexte de conversation sur plusieurs tours, d'utiliser des outils hébergés par Azure (comme l'interpréteur de code, la recherche de fichiers et la recherche web Bing), d'intégrer des serveurs MCP (Model Context Protocol) pour des fonctionnalités étendues, et de gérer des réponses en streaming. La compétence couvre l'ensemble du cycle de vie, de l'authentification via `DefaultAzureCredential` à la création d'agents avec des outils de fonction, des sorties structurées (Pydantic), et des fils de conversation pour la persistance. Elle prend en charge le SDK `agent-framework` (packages `agent-framework-azure-ai`) et est compatible avec les workflows synchrones et asynchrones, en mettant l'accent sur les gestionnaires de contexte et les meilleures pratiques de sécurité.

Compatible avec~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/SamuelChien/mega-skills-collection/tree/HEAD/agent-framework-azure-ai-py

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Agents Hébergés Azure du Framework d'Agents

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

Architecture

Requête Utilisateur → AzureAIAgentsProvider → Service 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://<projet>.services.ai.azure.com/api/projects/<id-projet>"  # 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-id-connexion-bing"  # Pour la recherche web
export AZURE_TOKEN_CREDENTIALS=prod # Requis uniquement si DefaultAzureCredential est utilisé en production

Authentification & Cycle de Vie

🔑 Deux règles s'appliquent à chaque exemple de code ci-dessous :

  1. Privilégiez DefaultAzureCredential. Il fonctionne localement (Azure CLI / VS Code / Developer CLI) et dans Azure (identité managée, identité de charge de travail) sans changement de code. Évitez les chaînes de connexion, les clés de compte/API — elles contournent l'audit et la rotation Entra.
    • Développement local : DefaultAzureCredential fonctionne tel quel.
    • Production : définissez AZURE_TOKEN_CREDENTIALS=prod (ou AZURE_TOKEN_CREDENTIALS=<credential_spécifique>) pour limiter la chaîne de credentials aux credentials sécurisés pour la production.
  2. 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 : with <Client>(...) as client:
    • Asynchrone : async with <Client>(...) as client: et async with DefaultAzureCredential() as credential: (depuis azure.identity.aio)

Les extraits de code peuvent abréger cette configuration, mais le code de production doit toujours suivre les 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_spécifique>
credential = DefaultAzureCredential(require_envvar=True)
# Ou utiliser un credential spécifique directement en production :
# Voir https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

Workflow de Base

Agent Simple

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="MonAgent",
            instructions="Vous êtes un assistant utile.",
        )
        
        result = await agent.run("Bonjour !")
        print(result.text)

asyncio.run(main())

Agent avec Outils de Fonction

from typing import Annotated
from pydantic import Field
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential

def obtenir_meteo(
    lieu: Annotated[str, Field(description="Nom de la ville pour obtenir la météo")],
) -> str:
    """Obtenir la météo actuelle pour un lieu."""
    return f"Météo à {lieu} : 72°F, ensoleillé"

def obtenir_heure_actuelle() -> str:
    """Obtenir 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="AgentMeteo",
            instructions="Vous aidez avec les requêtes météo et d'heure.",
            tools=[obtenir_meteo, obtenir_heure_actuelle],  # Passer 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="AgentMultiOutils",
            instructions="Vous pouvez exécuter du code, rechercher des fichiers et rechercher sur le web.",
            tools=[
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
            ],
        )
        
        result = await agent.run("Calcule la factorielle de 20 en Python")
        print(result.text)

Réponses en Streaming

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentsProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(
            name="AgentStreaming",
            instructions="Vous êtes un assistant utile.",
        )
        
        print("Agent : ", end="", flush=True)
        async for chunk in agent.run_stream("Raconte-moi une courte 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="AgentDialogue",
            instructions="Vous êtes un assistant utile.",
            tools=[obtenir_meteo],
        )
        
        # Créer un fil 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}")
        
        # Sauvegarder l'ID du fil pour une reprise ultérieure
        print(f"ID de 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 ReponseMeteo(BaseModel):
    model_config = ConfigDict(extra="forbid")
    
    localisation: str
    temperature: float
    unite: str
    conditions: str

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentsProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(
            name="AgentStructure",
            instructions="Fournissez des informations météorologiques au format structuré.",
            response_format=ReponseMeteo,
        )
        
        result = await agent.run("Météo à Seattle ?")
        meteo = ReponseMeteo.model_validate_json(result.text)
        print(f"{meteo.localisation} : {meteo.temperature}°{meteo.unite}")

Méthodes du Fournisseur

MéthodeDescription
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 un objet Agent du SDK (pas d'appel HTTP)

Référence Rapide des Outils Hébergés

OutilImportObjectif
HostedCodeInterpreterToolfrom agent_framework import HostedCodeInterpreterToolExécuter du code Python
HostedFileSearchToolfrom agent_framework import HostedFileSearchToolRechercher dans les magasins de vecteurs
HostedWebSearchToolfrom agent_framework import HostedWebSearchToolRecherche web Bing
HostedMCPToolfrom agent_framework import HostedMCPToolMCP géré par le service
MCPStreamableHTTPToolfrom agent_framework import MCPStreamableHTTPToolMCP 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 obtenir_meteo(
    lieu: Annotated[str, Field(description="Nom de la ville")],
) -> str:
    """Obtenir la météo pour un lieu."""
    return f"Météo à {lieu} : 72°F, ensoleillé"


class ResultatAnalyse(BaseModel):
    resume: str
    constats_cles: list[str]
    confiance: float


async def main():
    async with (
        AzureCliCredential() as credential,
        MCPStreamableHTTPTool(
            name="Docs MCP",
            url="https://learn.microsoft.com/api/mcp",
        ) as outil_mcp,
        AzureAIAgentsProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(
            name="AssistantRecherche",
            instructions="Vous êtes un assistant de recherche avec plusieurs capacités.",
            tools=[
                obtenir_meteo,
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
                outil_mcp,
            ],
        )
        
        fil = agent.get_new_thread()
        
        # Non-streaming
        resultat = await agent.run(
            "Recherche les meilleures pratiques Python et résume-moi",
            thread=fil,
        )
        print(f"Réponse : {resultat.text}")
        
        # Streaming
        print("\nStreaming : ", end="")
        async for morceau in agent.run_stream("Continue avec des exemples", thread=fil):
            if morceau.text:
                print(morceau.text, end="", flush=True)
        print()
        
        # Sortie structurée
        resultat = await agent.run(
            "Analyse les résultats",
            thread=fil,
            response_format=ResultatAnalyse,
        )
        analyse = ResultatAnalyse.model_validate_json(resultat.text)
        print(f"\nConfiance : {analyse.confiance}")


if __name__ == "__main__":
    asyncio.run(main())

Conventions

  • Utilisez toujours les gestionnaires de contexte asynchrones : async with 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
  • Préférez HostedMCPTool pour le MCP géré par le service, MCPStreamableHTTPTool pour le MCP géré par le client

Bonnes Pratiques

  1. Ce SDK est async-first — utilisez des gestionnaires async def et async with partout.
  2. Utilisez toujours des gestionnaires de contexte pour les clients et les credentials asynchrones. Enveloppez chaque client dans with Client(...) as client: (synchrone) ou async with Client(...) as client: (asynchrone). Pour DefaultAzureCredential asynchrone depuis azure.identity.aio, utilisez également async with credential: afin que les jetons et les transports soient nettoyés.

Fichiers de Référence

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

SamuelChien/mega-skills-collection

Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

SamuelChien/mega-skills-collection

Arquitecto de Soluciones Principal y Consultor Tecnológico de Andru.ia. Diagnostica y traza la hoja de ruta óptima para proyectos de IA en español.

SamuelChien/mega-skills-collection

Ingeniero de Sistemas de Andru.ia. Diseña, redacta y despliega nuevas habilidades (skills) dentro del repositorio siguiendo el Estándar de Diamante.

SamuelChien/mega-skills-collection

Estratega de Inteligencia de Dominio de Andru.ia. Analiza el nicho específico de un proyecto para inyectar conocimientos, regulaciones y estándares únicos del sector. Actívalo tras definir el nicho.

SamuelChien/mega-skills-collection

2D game development principles. Sprites, tilemaps, physics, camera.

SamuelChien/mega-skills-collection

3D game development principles. Rendering, shaders, physics, cameras.

SamuelChien/mega-skills-collection

Expert in building 3D experiences for the web - Three.js, React Three Fiber, Spline, WebGL, and interactive 3D scenes. Covers product configurators, 3D portfolios, immersive websites, and bringing depth to web experiences.

SamuelChien/mega-skills-collection

Accessibility audit skill for scanning, fixing, and verifying WCAG 2.2 Level A and AA compliance across React, Next.js, Vue, Angular, Svelte, and plain HTML codebases. Use when auditing accessibility, fixing a11y violations, checking color contrast, generating compliance reports, or integrating accessibility checks into CI/CD pipelines.

SamuelChien/mega-skills-collection

Ab Test Analyzer - Auto-activating skill for Data Analytics. Triggers on: ab test analyzer, ab test analyzer Part of the Data Analytics skill category.

SamuelChien/mega-skills-collection

A B Test Config Creator - Auto-activating skill for ML Deployment. Triggers on: a b test config creator, a b test config creator Part of the ML Deployment skill category.

SamuelChien/mega-skills-collection

When the user wants to plan, design, or implement an A/B test or experiment. Also use when the user mentions "A/B test," "split test," "experiment," "test this change," "variant copy," "multivariate test," "hypothesis," "conversion experiment," "statistical significance," or "test this." For tracking implementation, see analytics-tracking.

SamuelChien/mega-skills-collection

Acceptance Criteria Creator - Auto-activating skill for Enterprise Workflows. Triggers on: acceptance criteria creator, acceptance criteria creator Part of the Enterprise Workflows skill category.

SamuelChien/mega-skills-collection

Use when a coding task should be driven end-to-end from issue intake through implementation, review, deployment, and acceptance verification with minimal human re-intervention.

SamuelChien/mega-skills-collection

Accessibility Audit Runner - Auto-activating skill for Frontend Development. Triggers on: accessibility audit runner, accessibility audit runner Part of the Frontend Development skill category.

SamuelChien/mega-skills-collection

You are an accessibility expert specializing in WCAG compliance, inclusive design, and assistive technology compatibility. Conduct audits, identify barriers, and provide remediation guidance.

SamuelChien/mega-skills-collection

Web accessibility patterns for WCAG 2.2 compliance including ARIA, keyboard navigation, screen readers, and testing

SamuelChien/mega-skills-collection

Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed, or change policy for the Discord channel.

SamuelChien/mega-skills-collection

Create unified specification packages across Business, Development, and Design teams. Staged elaboration (L0 Vision → L1 Requirements → L2 Team Detail → L3 Acceptance Criteria) to build shared understanding. Does not write code.

SamuelChien/mega-skills-collection

Research a company or person and get actionable sales intel. Works standalone with web search, supercharged when you connect enrichment tools or your CRM. Trigger with "research [company]", "look up [person]", "intel on [prospect]", "who is [name] at [company]", or "tell me about [company]".

SamuelChien/mega-skills-collection

Validate messaging consistency across website, GitHub repos, and local documentation generating read-only discrepancy reports. Use when checking content alignment or finding mixed messaging. Trigger with phrases like "check consistency", "validate documentation", or "audit messaging".

Skills associés