Communitygithub.com

SamuelChien/mega-skills-collection

Azure AI Projects SDK の ImageBasedHostedAgentDefinition を使用して、コンテナベースの Foundry エージェントを構築します。Azure AI Foundry でカスタムコンテナイメージを使用してホステッドエージェントを作成する際に使用します。

mega-skills-collection とは?

このスキルは、Azure AI Foundry でカスタムコンテナイメージを使用したホステッドエージェントを作成、管理するための手順を提供します。ImageBasedHostedAgentDefinition を利用することで、開発者はコードインタープリタや MCP ツールなどのツール、リソース割り当て(CPU/メモリ)、環境変数を含む柔軟なエージェント設定が可能です。Azure AI Projects SDK(バージョン 2.0.0b3 以降)と DefaultAzureCredential を使用した認証に対応しており、Azure Container Registry、機能ホスト、適切なアクセス許可などの前提条件を満たす必要があります。このスキルは同期および非同期(async)パターンをサポートし、よくあるエラー、ベストプラクティス、トラブルシューティングのヒントも含まれているため、プロダクション環境向けエージェント構築に役立ちます。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Azure AI ホステッドエージェント (Python)

ImageBasedHostedAgentDefinition を使用して、Azure AI Projects SDK でコンテナベースのホステッドエージェントを構築します。

インストール

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. コンテナイメージ - ビルドして Azure Container Registry (ACR) にプッシュする
  2. ACR プル許可 - プロジェクトのマネージド ID に ACR の AcrPull ロールを付与する
  3. 機能ホスト - アカウントレベルの機能ホストが 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はい完全なコンテナイメージパス (レジストリ/イメージ:タグ)
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

ツール設定

ホステッドエージェントにツールを追加します:

コードインタープリタ

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 プル許可が拒否されたプロジェクトのマネージド ID に AcrPull ロールを付与する
InvalidContainerImageイメージが見つからないACR にイメージパスとタグが存在することを確認する
CapabilityHostNotFound機能ホストが設定されていないアカウントレベルの機能ホストを作成する
ProtocolVersionNotSupported無効なプロトコルバージョンバージョン "v1" で AgentProtocol.RESPONSES を使用する

ベストプラクティス

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

関連スキル