オプション
家 Skill データサイエンスと機械学習 agent-framework-azure-ai-py

agent-framework-azure-ai-py

microsoft/skills microsoft/skills

Microsoft Agent Framework Python SDK を使用して、Azure AI Foundry 上で永続的なエージェントを構築します。この SDK では、関数型ツール、ホスト型ツール、MCP サーバー、会話スレッド、およびストリーミング応答がサポートされています。

...すべて拡張します
2
更新された時間 2026年9月15日

エージェント・フレームワーク:Azure ホスト型エージェント

Microsoft Agent Framework Python SDK を使用して、Azure AI Foundry 上で永続的なエージェントを構築します。

アーキテクチャ

ユーザークエリ → AzureAIAgentsProvider → Azure AI エージェント サービス (永続型)
                    ↓
              Agent.run() / Agent.run_stream()
                    ↓
              ツール: Functions | ホスト型 (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="your-bing-connection-id"  # Web検索用
export AZURE_TOKEN_CREDENTIALS=prod # 本番環境でDefaultAzureCredentialを使用する場合にのみ必要

認証とライフサイクル

🔑 以下のすべてのコードサンプルには、次の2つのルールが適用されます:

  1. DefaultAzureCredentialを優先してください。コードを変更することなく、ローカル(Azure CLI / VS Code / Developer CLI)およびAzure(マネージド ID、ワークロード ID)で動作します。接続文字列やアカウント/API キーの使用は避けてください。これらはEntraの監査およびローテーションの対象外となります。
    • ローカル開発:DefaultAzureCredentialはそのまま使用できます。
    • 本番環境:AZURE_TOKEN_CREDENTIALS=prod(またはAZURE_TOKEN_CREDENTIALS= )を設定し、資格情報チェーンを本番環境に適した資格情報に制限してください。
  2. すべてのクライアントをコンテキストマネージャーでラップし、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())

Function Tools を使用したエージェント

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="コードの実行、ファイル検索、Web検索が可能です。",
            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}")
        
        # 2回目のターン - コンテキストが保持される
        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 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 エージェントオブジェクトをラップする(HTTP 呼び出しなし)

ホスト型ツールのクイックリファレンス

ツール インポート 目的
HostedCodeInterpreterTool from agent_framework import HostedCodeInterpreterTool Pythonコードの実行
HostedFileSearchTool from agent_framework import HostedFileSearchTool ベクトルストアの検索
HostedWebSearchTool from agent_framework import HostedWebSearchTool Bing ウェブ検索
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="都市名")],
) -> 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 を、クライアント管理型にはMCPStreamableHTTPTool を優先して使用してください

ベストプラクティス

  1. この SDK は非同期優先です非同期の defハンドラとasync を全体を通して使用してください。
  2. クライアントおよび非同期認証情報には、常にコンテキストマネージャーを使用してください。すべてのクライアントを、(同期の場合は)`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、引用、構造化出力
GitHubで見る
---
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

コピー コピー
クイックセットアップ: スキルフォルダを .claude/skills/ にコピーしてください。 Claude が自動的にそのスキルを検出して使用します。
リポジトリ microsoft/skills

関連スキル

web-search
更新された時間 2026年6月29日
webapp-testing
更新された時間 2026年6月29日
lark-base
更新された時間 2026年7月5日
agentmail
更新された時間 2026年6月29日
OR