Communitygithub.com

SamuelChien/mega-skills-collection

Crea agentes persistentes en Azure AI Foundry usando el SDK de Python del Agent Framework de Microsoft. Utilízalo cuando necesites agentes con AzureAIAgentsProvider, herramientas alojadas (intérprete de código, búsqueda de archivos, búsqueda web), integración de servidores MCP, gestión de hilos de conversación o respuestas en streaming. Incluye herramientas de función, salidas estructuradas y agentes multi-herramienta.

¿Qué es mega-skills-collection?

Esta skill permite construir agentes persistentes en Azure AI Foundry utilizando el SDK de Python del Microsoft Agent Framework (paquete `agent-framework-azure-ai`). Está diseñada para desarrolladores que necesitan crear agentes que mantengan el estado de la conversación, usen herramientas alojadas como la ejecución de código, búsqueda de archivos (vector stores) y búsqueda web con Bing, e integren servidores MCP tanto gestionados por el servicio como por el cliente. La skill explica en detalle la autenticación con `DefaultAzureCredential`, el ciclo de vida de los clientes con context managers asíncronos, y los flujos de trabajo básicos y avanzados: desde un agente simple hasta agentes con múltiples herramientas, respuestas en streaming, hilos de conversación persistentes y salidas estructuradas con Pydantic. Además, incluye tablas de referencia rápida para las herramientas alojadas y los métodos del proveedor `AzureAIAgentsProvider`, así como enlaces a documentación más detallada sobre herramientas, MCP, hilos y funcionalidades avanzadas. Es adecuada para plataformas de agentes como Claude Code, Codex o Cursor, siempre que se utilice el ecosistema Azure y el SDK de Microsoft.

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

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Agent Framework Azure Hosted Agents

Construye agentes persistentes en Azure AI Foundry usando el SDK de Python del Microsoft Agent Framework.

Arquitectura

User Query → AzureAIAgentsProvider → Azure AI Agent Service (Persistent)
                    ↓
              Agent.run() / Agent.run_stream()
                    ↓
              Tools: Functions | Hosted (Code/Search/Web) | MCP
                    ↓
              AgentThread (persistencia de conversación)

Instalación

# Framework completo (recomendado)
pip install agent-framework --pre

# O solo el paquete específico de Azure
pip install agent-framework-azure-ai --pre

Variables de Entorno

export AZURE_AI_PROJECT_ENDPOINT="https://<project>.services.ai.azure.com/api/projects/<project-id>"  # Requerido para todos los métodos de autenticación
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"  # Requerido para todos los métodos de autenticación
export BING_CONNECTION_ID="your-bing-connection-id"  # Para búsqueda web
export AZURE_TOKEN_CREDENTIALS=prod # Requerido solo si se usa DefaultAzureCredential en producción

Autenticación y Ciclo de Vida

🔑 Dos reglas aplican a cada fragmento de código a continuación:

  1. Preferir DefaultAzureCredential. Funciona localmente (Azure CLI / VS Code / Developer CLI) y en Azure (managed identity, workload identity) sin cambios de código. Evita cadenas de conexión, claves de cuenta/API — evitan la auditoría y rotación de Entra.
    • Desarrollo local: DefaultAzureCredential funciona tal cual.
    • Producción: establece AZURE_TOKEN_CREDENTIALS=prod (o AZURE_TOKEN_CREDENTIALS=<credential_específico>) para restringir la cadena de credenciales a aquellas seguras para producción.
  2. Envuelve cada cliente en un context manager para que los transportes HTTP, sockets y cachés de tokens se liberen de manera determinista:
    • Sincrónico: with <Cliente>(...) as client:
    • Asincrónico: async with <Cliente>(...) as client: y async with DefaultAzureCredential() as credential: (de azure.identity.aio)

Los fragmentos pueden abreviar esta configuración, pero el código en producción debe seguir siempre ambas reglas.

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

# Desarrollo
credential = AzureCliCredential()

# Producción
# Desarrollo local: DefaultAzureCredential. Producción: establecer AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=<credential_específico>
credential = DefaultAzureCredential(require_envvar=True)
# O usar una credencial específica directamente en producción:
# Ver https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

Flujo de Trabajo Principal

Agente Básico

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="Eres un asistente útil.",
        )
        
        result = await agent.run("¡Hola!")
        print(result.text)

asyncio.run(main())

Agente con Herramientas de Función

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="Nombre de la ciudad para obtener el clima")],
) -> str:
    """Obtiene el clima actual para una ubicación."""
    return f"Clima en {location}: 72°F, soleado"

