Communitygithub.com

SamuelChien/mega-skills-collection

Construa agentes do Azure AI Foundry usando o SDK Python do Microsoft Agent Framework (agent-framework-azure-ai). Use ao criar agentes persistentes com AzureAIAgentsProvider, utilizando ferramentas hospedadas (interpretador de código, busca de arquivos, busca na web), integrando servidores MCP, gerenciando threads de conversação ou implementando respostas em streaming. Abrange ferramentas de função, saídas estruturadas e agentes com múltiplas ferramentas.

O que é mega-skills-collection?

Este skill capacita desenvolvedores a construir agentes persistentes no Azure AI Foundry utilizando o Microsoft Agent Framework Python SDK. Ele é ideal para cenários que exigem agentes com estado, integração de ferramentas hospedadas (como interpretador de código, busca de arquivos e busca na web) e suporte ao protocolo MCP (Model Context Protocol). O skill cobre desde a configuração básica de autenticação com `DefaultAzureCredential` até padrões avançados como respostas em streaming, threads de conversação para múltiplas interações e saídas estruturadas com Pydantic. A implementação é totalmente assíncrona, utilizando gerenciadores de contexto (`async with`) para garantir liberação adequada de recursos. As plataformas suportadas incluem o Azure AI Agent Service, com provedor `AzureAIAgentsProvider`, e o skill demonstra como usar ferramentas de função Python, ferramentas hospedadas e ferramentas MCP (hospedadas ou gerenciadas pelo cliente) em um único agente. Para desenvolvedores que precisam de agentes confiáveis e escaláveis na nuvem Azure, este é um guia completo e prático.

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

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Agent Framework Azure Hosted Agents

Construa agentes persistentes no Azure AI Foundry usando o SDK Python do Microsoft Agent Framework.

Arquitetura

User Query → AzureAIAgentsProvider → Azure AI Agent Service (Persistente)
                    ↓
              Agent.run() / Agent.run_stream()
                    ↓
              Ferramentas: Funções | Hospedadas (Código/Busca/Web) | MCP
                    ↓
              AgentThread (persistência de conversação)

Instalação

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

# Apenas o pacote específico do Azure
pip install agent-framework-azure-ai --pre

Variáveis de Ambiente

export AZURE_AI_PROJECT_ENDPOINT="https://<projeto>.services.ai.azure.com/api/projects/<id-do-projeto>"  # Obrigatório para todos os métodos de autenticação
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"  # Obrigatório para todos os métodos de autenticação
export BING_CONNECTION_ID="seu-id-de-conexao-bing"  # Para busca na web
export AZURE_TOKEN_CREDENTIALS=prod # Obrigatório apenas se DefaultAzureCredential for usado em produção

Autenticação e Ciclo de Vida

🔑 Duas regras se aplicam a todos os exemplos de código abaixo:

  1. Prefira DefaultAzureCredential. Funciona localmente (Azure CLI / VS Code / Developer CLI) e no Azure (identidade gerenciada, identidade de carga de trabalho) sem alteração de código. Evite cadeias de conexão, chaves de conta/API — elas ignoram a auditoria e rotação do Entra.
    • Desenvolvimento local: DefaultAzureCredential funciona como está.
    • Produção: defina AZURE_TOKEN_CREDENTIALS=prod (ou AZURE_TOKEN_CREDENTIALS=<credencial_especifica>) para restringir a cadeia de credenciais apenas a credenciais seguras para produção.
  2. Envolva cada cliente em um gerenciador de contexto para que transportes HTTP, sockets e caches de token sejam liberados deterministamente:
    • Síncrono: with <Client>(...) as client:
    • Assíncrono: async with <Client>(...) as client: e async with DefaultAzureCredential() as credential: (de azure.identity.aio)

Os trechos podem abreviar esta configuração, mas o código de produção deve sempre seguir ambas as regras.

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

# Desenvolvimento
credential = AzureCliCredential()

# Produção
# Desenvolvimento local: DefaultAzureCredential. Produção: defina AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credencial_especifica>
credential = DefaultAzureCredential(require_envvar=True)
# Ou use uma credencial específica diretamente em produção:
# Consulte https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

Fluxo de Trabalho 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="MeuAgente",
            instructions="Você é um assistente útil.",
        )
        
        result = await agent.run("Olá!")
        print(result.text)

asyncio.run(main())

Agente com Ferramentas de Função

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="Nome da cidade para obter o clima")],
) -> str:
    """Obter o clima atual para um local."""
    return f"Clima em {location}: 22°C, ensolarado"

