Communitygithub.com

SamuelChien/mega-skills-collection

Erstelle persistente Azure AI Foundry Agents mit dem Microsoft Agent Framework Python SDK (agent-framework-azure-ai). Verwende dies beim Erstellen von Agents mit AzureAIAgentsProvider, gehosteten Tools (Code Interpreter, Dateisuche, Websuche), MCP-Servern, Konversationsthreads oder gestreamten Antworten. Deckt Funktions-Tools, strukturierte Ausgaben und Multi-Tool-Agents ab.

Was ist mega-skills-collection?

Dieses Skill bietet eine umfassende Anleitung, um persistente KI-Agenten auf Azure AI Foundry mit dem Microsoft Agent Framework Python SDK zu erstellen und zu verwalten. Es ist für Entwickler konzipiert, die Agents mit AzureAIAgentsProvider erstellen möchten, und unterstützt sowohl sync- als auch async-Workflows. Der Skill erklärt die grundlegende Architektur, Authentifizierung mit DefaultAzureCredential und die Verwendung von Kontextmanagern. Er behandelt die Erstellung von Agents mit Funktions-Tools, gehosteten Tools (Code Interpreter, Dateisuche, Websuche) und die Integration von MCP-Servern. Zudem wird gezeigt, wie Konversationsthreads für Mehrfachgespräche verwendet, gestreamte Antworten implementiert und strukturierte Ausgaben mit Pydantic-Modellen erzielt werden können. Der Skill deckt sowohl die clientseitig als auch dienstseitig verwalteten MCP-Integrationen ab. Die Dokumentation enthält vollständige Codebeispiele, einen Schnellüberblick über die verfügbaren gehosteten Tools und eine Tabelle der Provider-Methoden. Best Practices wie die Verwendung von DefaultAzureCredential und Kontextmanagern werden hervorgehoben, um sichere und wartbare Implementierungen zu gewährleisten.

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

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Agent Framework Azure Gehostete Agents

Erstelle persistente Agents auf Azure AI Foundry mit dem Microsoft Agent Framework Python SDK.

Architektur

Benutzeranfrage → AzureAIAgentsProvider → Azure AI Agent Service (Persistent)
                    ↓
              Agent.run() / Agent.run_stream()
                    ↓
              Tools: Funktionen | Gehostet (Code/Suche/Web) | MCP
                    ↓
              AgentThread (Konversationspersistenz)

Installation

# Vollständiges Framework (empfohlen)
pip install agent-framework --pre

# Oder nur Azure-spezifisches Paket
pip install agent-framework-azure-ai --pre

Umgebungsvariablen

export AZURE_AI_PROJECT_ENDPOINT="https://<project>.services.ai.azure.com/api/projects/<project-id>"  # Erforderlich für alle Authentifizierungsmethoden
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"  # Erforderlich für alle Authentifizierungsmethoden
export BING_CONNECTION_ID="your-bing-connection-id"  # Für Websuche
export AZURE_TOKEN_CREDENTIALS=prod # Nur erforderlich, wenn DefaultAzureCredential in der Produktion verwendet wird

Authentifizierung & Lebenszyklus

🔑 Zwei Regeln gelten für jedes untenstehende Codebeispiel:

  1. Bevorzuge DefaultAzureCredential. Es funktioniert lokal (Azure CLI / VS Code / Developer CLI) und in Azure (Managed Identity, Workload Identity) ohne Codeänderung. Vermeide Verbindungszeichenfolgen, Konto-/API-Schlüssel – sie umgehen Entra-Überprüfung und Rotation.
    • Lokale Entwicklung: DefaultAzureCredential funktioniert sofort.
    • Produktion: Setze AZURE_TOKEN_CREDENTIALS=prod (oder AZURE_TOKEN_CREDENTIALS=<spezifische_anmeldeinformation>), um die Anmeldeinformationskette auf produktionssichere Anmeldeinformationen zu beschränken.
  2. Wickle jeden Client in einen Kontextmanager ein, damit HTTP-Transports, Sockets und Token-Caches deterministisch freigegeben werden:
    • Synchron: with <Client>(...) as client:
    • Asynchron: async with <Client>(...) as client: und async with DefaultAzureCredential() as credential: (aus azure.identity.aio)

Codeausschnitte können diesen Aufbau verkürzen, aber Produktionscode sollte immer beiden Regeln folgen.

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

# Entwicklung
credential = AzureCliCredential()

# Produktion
# Lokale Entwicklung: DefaultAzureCredential. Produktion: Setze AZURE_TOKEN_CREDENTIALS=prod oder AZURE_TOKEN_CREDENTIALS=<spezifische_anmeldeinformation>
credential = DefaultAzureCredential(require_envvar=True)
# Oder verwende direkt spezifische Anmeldeinformationen in der Produktion:
# Siehe https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()

Kern-Workflow

Basis-Agent

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="Du bist ein hilfreicher Assistent.",
        )
        
        result = await agent.run("Hallo!")
        print(result.text)

asyncio.run(main())

