Communitygithub.com

SamuelChien/mega-skills-collection

Microsoft Agent Framework Python SDK(agent-framework-azure-ai)を使用して、Azure AI Foundry 上に永続的な AI エージェントを構築します。AzureAIAgentsProvider を用いたエージェント作成、ホステッドツール(コードインタプリタ、ファイル検索、Web 検索)の利用、MCP サーバーの統合、会話スレッドの管理、ストリーミング応答の実装をカバーします。ファンクションツール、構造化出力、マルチツールエージェントにも対応しています。

mega-skills-collection とは?

このスキルは、Microsoft の Agent Framework Python SDK(`agent-framework-azure-ai`)を使用して、Azure AI Foundry 上で永続的な AI エージェントを構築するための包括的なガイドです。Azure AI エージェントサービス上で永続的なエージェントを作成・管理するための `AzureAIAgentsProvider` を中心としたアーキテクチャを提供します。開発者は、関数ツール、ホステッドツール(コードインタプリタ、ファイル検索、Bing Web 検索)、MCP サーバーツールを組み込むことができ、また会話スレッドを使用したマルチターン対話やストリーミング応答もサポートしています。さらに、Pydantic モデルを使用した構造化出力にも対応しており、エージェントの応答を型安全に処理できます。認証には `DefaultAzureCredential` を推奨し、ローカル開発から本番環境へのスムーズな移行を実現します。

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

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

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

ドキュメント

Agent Framework Azure ホステッドエージェント

Microsoft Agent Framework Python SDK を使用して、Azure AI Foundry 上に永続的なエージェントを構築します。

アーキテクチャ

ユーザークエリ → AzureAIAgentsProvider → Azure AI エージェントサービス (永続的)
                    ↓
              Agent.run() / Agent.run_stream()
                    ↓
              ツール: 関数 | ホステッド (コード/検索/Web) | MCP
                    ↓
              AgentThread (会話の永続化)

インストール

# フルフレームワーク (推奨)
pip install agent-framework --pre

# Azure 専用パッケージのみ
pip install agent-framework-azure-ai --pre

環境変数

export AZURE_AI_PROJECT_ENDPOINT="https://<project>.services.ai.azure.com/api/projects/<project-id>"  # すべての認証方法で必須
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"  # すべての認証方法で必須
export BING_CONNECTION_ID="your-bing-connection-id"  # Web 検索用
export AZURE_TOKEN_CREDENTIALS=prod # 本番環境で DefaultAzureCredential を使用する場合のみ必須

認証とライフサイクル

🔑 以下のすべてのコードサンプルに適用される2つのルール:

  1. DefaultAzureCredential を推奨します。 ローカル (Azure CLI / VS Code / Developer CLI) と Azure (マネージド ID、ワークロード ID) の両方でコード変更なしに動作します。接続文字列やアカウント/API キーは Entra の監査とローテーションをバイパスするため避けてください。
    • ローカル開発: DefaultAzureCredential はそのまま使用できます。
    • 本番環境: AZURE_TOKEN_CREDENTIALS=prod (または AZURE_TOKEN_CREDENTIALS=<特定の資格情報>) を設定して、資格情報チェーンを本番環境で安全な資格情報に制限します。
  2. すべてのクライアントをコンテキストマネージャーでラップ して、HTTP トランスポート、ソケット、トークンキャッシュが確定的に解放されるようにします:
    • 同期: with <Client>(...) as client:
    • 非同期: async with <Client>(...) as client: かつ async with DefaultAzureCredential() as credential: (azure.identity.aio より)

スニペットではこの設定を省略する場合がありますが、本番コードでは常に両方のルールに従う必要があります。

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

# 開発環境
credential = AzureCliCredential()

# 本番環境
# ローカル開発: DefaultAzureCredential。本番: AZURE_TOKEN_CREDENTIALS=prod または AZURE_TOKEN_CREDENTIALS=<特定の資格情報> を設定
credential = DefaultAzureCredential(require_envvar=True)
# または本番環境で特定の資格情報を直接使用:
# https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes を参照
# credential = ManagedIdentityCredential()

コアワークフロー

基本エージェント

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="あなたは役立つアシスタントです。",
        )
        
        result = await agent.run("こんにちは!")
        print(result.text)

asyncio.run(main())

関数ツールを持つエージェント

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="天気を取得する都市名")],
) -> str:
    """指定された場所の現在の天気を取得します。"""
    return f"{location}の天気: 22°C, 晴れ"

