Communitygithub.com

Azure AI Gehostete Agents (Python)

Erstellen Sie containerbasierte Foundry-Agents mit dem Azure AI Projects SDK (ImageBasedHostedAgentDefinition). Verwenden Sie dies, wenn Sie gehostete Agents mit benutzerdefinierten Container-Images in Azure AI Foundry erstellen möchten.

Was ist Azure AI Gehostete Agents (Python)?

Diese Fähigkeit ermöglicht es Entwicklern, containerbasierte, gehostete Agents mit der `ImageBasedHostedAgentDefinition` aus dem Azure AI Projects SDK zu erstellen und zu verwalten. Sie ist ideal für die Bereitstellung benutzerdefinierter KI-Agenten in Azure AI Foundry, die in isolierten Containern mit spezifischen Ressourcen (CPU, Arbeitsspeicher) und Tools wie Code-Interpreter oder MCP-Servern ausgeführt werden. Das SDK unterstützt sowohl synchrone als auch asynchrone (async) Muster und erfordert eine Mindestversion von `2.0.0b3`. Voraussetzung sind ein Container-Image in einer Azure Container Registry (ACR) mit entsprechenden Zugriffsberechtigungen, eine Capability Host mit aktivierter öffentlicher Hosting-Umgebung sowie die Authentifizierung über `DefaultAzureCredential`. Die Fähigkeit deckt den gesamten Lebenszyklus ab: Erstellen, Auflisten und Löschen von Agent-Versionen, Konfiguration von Umgebungsvariablen und die Behandlung häufiger Fehler mithilfe von bewährten Methoden.

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

In Ihrer bevorzugten KI fragen

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

Dokumentation

Was macht Azure AI Gehostete Agents (Python)?

Erstellen Sie containerbasierte, gehostete Agents mit ImageBasedHostedAgentDefinition aus dem Azure AI Projects SDK.

Installation

pip install azure-ai-projects>=2.0.0b3 azure-identity

Mindest-SDK-Version: 2.0.0b3 oder höher erforderlich für die Unterstützung gehosteter Agents.

Umgebungsvariablen

AZURE_AI_PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>

Voraussetzungen

Bevor Sie gehostete Agents erstellen:

  1. Container-Image – Erstellen und veröffentlichen Sie es in einer Azure Container Registry (ACR)
  2. ACR Pull-Berechtigungen – Weisen Sie der verwalteten Identität Ihres Projekts die Rolle AcrPull auf der ACR zu
  3. Capability Host – Capability Host auf Kontoebene mit enablePublicHostingEnvironment=true
  4. SDK-Version – Stellen Sie sicher, dass azure-ai-projects>=2.0.0b3 installiert ist

Authentifizierung

Verwenden Sie immer DefaultAzureCredential:

from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient

credential = DefaultAzureCredential()
client = AIProjectClient(
    endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
    credential=credential
)

Kern-Workflow

1. Importe

import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    ImageBasedHostedAgentDefinition,
    ProtocolVersionRecord,
    AgentProtocol,
)

2. Gehosteten Agent erstellen

client = AIProjectClient(
    endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
    credential=DefaultAzureCredential()
)

agent = client.agents.create_version(
    agent_name="my-hosted-agent",
    definition=ImageBasedHostedAgentDefinition(
        container_protocol_versions=[
            ProtocolVersionRecord(protocol=AgentProtocol.RESPONSES, version="v1")
        ],
        cpu="1",
        memory="2Gi",
        image="myregistry.azurecr.io/my-agent:latest",
        tools=[{"type": "code_interpreter"}],
        environment_variables={
            "AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],
            "MODEL_NAME": "gpt-4o-mini"
        }
    )
)

print(f"Erstellter Agent: {agent.name} (Version: {agent.version})")

3. Agent-Versionen auflisten

versions = client.agents.list_versions(agent_name="my-hosted-agent")
for version in versions:
    print(f"Version: {version.version}, Status: {version.state}")

4. Agent-Version löschen

client.agents.delete_version(
    agent_name="my-hosted-agent",
    version=agent.version
)

Parameter von ImageBasedHostedAgentDefinition

ParameterTypErforderlichBeschreibung
container_protocol_versionslist[ProtocolVersionRecord]JaVom Agent unterstützte Protokollversionen
imagestrJaVollständiger Container-Image-Pfad (Registry/Image:Tag)
cpustrNeinCPU-Zuweisung (z. B. "1", "2")
memorystrNeinArbeitsspeicherzuweisung (z. B. "2Gi", "4Gi")
toolslist[dict]NeinDem Agent verfügbare Tools
environment_variablesdict[str, str]NeinUmgebungsvariablen für den Container

Protokollversionen

Der Parameter container_protocol_versions gibt an, welche Protokolle Ihr Agent unterstützt:

from azure.ai.projects.models import ProtocolVersionRecord, AgentProtocol

# RESPONSES-Protokoll – Standard-Agent-Antworten
container_protocol_versions=[
    ProtocolVersionRecord(protocol=AgentProtocol.RESPONSES, version="v1")
]

Verfügbare Protokolle:

ProtokollBeschreibung
AgentProtocol.RESPONSESStandard-Antwortprotokoll für Agent-Interaktionen

Ressourcenzuweisung

Geben Sie CPU und Arbeitsspeicher für Ihren Container an:

definition=ImageBasedHostedAgentDefinition(
    container_protocol_versions=[...],
    image="myregistry.azurecr.io/my-agent:latest",
    cpu="2",      # 2 CPU-Kerne
    memory="4Gi"  # 4 GiB Arbeitsspeicher
)

