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 | 託管型(Code/Search/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="您的 Bing 連線 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: - 非同步:
使用 `,以及(...)` 作為 `client` 的 `async` 方法 使用 `DefaultAzureCredential()` 作為 `credential` 的 `async` 方法:(來自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("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="您是一位樂於助人的助手。",
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"Agent: {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 上下文管理器:
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的 asyncDefaultAzureCredential,也請使用async 搭配 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
複製





首頁
