Communitygithub.com

SamuelChien/mega-skills-collection

使用 Microsoft Agent Framework Python SDK (agent-framework-azure-ai) 在 Azure AI Foundry 上建置持久性代理程式。適用於透過 AzureAIAgentsProvider 建立代理程式、使用代管工具(程式碼解譯器、檔案搜尋、網頁搜尋)、整合 MCP 伺服器、管理對話執行緒或實作串流回應。涵蓋函式工具、結構化輸出與多工具代理程式。

mega-skills-collection 是什麼?

此技能提供使用 Microsoft Agent Framework Python SDK 在 Azure AI Foundry 上建置與管理 AI 代理程式的完整解決方案。它透過 AzureAIAgentsProvider 支援持久性代理程式,可整合代管工具(如程式碼解譯器、檔案搜尋、Bing 網頁搜尋)與 MCP 伺服器。技能詳細說明核心工作流程,包括建立基本代理程式、新增函式工具、處理多輪對話執行緒、實作串流回應與結構化輸出。其架構採用非同步優先設計,並強調使用 `async with` 上下文管理器進行安全憑證管理與資源清理。支援多種驗證方式,推薦使用 `DefaultAzureCredential` 以簡化從本機開發到生產環境的部署。此技能適合需要透過 Python SDK 在 Azure 雲端上建置可靠、可擴展 AI 代理程式的開發者。

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

在你喜歡的 AI 中提問

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

說明文件

Agent Framework Azure 代管代理程式

使用 Microsoft Agent Framework Python SDK 在 Azure AI Foundry 上建置持久性代理程式。

架構

使用者查詢 → AzureAIAgentsProvider → Azure AI 代理程式服務 (持久性)
                    ↓
              Agent.run() / Agent.run_stream()
                    ↓
              工具:函式 | 代管 (程式碼/搜尋/網頁) | 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"  # 用於網頁搜尋
export AZURE_TOKEN_CREDENTIALS=prod # 僅在生產環境使用 DefaultAzureCredential 時需要

驗證與生命週期

🔑 下方每個程式碼範例都適用兩條規則:

  1. 優先使用 DefaultAzureCredential。 它在本地端 (Azure CLI / VS Code / 開發者 CLI) 與 Azure 環境 (受控識別、工作負載識別) 皆可直接運作,無須修改程式碼。應避免使用連接字串、帳戶/API 金鑰,因為它們會繞過 Entra 稽核與金鑰輪替。
    • 本地開發:DefaultAzureCredential 可直接使用。
    • 生產環境:設定 AZURE_TOKEN_CREDENTIALS=prod (或 AZURE_TOKEN_CREDENTIALS=<特定憑證>) 以將憑證鏈限制為生產環境安全的憑證。
  2. 將每個用戶端包裝在上下文管理器中,以確保 HTTP 傳輸、socket 和權杖快取能被明確釋放:
    • 同步: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} 的天氣:72°F,晴天"

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="你可以執行程式碼、搜尋檔案與網頁。",
            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}")
        
        # 第二輪 - 上下文保持不變
        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}")

Provider 方法

方法描述
create_agent()在 Azure AI 服務上建立新的代理程式
get_agent(agent_id)根據 ID 取得現有的代理程式
as_agent(sdk_agent)包裝 SDK Agent 物件 (無 HTTP 呼叫)

代管工具快速參考

工具匯入方式用途
HostedCodeInterpreterToolfrom agent_framework import HostedCodeInterpreterTool執行 Python 程式碼
HostedFileSearchToolfrom agent_framework import HostedFileSearchTool搜尋向量儲存庫
HostedWebSearchToolfrom agent_framework import HostedWebSearchToolBing 網頁搜尋
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} 的天氣:72°F,晴天"


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

相關技能