Communitygithub.com

SamuelChien/mega-skills-collection

使用微软 Agent Framework Python SDK(agent-framework-azure-ai)在 Azure AI Foundry 上构建持久化智能体。适用于使用 AzureAIAgentsProvider 创建持久化智能体、使用托管工具(代码解释器、文件搜索、网络搜索)、集成 MCP 服务器、管理对话线程或实现流式响应。涵盖函数工具、结构化输出和多工具智能体。

mega-skills-collection 是什么?

该技能基于微软 Agent Framework Python SDK,为开发者提供在 Azure AI Foundry 上构建持久化 AI 智能体的完整指南。它详细说明了如何使用 `AzureAIAgentsProvider` 与 Azure AI Agent 服务交互,支持创建、运行和管理具有对话持久性的智能体。核心功能包括:通过将 Python 函数直接传入 `tools` 参数来使用函数工具;利用 `HostedCodeInterpreterTool`、`HostedFileSearchTool`、`HostedWebSearchTool` 等托管工具;集成客户端管理或服务管理的 MCP 工具;实现流式响应;以及使用 `AgentThread` 进行多轮对话管理。此外,该技能还涵盖了结构化输出(基于 Pydantic)和身份验证最佳实践,特别强调使用 `DefaultAzureCredential` 和异步上下文管理器。它支持 Claude Code、Cursor、Codex 等 AI 编码助手平台,帮助开发者快速掌握在 Azure 生态中构建生产级智能体所需的全部模式。

兼容平台~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 托管智能体

使用微软 Agent Framework Python SDK 在 Azure AI Foundry 上构建持久化智能体。

架构

用户查询 → AzureAIAgentsProvider → Azure AI Agent 服务(持久化)
                    ↓
              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=<specific_credential>)以将凭据链限制为生产环境安全的凭据。
  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=<specific_credential>
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".

相关技能