mcpField
A
agent-framework-azure-ai-py

agent-framework-azure-ai-py

github.com/sickn33Agent 工作流48.7k160 次安装今天更新
代码仓库

关于 agent-framework-azure-ai-py

这是一个使用 Microsoft Agent Framework 在 Azure AI Foundry 构建持久化 Agent 的 Python 技能,涵盖托管工具、对话线程、流式响应和 MCP,并提示旧版示例需先验证版本兼容性。

主要功能

  1. 01创建和检索 Azure AI Agent
  2. 02函数与托管工具
  3. 03流式响应与持久化线程
  4. 04结构化输出
  5. 05旧版 API 兼容性指引

适用场景

  1. 01在 Azure AI Foundry 创建持久化 Agent
  2. 02为 Agent 添加函数或托管工具
  3. 03构建多轮对话
  4. 04按已安装的 SDK 版本验证示例

MCP 相关

介绍使用 HostedMCPTool 的服务管理型 MCP,以及使用 MCPStreamableHTTPTool 的客户端管理型 MCP。旧版示例需要验证兼容性。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill agent-framework-azure-ai-py

安装后在 Claude Code 中输入/agent-framework-azure-ai-py确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

UPSTREAM-LICENSE.txt
UPSTREAM-NOTICE.md
references/
advanced.md
threads.md
tools.md
mcp.md

详细介绍

上游捆绑支持

支持文件包含在相对于技能的路径中。其固定来源、许可证、哈希值和导入变更请参阅 UPSTREAM-NOTICE.md。

Agent Framework Azure 托管 Agent

使用 Microsoft Agent Framework Python SDK 在 Azure AI Foundry 上构建持久化 Agent。

架构

User Query → AzureAIAgentsProvider → Azure AI Agent Service (Persistent)
                    ↓
              Agent.run() / Agent.run_stream()
                    ↓
              Tools: Functions | Hosted (Code/Search/Web) | MCP
                    ↓
              AgentThread (conversation persistence)

SDK 代际与执行范围

以下示例保留了较早一代的 Agent Framework(AzureAIAgentsProvider、AgentThread、Hosted*Tool)。这些示例未经验证,无法确认适用于当前软件包。Microsoft 当前文档将模型提供程序与 Agent 服务分开介绍,Python README 中列出了 agent-framework-foundry。改编这些代码片段前,请确认已安装的版本,并使用与之匹配的官方 API/示例;目前尚未确定兼容的旧版本。请勿将旧类与未固定版本的最新安装组合使用,并假设它们可以正常运行。

选择准确的 Azure 租户/项目/部署、主体和最小权限角色。创建 Agent、上传文件、启用代码/网页/MCP 工具以及运行提示词都会向服务发送数据,可能会持久化记录并产生费用。请先确定授权范围、预算、超时、工具允许列表和资源清理方式。关闭客户端不会删除托管 Agent/文件/向量存储/线程。请将检索到的文本和工具文本视为不可信内容,并在工具中强制执行租户/资源/操作授权;提示词不是访问控制措施。

安装

# Current package discovery only; pin reviewed versions in your project lockfile.
# These installs do not make the legacy snippets below compatible.
pip install agent-framework
# Selective current Foundry integration:
pip install agent-framework-foundry

环境变量

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"  # For web search

身份验证

from azure.identity.aio import AzureCliCredential, DefaultAzureCredential

# Development
credential = AzureCliCredential()

# Production
credential = DefaultAzureCredential()

核心工作流

基本 Agent
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="You are a helpful assistant.",
        )
        
        result = await agent.run("Hello!")
        print(result.text)

asyncio.run(main())
使用函数工具的 Agent
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="City name to get weather for")],
) -> str:
    """Return fixture weather (not a live observation)."""
    return f"Weather in {location}: 72°F, sunny"

def get_current_time() -> str:
    """Get the current UTC time."""
    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="You help with weather and time queries.",
            tools=[get_weather, get_current_time],  # Pass functions directly
        )
        
        result = await agent.run("What's the weather in Seattle?")
        print(result.text)
使用托管工具的 Agent
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="You can execute code, search files, and search the web.",
            tools=[
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
            ],
        )
        
        result = await agent.run("Calculate the factorial of 20 in Python")
        print(result.text)
流式响应
async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentsProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(
            name="StreamingAgent",
            instructions="You are a helpful assistant.",
        )
        
        print("Agent: ", end="", flush=True)
        async for chunk in agent.run_stream("Tell me a short story"):
            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="You are a helpful assistant.",
            tools=[get_weather],
        )
        
        # Create thread for conversation persistence
        thread = agent.get_new_thread()
        
        # First turn
        result1 = await agent.run("What's the weather in Seattle?", thread=thread)
        print(f"Agent: {result1.text}")
        
        # Second turn - context is maintained
        result2 = await agent.run("What about Portland?", thread=thread)
        print(f"Agent: {result2.text}")
        
        # Save thread ID for later resumption
        print(f"Conversation 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="Provide weather information in structured format.",
            response_format=WeatherResponse,
        )
        
        result = await agent.run("Weather in Seattle?")
        weather = WeatherResponse.model_validate_json(result.text)
        print(f"{weather.location}: {weather.temperature}°{weather.unit}")

提供程序方法

方法描述
create_agent()在 Azure AI 服务上创建新 Agent
get_agent(agent_id)按 ID 获取现有 Agent
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="City name")],
) -> str:
    """Return fixture weather (not a live observation)."""
    return f"Weather in {location}: 72°F, sunny"


class AnalysisResult(BaseModel):
    summary: str
    key_findings: list[str]
    confidence: float = Field(ge=0.0, le=1.0)


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="You are a research assistant with multiple capabilities.",
            tools=[
                get_weather,
                HostedCodeInterpreterTool(),
                HostedWebSearchTool(name="Bing"),
                mcp_tool,
            ],
        )
        
        thread = agent.get_new_thread()
        
        # Non-streaming
        result = await agent.run(
            "Search for Python best practices and summarize",
            thread=thread,
        )
        print(f"Response: {result.text}")
        
        # Streaming
        print("\nStreaming: ", end="")
        async for chunk in agent.run_stream("Continue with examples", thread=thread):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()
        
        # Structured output
        result = await agent.run(
            "Analyze findings",
            thread=thread,
            response_format=AnalysisResult,
        )
        analysis = AnalysisResult.model_validate_json(result.text)
        print(f"\nModel self-rating (not calibrated reliability): {analysis.confidence}")


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

当前参考资料:Microsoft 提供程序模型、Python 安装与示例。

约定

  • 始终使用异步上下文管理器:async with provider:
  • 将函数直接传递给 tools= 参数(自动转换为 AIFunction)
  • 函数参数使用 Annotated[type, Field(description=...)]
  • 多轮对话使用 get_new_thread()
  • 服务管理的 MCP 优先使用 HostedMCPTool,客户端管理的 MCP 使用 MCPStreamableHTTPTool

参考文件

  • references/tools.md:托管工具的详细模式
  • references/mcp.md:MCP 集成(托管 + 本地)
  • references/threads.md:线程与对话管理
  • references/advanced.md:OpenAPI、引用、结构化输出

适用场景

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

限制

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

评论

支持 Markdown