Communitygithub.com

SamuelChien/mega-skills-collection

使用 Azure AI Projects SDK 构建基于容器的 Foundry Agent。在需要创建带有自定义容器镜像的托管代理时使用。

mega-skills-collection 是什么?

此技能专门用于在 Azure AI Foundry 中通过 `ImageBasedHostedAgentDefinition` 创建基于容器的托管 Agent。它适用于 Azure AI Projects SDK,要求 SDK 版本 >= 2.0.0b3,并依赖 `DefaultAzureCredential` 进行认证。技能提供完整的 Python 代码示例,涵盖托管 Agent 的核心生命周期:创建版本、列出版本和删除版本。详细说明参数配置,包括容器协议版本(推荐 `AgentProtocol.RESPONSES`,版本 v1)、容器镜像路径、资源分配(CPU 0.5 到 4 核,内存 1Gi 到 8Gi)以及工具集成(如代码解释器、文件搜索和 MCP 工具)。此外还提供了异步实现模式、常见错误排查(如 `ImagePullBackOff`、`InvalidContainerImage`)和最佳实践(镜像版本化、最小资源起步、避免硬编码秘密)。适用于开发者在 Azure AI Foundry 中部署自定义逻辑的托管 Agent 场景。

兼容平台~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 托管 Agent (Python)

使用 Azure AI Projects SDK 中的 ImageBasedHostedAgentDefinition 构建基于容器的托管 Agent。

安装

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

最低 SDK 版本: 2.0.0b3 或更高版本以支持托管 Agent。

环境变量

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

先决条件

创建托管 Agent 前需完成:

  1. 容器镜像 - 构建并推送到 Azure 容器注册表 (ACR)
  2. ACR 拉取权限 - 为项目的托管标识授予 ACR 的 AcrPull 角色
  3. Capability Host - 账户级别的 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. 创建托管 Agent

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

3. 列出 Agent 版本

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

4. 删除 Agent 版本

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

ImageBasedHostedAgentDefinition 参数

参数类型必需描述
container_protocol_versionslist[ProtocolVersionRecord]是Agent 支持的协议版本
imagestr是完整容器镜像路径 (registry/image:tag)
cpustr否CPU 分配 (例如 "1", "2")
memorystr否内存分配 (例如 "2Gi", "4Gi")
toolslist[dict]否Agent 可用的工具
environment_variablesdict[str, str]否容器的环境变量

协议版本

container_protocol_versions 参数指定 Agent 支持的协议:

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

# RESPONSES 协议 - 标准 Agent 响应
container_protocol_versions=[
    ProtocolVersionRecord(protocol=AgentProtocol.RESPONSES, version="v1")
]

可用协议:

协议描述
AgentProtocol.RESPONSES用于 Agent 交互的标准响应协议

资源分配

指定容器的 CPU 和内存:

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

资源限制:

资源最小值最大值默认值
CPU0.541
内存1Gi8Gi2Gi

工具配置

向托管 Agent 添加工具:

代码解释器

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():
    """使用自定义容器镜像创建托管 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: {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():
    """异步创建托管 Agent。"""
    
    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未配置 Capability Host创建账户级别的 Capability Host
ProtocolVersionNotSupported无效的协议版本使用 AgentProtocol.RESPONSES 及版本 "v1"

最佳实践

  1. 版本化镜像 - 在生产环境中使用具体标签,而非 latest
  2. 最小资源 - 从最小的 CPU/内存开始,根据需求扩展
  3. 环境变量 - 用于所有配置,切勿硬编码
  4. 错误处理 - 将 Agent 创建包裹在 try/except 块中
  5. 清理 - 删除未使用的 Agent 版本以释放资源

参考链接

使用时机

本技能适用于执行概述中描述的工作流或操作。

限制

  • 仅当任务明确符合上述范围时使用本技能。
  • 请勿将输出视为特定环境验证、测试或专家审查的替代品。
  • 如果缺少必需的输入、权限、安全边界或成功标准,请停止并请求澄清。

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

相关技能