人間中心エージェント

Microsoft Agent Framework では、 Anthropic のクロード モデルを使用するエージェントの作成がサポートされています。

はじめに

必要な NuGet パッケージをプロジェクトに追加します。

dotnet add package Microsoft.Agents.AI.Anthropic --prerelease

Azure Foundry を使用している場合は、次も追加します。

dotnet add package Anthropic.Foundry --prerelease
dotnet add package Azure.Identity

コンフィギュレーション

環境変数

Anthropic 認証に必要な環境変数を設定します。

# Required for Anthropic API access
$env:ANTHROPIC_API_KEY="your-anthropic-api-key"
$env:ANTHROPIC_DEPLOYMENT_NAME="claude-haiku-4-5"  # or your preferred model

Anthropic コンソールから API キーを取得できます。

プロバイダーホスト型の Anthropic エンドポイントの場合、Python パッケージでは、 AnthropicFoundryClientAnthropicBedrockClient、および AnthropicVertexClientも公開されます。

API キーを使用した Azure Foundry の場合

$env:ANTHROPIC_RESOURCE="your-foundry-resource-name"  # Subdomain before .services.ai.azure.com
$env:ANTHROPIC_API_KEY="your-anthropic-api-key"
$env:ANTHROPIC_DEPLOYMENT_NAME="claude-haiku-4-5"

Azure CLI を使用した Azure Foundry の場合

$env:ANTHROPIC_RESOURCE="your-foundry-resource-name"  # Subdomain before .services.ai.azure.com
$env:ANTHROPIC_DEPLOYMENT_NAME="claude-haiku-4-5"

Azure CLI で Azure Foundry を使用する場合は、 az login でログインし、Azure Foundry リソースにアクセスできることを確認してください。 詳細については、 Azure CLI のドキュメントを参照してください

Anthropic エージェントを作成する

基本的なエージェントの作成 (Anthropic パブリック API)

パブリック API を使用して Anthropic エージェントを作成する最も簡単な方法は次のとおりです。

var apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY");
var deploymentName = Environment.GetEnvironmentVariable("ANTHROPIC_DEPLOYMENT_NAME") ?? "claude-haiku-4-5";

AnthropicClient client = new() { APIKey = apiKey };

AIAgent agent = client.AsAIAgent(
    model: deploymentName,
    name: "HelpfulAssistant",
    instructions: "You are a helpful assistant.");

// Invoke the agent and output the text result.
Console.WriteLine(await agent.RunAsync("Hello, how can you help me?"));

API キーを使用した Azure Foundry での Anthropic の使用

Azure Foundry で Anthropic を設定したら、API キー認証で使用できます。

var resource = Environment.GetEnvironmentVariable("ANTHROPIC_RESOURCE");
var apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY");
var deploymentName = Environment.GetEnvironmentVariable("ANTHROPIC_DEPLOYMENT_NAME") ?? "claude-haiku-4-5";

AnthropicClient client = new AnthropicFoundryClient(
    new AnthropicFoundryApiKeyCredentials(apiKey, resource));

AIAgent agent = client.AsAIAgent(
    model: deploymentName,
    name: "FoundryAgent",
    instructions: "You are a helpful assistant using Anthropic on Azure Foundry.");

Console.WriteLine(await agent.RunAsync("How do I use Anthropic on Foundry?"));

Azure 資格情報で Anthropic on Azure Foundry を使用する (Azure Cli 資格情報の例)

Azure 資格情報が推奨される環境の場合:

var resource = Environment.GetEnvironmentVariable("ANTHROPIC_RESOURCE");
var deploymentName = Environment.GetEnvironmentVariable("ANTHROPIC_DEPLOYMENT_NAME") ?? "claude-haiku-4-5";

AnthropicClient client = new AnthropicFoundryClient(
    new AnthropicAzureTokenCredential(new DefaultAzureCredential(), resource));

AIAgent agent = client.AsAIAgent(
    model: deploymentName,
    name: "FoundryAgent",
    instructions: "You are a helpful assistant using Anthropic on Azure Foundry.");

Console.WriteLine(await agent.RunAsync("How do I use Anthropic on Foundry?"));

/// <summary>
/// Provides methods for invoking the Azure hosted Anthropic models using <see cref="TokenCredential"/> types.
/// </summary>
public sealed class AnthropicAzureTokenCredential(TokenCredential tokenCredential, string resourceName) : IAnthropicFoundryCredentials
{
    /// <inheritdoc/>
    public string ResourceName { get; } = resourceName;

