agent-framework-azure-ai-py
microsoft/skills
使用 Microsoft Agent Framework Python SDK 在 Azure AI Foundry 上构建持久化代理,支持函数工具、托管工具、MCP 服务器、对话线程和流式响应。
...展开全部Agent Framework Azure 托管代理
使用 Microsoft Agent Framework Python SDK 在 Azure AI Foundry 上构建持久化代理。
架构
用户查询 → AzureAIAgentsProvider → Azure AI 代理服务(持久化)
↓
Agent.run() / Agent.run_stream()
↓
工具:Function | 托管(代码/搜索/Web) | MCP
↓
AgentThread(对话持久化)
安装
# 完整框架(推荐)
pip install agent-framework --pre
# 或仅安装 Azure 专用包
pip install agent-framework-azure-ai --pre
环境变量
export AZURE_AI_PROJECT_ENDPOINT="https://.services.ai.azure.com/api/projects/" # 所有身份验证方法均需此变量
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # 所有身份验证方法均需此项
export BING_CONNECTION_ID="your-bing-connection-id" # 用于网页搜索
export AZURE_TOKEN_CREDENTIALS=prod # 仅当在生产环境中使用 DefaultAzureCredential 时才需要此项
身份验证与生命周期
🔑 以下每个代码示例均适用两条规则:
- 优先使用
DefaultAzureCredential。它既可在本地(Azure CLI / VS Code / Developer CLI)使用,也可在 Azure 中(托管身份、工作负载身份)使用,且无需修改代码。请避免使用连接字符串、账户/API 密钥——它们会绕过 Entra 审计和轮换机制。
- 本地开发:
DefaultAzureCredential可直接使用。- 生产环境:将
AZURE_TOKEN_CREDENTIALS设置为prod(或AZURE_TOKEN_CREDENTIALS=),以将凭据链限制为生产环境安全的凭据。- 将每个客户端封装在上下文管理器中,以确保 HTTP 传输、套接字和令牌缓存能以可预测的方式释放:
- 同步模式:
使用 ``(...) as client: - 异步:
async with以及(...) 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("Hello!")
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"Agent: {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}")
提供程序方法
| 方法 | 描述 |
|---|---|
create_agent() |
在 Azure AI 服务上创建新代理 |
get_agent(agent_id) |
按 ID 检索现有代理 |
as_agent(sdk_agent) |
封装 SDK 代理对象(不进行 HTTP 调用) |
托管工具快速参考
| 工具 | 导入 | 用途 |
|---|---|---|
HostedCodeInterpreterTool |
from agent_framework import HostedCodeInterpreterTool |
执行 Python 代码 |
HostedFileSearchTool |
from agent_framework import HostedFileSearchTool |
搜索向量存储库 |
托管网页搜索工具 |
from agent_framework import HostedWebSearchTool |
Bing 网络搜索 |
托管MCPTool |
from agent_framework import HostedMCPTool |
服务管理的 MCP |
MCPStreamableHTTPTool |
from 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
最佳实践
- 此 SDK 采用“异步优先”原则——请在整个过程中使用
async def处理程序和async 关键字。 - 始终为客户端和异步凭据使用上下文管理器。将每个客户端包装在
`Client(...) as client:`(同步)或`async with Client(...) as client:`(异步)中。 对于来自azure.identity.aio的异步DefaultAzureCredential,也请使用async with credential:,以便对令牌和传输进行清理。
参考文件
- references/tools.md:详细的托管工具模式
- references/mcp.md:MCP 集成(托管 + 本地)
- references/threads.md:线程和对话管理
- references/advanced.md:OpenAPI、引用、结构化输出
---
name: agent-framework-azure-ai-py
description: Build persistent agents on Azure AI Foundry using the Microsoft Agent Framework Python SDK, with support for function tools, hosted tools, MCP servers, conversation threads, and streaming responses.
license: MIT
---
# Agent Framework Azure Hosted Agents
Build persistent agents on Azure AI Foundry using the Microsoft Agent Framework Python SDK.
## Architecture
```
User Query → AzureAIAgentsProvider → Azure AI Agent Service (Persistent)
↓
Agent.run() / Agent.run_stream()
↓
Tools: Functions | Hosted (Code/Search/Web) | MCP
↓
AgentThread (conversation persistence)
```
## Installation
```bash
# Full framework (recommended)
pip install agent-framework --pre
# Or Azure-specific package only
pip install agent-framework-azure-ai --pre
```
## Environment Variables
```bash
export AZURE_AI_PROJECT_ENDPOINT="https://<project>.services.ai.azure.com/api/projects/<project-id>" # Required for all auth methods
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini" # Required for all auth methods
export BING_CONNECTION_ID="your-bing-connection-id" # For web search
export AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Authentication & Lifecycle
> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
> - Local dev: `DefaultAzureCredential` works as-is.
> - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
> - Sync: `with <Client>(...) as client:`
> - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.
```python
from azure.identity.aio import AzureCliCredential, DefaultAzureCredential, ManagedIdentityCredential
# Development
credential = AzureCliCredential()
# Production
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
```
## Core Workflow
### Basic Agent
```python
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 with Function Tools
```python
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:
"""Get the current weather for a location."""
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 with Hosted Tools
```python
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)
```
### Streaming Responses
```python
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()
```
### Conversation Threads
```python
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}")
```
### Structured Outputs
```python
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}")
```
## Provider Methods
| Method | Description |
|--------|-------------|
| `create_agent()` | Create new agent on Azure AI service |
| `get_agent(agent_id)` | Retrieve existing agent by ID |
| `as_agent(sdk_agent)` | Wrap SDK Agent object (no HTTP call) |
## Hosted Tools Quick Reference
| Tool | Import | Purpose |
|------|--------|---------|
| `HostedCodeInterpreterTool` | `from agent_framework import HostedCodeInterpreterTool` | Execute Python code |
| `HostedFileSearchTool` | `from agent_framework import HostedFileSearchTool` | Search vector stores |
| `HostedWebSearchTool` | `from agent_framework import HostedWebSearchTool` | Bing web search |
| `HostedMCPTool` | `from agent_framework import HostedMCPTool` | Service-managed MCP |
| `MCPStreamableHTTPTool` | `from agent_framework import MCPStreamableHTTPTool` | Client-managed MCP |
## Complete Example
```python
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:
"""Get weather for a location."""
return f"Weather in {location}: 72°F, sunny"
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="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"\nConfidence: {analysis.confidence}")
if __name__ == "__main__":
asyncio.run(main())
```
## Conventions
- Always use async context managers: `async with provider:`
- Pass functions directly to `tools=` parameter (auto-converted to AIFunction)
- Use `Annotated[type, Field(description=...)]` for function parameters
- Use `get_new_thread()` for multi-turn conversations
- Prefer `HostedMCPTool` for service-managed MCP, `MCPStreamableHTTPTool` for client-managed
## Best Practices
1. **This SDK is async-first** — use `async def` handlers and `async with` throughout.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with Client(...) as client:` (sync) or `async with Client(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
## Reference Files
- [references/tools.md](references/tools.md): Detailed hosted tool patterns
- [references/mcp.md](references/mcp.md): MCP integration (hosted + local)
- [references/threads.md](references/threads.md): Thread and conversation management
- [references/advanced.md](references/advanced.md): OpenAPI, citations, structured outputs
所有文件
0 个文件安装 agent-framework-azure-ai-py
下载技能文件并将其解压到 .claude/skills/ 目录中。
下载ZIP克隆仓库并复制技能文件到您的项目中。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/agent-framework-azure-ai-py # Copy SKILL.md to your .claude/skills/ directory
复制





首页
