Communitygithub.com

SamuelChien/mega-skills-collection

使用 Azure AI Projects SDK (ImageBasedHostedAgentDefinition) 建立容器化 Foundry 代理。在用於 Azure AI Foundry 中建立具有自訂容器映像的託管代理時使用。

mega-skills-collection 是什麼?

這個技能提供了一份完整的指南,教你如何使用 Azure AI Projects SDK (Python) 中的 `ImageBasedHostedAgentDefinition` 來建立容器化的託管代理。它涵蓋了從安裝必要的套件 (`azure-ai-projects>=2.0.0b3`, `azure-identity`) 到設定環境變數、驗證,以及完整工作流程的每個步驟。其主要用途是在 Azure AI Foundry 平台中,將自訂的 Docker 容器映像部署為可執行的 AI 代理。文件中詳細說明了代理設定的各個參數,包含協定版本、資源分配 (CPU/記憶體)、工具配置 (例如程式碼解譯器、MCP 工具) 和環境變數傳遞,並提供完整的同步與非同步程式碼範例。此外,它也列出了常見的錯誤訊息 (如 `ImagePullBackOff`) 及其解決方案,並強調了最佳實務,例如使用特定映像標籤而非 `latest`、最小資源起步以及從環境變數讀取機敏資訊。這個技能主要支援 Azure AI Foundry 平台,特別適合需要在受控環境中執行自訂程式碼或工具的開發者。

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

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Azure AI 託管代理 (Python)

使用 Azure AI Projects SDK 中的 ImageBasedHostedAgentDefinition 來建立基於容器的託管代理。

安裝

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

最低 SDK 版本: 需要 2.0.0b3 或更高版本以支援託管代理。

環境變數

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

先決條件

在建立託管代理之前:

  1. 容器映像 (Container Image) - 建立並推送到 Azure Container Registry (ACR)
  2. ACR 拉取權限 - 授予您專案受控身分在 ACR 上的 AcrPull 角色
  3. 能力主機 (Capability Host) - 帳戶級別的能力主機,且 enablePublicHostingEnvironment=true
  4. SDK 版本 - 確認 azure-ai-projects>=2.0.0b3

驗證

始終使用 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
)

核心工作流程

1. 匯入

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

2. 建立託管代理

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"已建立代理:{agent.name} (版本:{agent.version})")

3. 列出代理版本

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

4. 刪除代理版本

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

ImageBasedHostedAgentDefinition 參數

參數類型必填說明
container_protocol_versionslist[ProtocolVersionRecord]是代理支援的協定版本
imagestr是完整的容器映像路徑 (registry/image:tag)
cpustr否CPU 配置 (例如 "1", "2")
memorystr否記憶體配置 (例如 "2Gi", "4Gi")
toolslist[dict]否代理可用的工具
environment_variablesdict[str, str]否容器的環境變數

協定版本

container_protocol_versions 參數指定您的代理支援哪些協定:

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

# RESPONSES 協定 - 標準代理回應
container_protocol_versions=[
    ProtocolVersionRecord(protocol=AgentProtocol.RESPONSES, version="v1")
]

可用的協定:

協定說明
AgentProtocol.RESPONSES代理互動的標準回應協定

資源配置

為您的容器指定 CPU 和記憶體:

definition=ImageBasedHostedAgentDefinition(
    container_protocol_versions=[...],
    image="myregistry.azurecr.io/my-agent:latest",
    cpu="2",      # 2 個 CPU 核心
    memory="4Gi"  # 4 GiB 記憶體
)

資源限制:

資源最小值最大值預設值
CPU0.541
記憶體1Gi8Gi2Gi

工具配置

將工具新增到您的託管代理:

程式碼解譯器 (Code Interpreter)

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

MCP 工具

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

多個工具

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

環境變數

將配置傳遞給您的容器:

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

最佳實務: 永遠不要將機密資訊硬編碼。請使用環境變數或 Azure Key Vault。

完整範例

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():
    """使用自訂容器映像建立託管代理。"""
    
    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"已建立託管代理:{agent.name}")
    print(f"版本:{agent.version}")
    print(f"狀態:{agent.state}")
    
    return agent

if __name__ == "__main__":
    create_hosted_agent()

非同步模式

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():
    """非同步建立託管代理。"""
    
    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

常見錯誤

錯誤原因解決方案
ImagePullBackOffACR 拉取權限遭拒授予專案受控身分 AcrPull 角色
InvalidContainerImage找不到映像驗證 ACR 中的映像路徑和標籤是否存在
CapabilityHostNotFound未配置能力主機建立帳戶級別的能力主機
ProtocolVersionNotSupported無效的協定版本使用 AgentProtocol.RESPONSES 搭配版本 "v1"

最佳實務

  1. 為您的映像設定版本 - 在生產環境中使用特定標籤,而非 latest
  2. 最小資源 - 從最小的 CPU/記憶體開始,根據需要擴展
  3. 環境變數 - 用於所有配置,切勿硬編碼
  4. 錯誤處理 - 將代理建立包裝在 try/except 區塊中
  5. 清理 - 刪除未使用的代理版本以釋放資源

參考連結

使用時機

此技能適用於執行概述中所述的工作流程或動作。

限制

  • 僅在任務明確符合上述描述的範圍時使用此技能。
  • 請勿將輸出視為環境特定驗證、測試或專家審查的替代品。
  • 如果缺少必要的輸入、權限、安全邊界或成功標準,請停止並要求澄清。

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

相關技能