    /// <inheritdoc/>
    public void Apply(HttpRequestMessage requestMessage)
    {
        requestMessage.Headers.Authorization = new AuthenticationHeaderValue(
                scheme: "bearer",
                parameter: tokenCredential.GetToken(new TokenRequestContext(scopes: ["https://ai.azure.com/.default"]), CancellationToken.None)
                    .Token);
    }
}

Warnung

DefaultAzureCredential は開発には便利ですが、運用環境では慎重に考慮する必要があります。 運用環境では、待機時間の問題、意図しない資格情報のプローブ、フォールバック メカニズムによる潜在的なセキュリティ リスクを回避するために、特定の資格情報 ( ManagedIdentityCredential など) を使用することを検討してください。

ヒント

実行可能な完全な例については、 .NET サンプル を参照してください。

ツール

ツール 地位
関数ツール AIFunctionを介した Standard AIFunctionFactory.Create(...) インスタンス。
ツールの承認 関数呼び出し対応のチャット クライアントによって提供され、あらゆる関数ツール呼び出しで動作します。
コード インタープリター 現在、.NET Anthropic クライアントではサポートされていません。
ファイル検索 サポートされていません。
Web 検索 現在、.NET Anthropic クライアントではサポートされていません。
ホストされている MCP ツール Supported.
ローカル MCP ツール Supported.

エージェントの使用

エージェントは標準の AIAgent であり、すべての標準エージェント操作をサポートします。

エージェントを実行して操作する方法の詳細については、 エージェントの概要 に関するチュートリアルを参照してください。

[前提条件]

Microsoft Agent Framework Anthropic パッケージをインストールします。

pip install agent-framework-anthropic --pre

コンフィギュレーション

環境変数

Anthropic 認証に必要な環境変数を設定します。

# Required for Anthropic API access
ANTHROPIC_API_KEY="your-anthropic-api-key"
ANTHROPIC_CHAT_MODEL="claude-sonnet-4-5-20250929"  # or your preferred model

# Optional: override the Anthropic API endpoint (e.g. for Foundry-compatible deployments)
ANTHROPIC_BASE_URL="https://your-custom-endpoint.com"

または、プロジェクト ルートで .env ファイルを使用することもできます。

ANTHROPIC_API_KEY=your-anthropic-api-key
ANTHROPIC_CHAT_MODEL=claude-sonnet-4-5-20250929
# ANTHROPIC_BASE_URL=https://your-custom-endpoint.com  # optional

Anthropic コンソールから API キーを取得できます。

はじめに

Agent Framework から必要なクラスをインポートします。

import asyncio
from agent_framework.anthropic import AnthropicClient

Anthropic エージェントを作成する

基本的なエージェントの作成

Anthropic エージェントを作成する最も簡単な方法は次のとおりです。

async def basic_example():
    # Create an agent using Anthropic
    agent = AnthropicClient().as_agent(
        name="HelpfulAssistant",
        instructions="You are a helpful assistant.",
    )

    result = await agent.run("Hello, how can you help me?")
    print(result.text)

明示的な構成の使用

環境変数に依存する代わりに、明示的な構成を指定できます。

async def explicit_config_example():
    agent = AnthropicClient(
        model="claude-sonnet-4-5-20250929",
        api_key="your-api-key-here",
    ).as_agent(
        name="HelpfulAssistant",
        instructions="You are a helpful assistant.",
    )

    result = await agent.run("What can you do?")
    print(result.text)

カスタム ベース URL の使用

base_urlAnthropicClient に直接渡して、Foundryによってホストされたデプロイメントなど、Anthropic互換のエンドポイントを指すようにします。 これにより、AnthropicClientに切り替えるのではなく、同じAnthropicFoundryClientコードを保持し、エンドポイントのみを変更できます。

async def custom_base_url_example():
    agent = AnthropicClient(
        model="claude-haiku-4-5",
        api_key="your-api-key-here",
        base_url="https://your-foundry-resource.services.ai.azure.com/models/anthropic",
    ).as_agent(
        name="HelpfulAssistant",
        instructions="You are a helpful assistant.",
    )

    result = await agent.run("What can you do?")
    print(result.text)

base_url 明示的に渡されない場合、 ANTHROPIC_BASE_URL 環境変数にフォールバックします。

Foundry でアントロピックを使用する方法

Foundry で Anthropic をセットアップしたら、次の環境変数が設定されていることを確認します。

ANTHROPIC_FOUNDRY_API_KEY="your-foundry-api-key"
ANTHROPIC_FOUNDRY_RESOURCE="your-foundry-resource-name"
ANTHROPIC_CHAT_MODEL="claude-haiku-4-5"

次に、次のようにエージェントを作成します。

from agent_framework.foundry import AnthropicFoundryClient