Agent mit Funktions-Tools

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="Stadtname, für den das Wetter abgerufen werden soll")],
) -> str:
    """Holt das aktuelle Wetter für einen Ort."""
    return f"Wetter in {location}: 72°F, sonnig"

def get_current_time() -> str:
    """Holt die aktuelle UTC-Zeit."""
    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="Du hilfst bei Wetter- und Zeitanfragen.",
            tools=[get_weather, get_current_time],  # Funktionen direkt übergeben
        )
        
        result = await agent.run("Wie ist das Wetter in Seattle?")
        print(result.text)

Agent mit gehosteten Tools

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="Du kannst Code ausführen, Dateien durchsuchen und das Web durchsuchen.",
            tools=[
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
            ],
        )
        
        result = await agent.run("Berechne die Fakultät von 20 in Python")
        print(result.text)

Streamende Antworten

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentsProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(
            name="StreamingAgent",
            instructions="Du bist ein hilfreicher Assistent.",
        )
        
        print("Agent: ", end="", flush=True)
        async for chunk in agent.run_stream("Erzähl mir eine kurze Geschichte"):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()

Konversationsthreads

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="Du bist ein hilfreicher Assistent.",
            tools=[get_weather],
        )
        
        # Thread für Konversationspersistenz erstellen
        thread = agent.get_new_thread()
        
        # Erste Runde
        result1 = await agent.run("Wie ist das Wetter in Seattle?", thread=thread)
        print(f"Agent: {result1.text}")
        
        # Zweite Runde - Kontext bleibt erhalten
        result2 = await agent.run("Und was ist mit Portland?", thread=thread)
        print(f"Agent: {result2.text}")
        
        # Thread-ID für späteren Wiederaufnahme speichern
        print(f"Konversations-ID: {thread.conversation_id}")

Strukturierte Ausgaben

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="Gib Wetterinformationen in strukturiertem Format aus.",
            response_format=WeatherResponse,
        )
        
        result = await agent.run("Wetter in Seattle?")
        weather = WeatherResponse.model_validate_json(result.text)
        print(f"{weather.location}: {weather.temperature}°{weather.unit}")

Provider-Methoden

MethodeBeschreibung
create_agent()Neuen Agenten im Azure AI Service erstellen
get_agent(agent_id)Vorhandenen Agenten anhand der ID abrufen
as_agent(sdk_agent)SDK-Agentenobjekt wrappen (kein HTTP-Aufruf)

Kurzübersicht gehostete Tools

ToolImportZweck
HostedCodeInterpreterToolfrom agent_framework import HostedCodeInterpreterToolPython-Code ausführen
HostedFileSearchToolfrom agent_framework import HostedFileSearchToolVektorspeicher durchsuchen
HostedWebSearchToolfrom agent_framework import HostedWebSearchToolBing-Websuche
HostedMCPToolfrom agent_framework import HostedMCPToolDienstseitig verwaltetes MCP
MCPStreamableHTTPToolfrom agent_framework import MCPStreamableHTTPToolClientseitig verwaltetes MCP

Vollständiges Beispiel

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="Stadtname")],
) -> str:
    """Holt das Wetter für einen Ort."""
    return f"Wetter in {location}: 72°F, sonnig"


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="Du bist ein Forschungsassistent mit mehreren Fähigkeiten.",
            tools=[
                get_weather,
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
                mcp_tool,
            ],
        )
        
        thread = agent.get_new_thread()
        
        # Nicht-streamend
        result = await agent.run(
            "Suche nach Python-Best Practices und fasse zusammen",
            thread=thread,
        )
        print(f"Antwort: {result.text}")
        
        # Streamend
        print("\nStreamend: ", end="")
        async for chunk in agent.run_stream("Fahre mit Beispielen fort", thread=thread):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()
        
        # Strukturierte Ausgabe
        result = await agent.run(
            "Analysiere die Ergebnisse",
            thread=thread,
            response_format=AnalysisResult,
        )
        analysis = AnalysisResult.model_validate_json(result.text)
        print(f"\nKonfidenz: {analysis.confidence}")


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

Konventionen

  • Verwende immer async-Kontextmanager: async with provider:
  • Übergebe Funktionen direkt an den Parameter tools= (automatisch in AIFunction konvertiert)
  • Verwende Annotated[type, Field(description=...)] für Funktionsparameter
  • Verwende get_new_thread() für Mehrfachgespräche
  • Bevorzuge HostedMCPTool für dienstseitig verwaltetes MCP, MCPStreamableHTTPTool für clientseitig verwaltetes MCP

Best Practices

  1. Dieses SDK ist async-first – verwende async def-Handler und überall async with.
  2. Verwende immer Kontextmanager für Clients und async-Anmeldeinformationen. Wickle jeden Client in with Client(...) as client: (synchron) oder async with Client(...) as client: (asynchron) ein. Für async DefaultAzureCredential aus azure.identity.aio verwende ebenfalls async with credential:, damit Tokens und Transports bereinigt werden.

Referenzdateien

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

Verwandte Skills