agent-framework-azure-ai-py
Microsoft Agent Framework Python SDK(agent-framework-azure-ai)を使用して、Azure AI Foundryエージェントを構築できます。AzureAIAgentsProviderで永続的なエージェントを作成する場合、ホストされたツール(コードインタープリター、ファイル検索、ウェブ検索)を利用する場合、MCPサーバーを統合する場合、会話スレッドを管理する場合、またはストリーミングレスポンスを実装する場合に使用します。関数ツール、構造化出力、マルチツールエージェントに対応しています。
description の原文を見る
Build Azure AI Foundry agents using the Microsoft Agent Framework Python SDK (agent-framework-azure-ai). Use when creating persistent agents with AzureAIAgentsProvider, using hosted tools (code interpreter, file search, web search), integrating MCP servers, managing conversation threads, or implementing streaming responses. Covers function tools, structured outputs, and multi-tool agents.
SKILL.md 本文
Agent Framework Azure ホステッドエージェント
Microsoft Agent Framework Python SDK を使用して Azure AI Foundry でパーシステントなエージェントを構築します。
アーキテクチャ
User Query → AzureAIAgentsProvider → Azure AI Agent Service (Persistent)
↓
Agent.run() / Agent.run_stream()
↓
Tools: Functions | Hosted (Code/Search/Web) | MCP
↓
AgentThread (conversation persistence)
インストール
# フルフレームワーク (推奨)
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" # Web 検索用
認証
from azure.identity.aio import AzureCliCredential, DefaultAzureCredential
# 開発環境
credential = AzureCliCredential()
# 本番環境
credential = DefaultAzureCredential()
コアワークフロー
基本的なエージェント
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())
ファンクションツール付きエージェント
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)
ホステッドツール付きエージェント
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],
)
# 会話の永続性のためのスレッドを作成
thread = agent.get_new_thread()
# 最初のターン
result1 = await agent.run("What's the weather in Seattle?", thread=thread)
print(f"Agent: {result1.text}")
# 2 番目のターン - コンテキストが維持されます
result2 = await agent.run("What about Portland?", thread=thread)
print(f"Agent: {result2.text}")
# 後で再開するためにスレッド ID を保存
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 サービス上に新しいエージェントを作成 |
get_agent(agent_id) | ID で既存のエージェントを取得 |
as_agent(sdk_agent) | SDK Agent オブジェクトをラップ (HTTP 呼び出しなし) |
ホステッドツールクイックリファレンス
| ツール | インポート | 目的 |
|---|---|---|
HostedCodeInterpreterTool | from agent_framework import HostedCodeInterpreterTool | Python コードを実行 |
HostedFileSearchTool | from agent_framework import HostedFileSearchTool | ベクトルストアを検索 |
HostedWebSearchTool | from agent_framework import HostedWebSearchTool | Bing Web 検索 |
HostedMCPTool | 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="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()
# ストリーミングなし
result = await agent.run(
"Search for Python best practices and summarize",
thread=thread,
)
print(f"Response: {result.text}")
# ストリーミング
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()
# 構造化出力
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())
規則
- 常に async コンテキストマネージャーを使用してください:
async with provider: - 関数を
tools=パラメータに直接渡してください (AIFunction に自動変換されます) - 関数パラメータに
Annotated[type, Field(description=...)]を使用してください - マルチターン会話には
get_new_thread()を使用してください - サービス管理型 MCP には
HostedMCPToolを、クライアント管理型にはMCPStreamableHTTPToolを優先してください
リファレンスファイル
- references/tools.md: ホステッドツールの詳細パターン
- references/mcp.md: MCP インテグレーション (ホステッド + ローカル)
- references/threads.md: スレッドと会話管理
- references/advanced.md: OpenAPI、引用、構造化出力
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- Tryboy869
- ライセンス
- MIT
- 最終更新
- 2026/2/28
Source: https://github.com/Tryboy869/dojutsu-for-ai / ライセンス: MIT