async def foundry_example():
    agent = AnthropicFoundryClient().as_agent(
        name="FoundryAgent",
        instructions="You are a helpful assistant using Anthropic on Foundry.",
    )

    result = await agent.run("How do I use Anthropic on Foundry?")
    print(result.text)

リソース名ではなく、完全な Anthropic 互換エンドポイントを構成する場合は、ANTHROPIC_FOUNDRY_BASE_URLに加えてANTHROPIC_FOUNDRY_API_KEYを設定します。

ツール

AnthropicClient は、標準の関数ツールのサポートと共に、ホストされているAnthropic ツール ファクトリを公開します。 client.get_*_tool(...)を使用してツールをビルドし、tools=またはas_agent(...)Agent(...)を渡します。

ツール 工場/建設 地位
関数ツール 任意のPythonの呼び出し可能オブジェクトまたは@ai_functionを渡します Python プロセスでローカルに呼び出されます。
ツールの承認 フレームワークの関数呼び出しチャット クライアントによって処理されます 任意の関数ツール呼び出しで動作します。
コード インタープリター client.get_code_interpreter_tool() Anthropic Skills に必要です。
ファイル検索 n/a Anthropic API によって公開されません。
Web 検索 client.get_web_search_tool() Anthropicのホスト型ウェブ検索。
ホストされている MCP ツール client.get_mcp_tool(name=..., url=...) Anthropicによって呼び出されたリモート MCP サーバー。
ローカル MCP ツール MCPStreamableHTTPTool / MCPStdioTool プロセス内で実行されます。

ホストされている MCP、Web 検索、拡張思考、Anthropic スキルの組み合わせなど、より豊富な例については、以下の「Hosted Toolsを参照してください。

エージェントの機能

from typing import Annotated

def get_weather(
    location: Annotated[str, "The location to get the weather for."],
) -> str:
    """Get the weather for a given location."""
    conditions = ["sunny", "cloudy", "rainy", "stormy"]
    return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."

async def tools_example():
    agent = AnthropicClient().as_agent(
        name="WeatherAgent",
        instructions="You are a helpful weather assistant.",
        tools=get_weather,  # Add tools to the agent
    )

    result = await agent.run("What's the weather like in Seattle?")
    print(result.text)

ストリーミング応答

ユーザー エクスペリエンスを向上するために生成された応答を取得します。

async def streaming_example():
    agent = AnthropicClient().as_agent(
        name="WeatherAgent",
        instructions="You are a helpful weather agent.",
        tools=get_weather,
    )

    query = "What's the weather like in Portland and in Paris?"
    print(f"User: {query}")
    print("Agent: ", end="", flush=True)
    async for chunk in agent.run(query, stream=True):
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print()

ホステッド ツール

Anthropic エージェントは、Web 検索、MCP (モデル コンテキスト プロトコル)、コード実行などのホストされたツールをサポートします。

from agent_framework.anthropic import AnthropicClient

async def hosted_tools_example():
    client = AnthropicClient()
    agent = client.as_agent(
        name="DocsAgent",
        instructions="You are a helpful agent for both Microsoft docs questions and general questions.",
        tools=[
            client.get_mcp_tool(
                name="Microsoft Learn MCP",
                url="https://learn.microsoft.com/api/mcp",
            ),
            client.get_web_search_tool(),
        ],
        default_options={"max_tokens": 20000},
    )

    result = await agent.run("Can you compare Python decorators with C# attributes?")
    print(result.text)

拡張思考 (推論)

Anthropic は、 thinking 機能を通じて拡張思考機能をサポートしています。これにより、モデルは推論プロセスを示すことができます。

from agent_framework.anthropic import AnthropicClient

async def thinking_example():
    client = AnthropicClient()
    agent = client.as_agent(
        name="DocsAgent",
        instructions="You are a helpful agent.",
        tools=[client.get_web_search_tool()],
        default_options={
            "max_tokens": 20000,
            "thinking": {"type": "enabled", "budget_tokens": 10000}
        },
    )

    query = "Can you compare Python decorators with C# attributes?"
    print(f"User: {query}")
    print("Agent: ", end="", flush=True)

    async for chunk in agent.run(query, stream=True):
        for content in chunk.contents:
            if content.type == "text_reasoning":
                # Display thinking in a different color
                print(f"\033[32m{content.text}\033[0m", end="", flush=True)
            if content.type == "usage":
                print(f"\n\033[34m[Usage: {content.usage_details}]\033[0m\n", end="", flush=True)
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print()

アントロピック スキル

Anthropic は、PowerPointプレゼンテーションの作成など、エージェント機能を拡張するマネージド スキルを提供します。 スキルが機能するには、コード インタープリター ツールが必要です。

from agent_framework import Content
from agent_framework.anthropic import AnthropicClient