def get_current_time() -> str:
    """現在のUTC時刻を取得します。"""
    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="あなたは天気と時刻の質問に答えます。",
            tools=[get_weather, get_current_time],  # 関数を直接渡す
        )
        
        result = await agent.run("東京の天気は?")
        print(result.text)

ホステッドツールを持つエージェント

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="あなたはコードを実行し、ファイルを検索し、Webを検索できます。",
            tools=[
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
            ],
        )
        
        result = await agent.run("Pythonで20の階乗を計算してください")
        print(result.text)

ストリーミング応答

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentsProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(
            name="StreamingAgent",
            instructions="あなたは役立つアシスタントです。",
        )
        
        print("エージェント: ", end="", flush=True)
        async for chunk in agent.run_stream("短い物語を聞かせてください"):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()

会話スレッド

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="あなたは役立つアシスタントです。",
            tools=[get_weather],
        )
        
        # 会話の永続化のためにスレッドを作成
        thread = agent.get_new_thread()
        
        # 最初のターン
        result1 = await agent.run("東京の天気は?", thread=thread)
        print(f"エージェント: {result1.text}")
        
        # 2番目のターン - コンテキストが維持される
        result2 = await agent.run("大阪はどうですか?", thread=thread)
        print(f"エージェント: {result2.text}")
        
        # 後で再開するためにスレッドIDを保存
        print(f"会話ID: {thread.conversation_id}")

構造化出力

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="構造化形式で天気情報を提供してください。",
            response_format=WeatherResponse,
        )
        
        result = await agent.run("東京の天気は?")
        weather = WeatherResponse.model_validate_json(result.text)
        print(f"{weather.location}: {weather.temperature}°{weather.unit}")

プロバイダーメソッド

メソッド説明
create_agent()Azure AI サービスに新しいエージェントを作成
get_agent(agent_id)ID で既存のエージェントを取得
as_agent(sdk_agent)SDK エージェントオブジェクトをラップ (HTTP 呼び出しなし)

ホステッドツールクイックリファレンス

ツールインポート目的
HostedCodeInterpreterToolfrom agent_framework import HostedCodeInterpreterToolPython コードを実行
HostedFileSearchToolfrom agent_framework import HostedFileSearchToolベクターストアを検索
HostedWebSearchToolfrom agent_framework import HostedWebSearchToolBing Web 検索
HostedMCPToolfrom agent_framework import HostedMCPToolサービス管理型 MCP
MCPStreamableHTTPToolfrom agent_framework import MCPStreamableHTTPToolクライアント管理型 MCP

完全な例

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="都市名")],
) -> str:
    """場所の天気を取得します。"""
    return f"{location}の天気: 22°C, 晴れ"


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="あなたは複数の機能を持つリサーチアシスタントです。",
            tools=[
                get_weather,
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
                mcp_tool,
            ],
        )
        
        thread = agent.get_new_thread()
        
        # 非ストリーミング
        result = await agent.run(
            "Pythonのベストプラクティスを検索して要約してください",
            thread=thread,
        )
        print(f"応答: {result.text}")
        
        # ストリーミング
        print("\nストリーミング: ", end="")
        async for chunk in agent.run_stream("例を続けてください", thread=thread):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()
        
        # 構造化出力
        result = await agent.run(
            "調査結果を分析してください",
            thread=thread,
            response_format=AnalysisResult,
        )
        analysis = AnalysisResult.model_validate_json(result.text)
        print(f"\n信頼度: {analysis.confidence}")


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

規約

  • 常に非同期コンテキストマネージャーを使用: async with provider:
  • 関数を tools= パラメーターに直接渡す (自動的に AIFunction に変換されます)
  • 関数パラメーターには Annotated[type, Field(description=...)] を使用する
  • マルチターン会話には get_new_thread() を使用する
  • サービス管理型 MCP には HostedMCPTool、クライアント管理型 MCP には MCPStreamableHTTPTool を推奨

ベストプラクティス

  1. この SDK は非同期ファーストです — ハンドラーには async def を、全体で async with を使用してください。
  2. クライアントと非同期資格情報には常にコンテキストマネージャーを使用してください。 すべてのクライアントを with Client(...) as client: (同期) または async with Client(...) as client: (非同期) でラップします。azure.identity.aio からの非同期 DefaultAzureCredential については、トークンとトランスポートがクリーンアップされるように async with credential: も使用してください。

リファレンスファイル

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

関連スキル