def get_current_time() -> str:
    """Obter a hora UTC atual."""
    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="AgenteClima",
            instructions="Você ajuda com consultas sobre clima e hora.",
            tools=[get_weather, get_current_time],  # Passe funções diretamente
        )
        
        result = await agent.run("Qual é o clima em Seattle?")
        print(result.text)

Agente com Ferramentas Hospedadas

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="AgenteMultiFerramenta",
            instructions="Você pode executar código, pesquisar arquivos e pesquisar na web.",
            tools=[
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
            ],
        )
        
        result = await agent.run("Calcule o fatorial de 20 em Python")
        print(result.text)

Respostas em Streaming

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentsProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(
            name="AgenteStreaming",
            instructions="Você é um assistente útil.",
        )
        
        print("Agente: ", end="", flush=True)
        async for chunk in agent.run_stream("Conte-me uma história curta"):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()

Threads de Conversação

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="AgenteChat",
            instructions="Você é um assistente útil.",
            tools=[get_weather],
        )
        
        # Criar thread para persistência da conversação
        thread = agent.get_new_thread()
        
        # Primeira interação
        result1 = await agent.run("Qual é o clima em Seattle?", thread=thread)
        print(f"Agente: {result1.text}")
        
        # Segunda interação - o contexto é mantido
        result2 = await agent.run("E em Portland?", thread=thread)
        print(f"Agente: {result2.text}")
        
        # Salvar ID da thread para retomada posterior
        print(f"ID da Conversação: {thread.conversation_id}")

Saídas Estruturadas

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="AgenteEstruturado",
            instructions="Forneça informações climáticas em formato estruturado.",
            response_format=WeatherResponse,
        )
        
        result = await agent.run("Clima em Seattle?")
        weather = WeatherResponse.model_validate_json(result.text)
        print(f"{weather.location}: {weather.temperature}°{weather.unit}")

Métodos do Provedor

MétodoDescrição
create_agent()Criar novo agente no serviço Azure AI
get_agent(agent_id)Recuperar agente existente por ID
as_agent(sdk_agent)Envolver objeto Agent do SDK (sem chamada HTTP)

Referência Rápida de Ferramentas Hospedadas

FerramentaImportaçãoPropósito
HostedCodeInterpreterToolfrom agent_framework import HostedCodeInterpreterToolExecutar código Python
HostedFileSearchToolfrom agent_framework import HostedFileSearchToolPesquisar em armazenamentos vetoriais
HostedWebSearchToolfrom agent_framework import HostedWebSearchToolBusca na web Bing
HostedMCPToolfrom agent_framework import HostedMCPToolMCP gerenciado pelo serviço
MCPStreamableHTTPToolfrom agent_framework import MCPStreamableHTTPToolMCP gerenciado pelo cliente

Exemplo 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="Nome da cidade")],
) -> str:
    """Obter clima para um local."""
    return f"Clima em {location}: 22°C, ensolarado"


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="AssistentePesquisa",
            instructions="Você é um assistente de pesquisa com múltiplas capacidades.",
            tools=[
                get_weather,
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
                mcp_tool,
            ],
        )
        
        thread = agent.get_new_thread()
        
        # Sem streaming
        result = await agent.run(
            "Pesquise por melhores práticas em Python e resuma",
            thread=thread,
        )
        print(f"Resposta: {result.text}")
        
        # Streaming
        print("\nStreaming: ", end="")
        async for chunk in agent.run_stream("Continue com exemplos", thread=thread):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()
        
        # Saída estruturada
        result = await agent.run(
            "Analise os resultados",
            thread=thread,
            response_format=AnalysisResult,
        )
        analysis = AnalysisResult.model_validate_json(result.text)
        print(f"\nConfiança: {analysis.confidence}")


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

Convenções

  • Sempre use gerenciadores de contexto assíncronos: async with provider:
  • Passe funções diretamente para o parâmetro tools= (convertidas automaticamente para AIFunction)
  • Use Annotated[type, Field(description=...)] para parâmetros de função
  • Use get_new_thread() para conversas de múltiplas interações
  • Prefira HostedMCPTool para MCP gerenciado pelo serviço, MCPStreamableHTTPTool para MCP gerenciado pelo cliente

Melhores Práticas

  1. Este SDK é assíncrono primeiro — use manipuladores async def e async with em todo o código.
  2. Sempre use gerenciadores de contexto para clientes e credenciais assíncronas. Envolva cada cliente em with Client(...) as client: (síncrono) ou async with Client(...) as client: (assíncrono). Para DefaultAzureCredential assíncrono de azure.identity.aio, também use async with credential: para que tokens e transportes sejam limpos.

Arquivos de Referência

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".

Habilidades Relacionadas