async def skills_example():
    # Create client with skills beta flag
    client = AnthropicClient(additional_beta_flags=["skills-2025-10-02"])

    # Create an agent with the pptx skill enabled
    # Skills require the Code Interpreter tool
    agent = client.as_agent(
        name="PresentationAgent",
        instructions="You are a helpful agent for creating PowerPoint presentations.",
        tools=client.get_code_interpreter_tool(),
        default_options={
            "max_tokens": 20000,
            "thinking": {"type": "enabled", "budget_tokens": 10000},
            "container": {
                "skills": [{"type": "anthropic", "skill_id": "pptx", "version": "latest"}]
            },
        },
    )

    query = "Create a presentation about renewable energy with 5 slides"
    print(f"User: {query}")
    print("Agent: ", end="", flush=True)

    files: list[Content] = []
    async for chunk in agent.run(query, stream=True):
        for content in chunk.contents:
            match content.type:
                case "text":
                    print(content.text, end="", flush=True)
                case "text_reasoning":
                    print(f"\033[32m{content.text}\033[0m", end="", flush=True)
                case "hosted_file":
                    # Catch generated files
                    files.append(content)

    print("\n")

    # Download generated files
    if files:
        print("Generated files:")
        for idx, file in enumerate(files):
            file_content = await client.anthropic_client.beta.files.download(
                file_id=file.file_id,
                betas=["files-api-2025-04-14"]
            )
            filename = f"presentation-{idx}.pptx"
            with open(filename, "wb") as f:
                await file_content.write_to_file(f.name)
            print(f"File {idx}: {filename} saved to disk.")

完全な例

# Copyright (c) Microsoft. All rights reserved.

import asyncio
from random import randint
from typing import Annotated

from agent_framework import tool
from agent_framework.anthropic import AnthropicClient

"""
Anthropic Chat Agent Example

This sample demonstrates using Anthropic with an agent and a single custom tool.
"""


# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
@tool(approval_mode="never_require")
def get_weather(
    location: Annotated[str, "The location to get the weather for."],
) -> str:
    """Get the weather for a given location."""
    conditions = ["sunny", "cloudy", "rainy", "stormy"]
    return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."


async def non_streaming_example() -> None:
    """Example of non-streaming response (get the complete result at once)."""
    print("=== Non-streaming Response Example ===")

    agent = AnthropicClient(
    ).as_agent(
        name="WeatherAgent",
        instructions="You are a helpful weather agent.",
        tools=get_weather,
    )

    query = "What's the weather like in Seattle?"
    print(f"User: {query}")
    result = await agent.run(query)
    print(f"Result: {result}\n")


async def streaming_example() -> None:
    """Example of streaming response (get results as they are generated)."""
    print("=== Streaming Response Example ===")

    agent = AnthropicClient(
    ).as_agent(
        name="WeatherAgent",
        instructions="You are a helpful weather agent.",
        tools=get_weather,
    )

    query = "What's the weather like in Portland and in Paris?"
    print(f"User: {query}")
    print("Agent: ", end="", flush=True)
    async for chunk in agent.run(query, stream=True):
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print("\n")


async def main() -> None:
    print("=== Anthropic Example ===")

    await streaming_example()
    await non_streaming_example()


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

エージェントの使用

エージェントは標準の Agent であり、すべての標準エージェント操作をサポートします。

エージェントを実行して操作する方法の詳細については、 エージェントの概要 に関するチュートリアルを参照してください。

Anthropic

anthropicprovider パッケージは、Anthropic API を使用してエージェントを作成します。

Installation

go get github.com/microsoft/agent-framework-go

Anthropic エージェントを作成する

import (
    "github.com/microsoft/agent-framework-go/agent"
    "github.com/microsoft/agent-framework-go/provider/anthropicprovider"

    "github.com/anthropics/anthropic-sdk-go"
)

a := anthropicprovider.NewAgent(
    anthropic.NewClient(), // uses ANTHROPIC_API_KEY env var
    anthropicprovider.AgentConfig{
        Model: "claude-sonnet-4-5",
        Instructions: "You are a helpful assistant.",
        Config: agent.Config{
            Name:         "ClaudeAgent",
        },
    },
)

resp, err := a.RunText(ctx, "Tell me a joke.").Collect()

カスタム オプション

anthropicprovider.MessageNewParamsを使用してAnthropic固有のパラメーターを渡します。

resp, err := a.RunText(ctx, "Hello!",
    anthropicprovider.MessageNewParams(anthropic.MessageNewParams{
        MaxTokens: 500,
    }),
).Collect()

ヒント

完全な例については、Anthropicサンプルを参照してください。

次のステップ