def get_current_time() -> str:
    """Obtiene la hora UTC actual."""
    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="Ayudas con consultas sobre el clima y la hora.",
            tools=[get_weather, get_current_time],  # Pasa funciones directamente
        )
        
        result = await agent.run("¿Cómo está el clima en Seattle?")
        print(result.text)

Agente con Herramientas Alojadas

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="Puedes ejecutar código, buscar archivos y buscar en la web.",
            tools=[
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
            ],
        )
        
        result = await agent.run("Calcula el factorial de 20 en Python")
        print(result.text)

Respuestas en Streaming

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentsProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(
            name="StreamingAgent",
            instructions="Eres un asistente útil.",
        )
        
        print("Agente: ", end="", flush=True)
        async for chunk in agent.run_stream("Cuéntame una historia corta"):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()

Hilos de Conversación

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="Eres un asistente útil.",
            tools=[get_weather],
        )
        
        # Crear hilo para persistencia de la conversación
        thread = agent.get_new_thread()
        
        # Primer turno
        result1 = await agent.run("¿Cómo está el clima en Seattle?", thread=thread)
        print(f"Agente: {result1.text}")
        
        # Segundo turno - se mantiene el contexto
        result2 = await agent.run("¿Y en Portland?", thread=thread)
        print(f"Agente: {result2.text}")
        
        # Guardar ID del hilo para reanudar después
        print(f"ID de conversación: {thread.conversation_id}")

Salidas Estructuradas

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="Proporciona información del clima en formato estructurado.",
            response_format=WeatherResponse,
        )
        
        result = await agent.run("¿Clima en Seattle?")
        weather = WeatherResponse.model_validate_json(result.text)
        print(f"{weather.location}: {weather.temperature}°{weather.unit}")

Métodos del Proveedor

MétodoDescripción
create_agent()Crea un nuevo agente en el servicio Azure AI
get_agent(agent_id)Recupera un agente existente por ID
as_agent(sdk_agent)Envuelve un objeto SDK Agent (sin llamada HTTP)

Referencia Rápida de Herramientas Alojadas

HerramientaImportaciónPropósito
HostedCodeInterpreterToolfrom agent_framework import HostedCodeInterpreterToolEjecuta código Python
HostedFileSearchToolfrom agent_framework import HostedFileSearchToolBusca en vector stores
HostedWebSearchToolfrom agent_framework import HostedWebSearchToolBúsqueda web con Bing
HostedMCPToolfrom agent_framework import HostedMCPToolMCP gestionado por el servicio
MCPStreamableHTTPToolfrom agent_framework import MCPStreamableHTTPToolMCP gestionado por el cliente

Ejemplo Completo

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="Nombre de la ciudad")],
) -> str:
    """Obtiene el clima para una ubicación."""
    return f"Clima en {location}: 72°F, soleado"


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="Eres un asistente de investigación con múltiples capacidades.",
            tools=[
                get_weather,
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
                mcp_tool,
            ],
        )
        
        thread = agent.get_new_thread()
        
        # Sin streaming
        result = await agent.run(
            "Busca las mejores prácticas de Python y haz un resumen",
            thread=thread,
        )
        print(f"Respuesta: {result.text}")
        
        # Streaming
        print("\nStreaming: ", end="")
        async for chunk in agent.run_stream("Continúa con ejemplos", thread=thread):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()
        
        # Salida estructurada
        result = await agent.run(
            "Analiza los hallazgos",
            thread=thread,
            response_format=AnalysisResult,
        )
        analysis = AnalysisResult.model_validate_json(result.text)
        print(f"\nConfianza: {analysis.confidence}")


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

Convenciones

  • Usa siempre context managers asíncronos: async with provider:
  • Pasa funciones directamente al parámetro tools= (se convierten automáticamente a AIFunction)
  • Usa Annotated[type, Field(description=...)] para parámetros de funciones
  • Usa get_new_thread() para conversaciones de múltiples turnos
  • Prefiere HostedMCPTool para MCP gestionado por el servicio, MCPStreamableHTTPTool para MCP gestionado por el cliente

Mejores Prácticas

  1. Este SDK es asíncrono primero — usa async def handlers y async with en todo momento.
  2. Usa siempre context managers para clientes y credenciales asíncronas. Envuelve cada cliente en with Client(...) as client: (sincrónico) o async with Client(...) as client: (asíncrono). Para DefaultAzureCredential asíncrono de azure.identity.aio, también usa async with credential: para que los tokens y transportes se limpien.

Archivos de Referencia

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 relacionados