Ressourcengrenzen:

RessourceMinMaxStandard
CPU0,541
Arbeitsspeicher1Gi8Gi2Gi

Tool-Konfiguration

Fügen Sie Ihrem gehosteten Agent Tools hinzu:

Code-Interpreter

tools=[{"type": "code_interpreter"}]

MCP-Tools

tools=[
    {"type": "code_interpreter"},
    {
        "type": "mcp",
        "server_label": "my-mcp-server",
        "server_url": "https://my-mcp-server.example.com"
    }
]

Mehrere Tools

tools=[
    {"type": "code_interpreter"},
    {"type": "file_search"},
    {
        "type": "mcp",
        "server_label": "custom-tool",
        "server_url": "https://custom-tool.example.com"
    }
]

Umgebungsvariablen

Übergeben Sie Konfiguration an Ihren Container:

environment_variables={
    "AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],
    "MODEL_NAME": "gpt-4o-mini",
    "LOG_LEVEL": "INFO",
    "CUSTOM_CONFIG": "value"
}

Bewährte Methode: Härten Sie Geheimnisse niemals fest ein. Verwenden Sie Umgebungsvariablen oder Azure Key Vault.

Vollständiges Beispiel

import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    ImageBasedHostedAgentDefinition,
    ProtocolVersionRecord,
    AgentProtocol,
)

def create_hosted_agent():
    """Erstellt einen gehosteten Agent mit einem benutzerdefinierten Container-Image."""
    
    client = AIProjectClient(
        endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
        credential=DefaultAzureCredential()
    )
    
    agent = client.agents.create_version(
        agent_name="data-processor-agent",
        definition=ImageBasedHostedAgentDefinition(
            container_protocol_versions=[
                ProtocolVersionRecord(
                    protocol=AgentProtocol.RESPONSES,
                    version="v1"
                )
            ],
            image="myregistry.azurecr.io/data-processor:v1.0",
            cpu="2",
            memory="4Gi",
            tools=[
                {"type": "code_interpreter"},
                {"type": "file_search"}
            ],
            environment_variables={
                "AZURE_AI_PROJECT_ENDPOINT": os.environ["AZURE_AI_PROJECT_ENDPOINT"],
                "MODEL_NAME": "gpt-4o-mini",
                "MAX_RETRIES": "3"
            }
        )
    )
    
    print(f"Erstellter gehosteter Agent: {agent.name}")
    print(f"Version: {agent.version}")
    print(f"Status: {agent.state}")
    
    return agent

if __name__ == "__main__":
    create_hosted_agent()

Asynchrones Muster

import os
from azure.identity.aio import DefaultAzureCredential
from azure.ai.projects.aio import AIProjectClient
from azure.ai.projects.models import (
    ImageBasedHostedAgentDefinition,
    ProtocolVersionRecord,
    AgentProtocol,
)

async def create_hosted_agent_async():
    """Erstellt einen gehosteten Agent asynchron."""
    
    async with DefaultAzureCredential() as credential:
        async with AIProjectClient(
            endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
            credential=credential
        ) as client:
            agent = await client.agents.create_version(
                agent_name="async-agent",
                definition=ImageBasedHostedAgentDefinition(
                    container_protocol_versions=[
                        ProtocolVersionRecord(
                            protocol=AgentProtocol.RESPONSES,
                            version="v1"
                        )
                    ],
                    image="myregistry.azurecr.io/async-agent:latest",
                    cpu="1",
                    memory="2Gi"
                )
            )
            return agent

Häufige Fehler

FehlerUrsacheLösung
ImagePullBackOffACR Pull-Berechtigung verweigertWeisen Sie der verwalteten Identität des Projekts die Rolle AcrPull zu
InvalidContainerImageImage nicht gefundenÜberprüfen Sie, ob Image-Pfad und Tag in der ACR existieren
CapabilityHostNotFoundKein Capability Host konfiguriertErstellen Sie einen Capability Host auf Kontoebene
ProtocolVersionNotSupportedUngültige ProtokollversionVerwenden Sie AgentProtocol.RESPONSES mit der Version "v1"

Bewährte Methoden

  1. Images versionieren – Verwenden Sie in der Produktion spezifische Tags, nicht latest
  2. Minimale Ressourcen – Beginnen Sie mit minimaler CPU/Arbeitsspeicher und skalieren Sie bei Bedarf hoch
  3. Umgebungsvariablen – Verwenden Sie diese für die gesamte Konfiguration; härten Sie nichts fest ein
  4. Fehlerbehandlung – Umgeben Sie die Agent-Erstellung mit try/except-Blöcken
  5. Bereinigung – Löschen Sie nicht verwendete Agent-Versionen, um Ressourcen freizugeben

Referenzlinks

Wann verwenden

Diese Fähigkeit ist anwendbar, um den in der Übersicht beschriebenen Workflow oder die darin beschriebenen Aktionen auszuführen.

Einschränkungen

  • Verwenden Sie diese Fähigkeit nur, wenn die Aufgabe eindeutig dem oben beschriebenen Umfang entspricht.
  • Behandeln Sie die Ausgabe nicht als Ersatz für eine umgebungsspezifische Validierung, Tests oder eine fachliche Überprüfung.
  • Halten Sie an und fragen Sie nach, wenn erforderliche Eingaben, Berechtigungen, Sicherheitsgrenzen oder Erfolgskriterien fehlen.

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