Anthropic

Microsoft 代理程式架構支援建立使用 Anthropic 的 Claude 模型的代理程式。

Warning

將模型或嵌入輸出,以及支援時由模型產生的工具呼叫,視為不可信的應用程式輸入。 在程式碼產生副作用或渲染內容之前,先驗證它們。 如果你設定自訂端點,請確認你信任它的 URL 和營運方。

直接模型推論與 Claude Agent SDK 的比較

Agent Framework 對 Anthropic 的支援有兩種不同形式。

Integration 類型 代理迴圈與工具 何時使用
直接模型推論(本頁) AnthropicClient 以及提供者託管的變體,並以 Agent(client=...) 包裝 你的應用程式擁有 Agent Framework 迴圈、會話、中介軟體、函式工具,以及支援的 Anthropic 託管工具。 您希望將 Claude 做為標準應用程式擁有之 Agent Framework 代理程式背後的模型。
Anthropic Claude 代理程式 SDK ClaudeAgent,直接建構 Claude 的編碼代理執行環境擁有會話、權限、內建的檔案與 shell 工具,以及 MCP 行為。 你需要 Claude 的代管程式設計代理執行環境和權限模型。

使用者入門

將必要的 NuGet 套件新增至您的專案。

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

如果你正在使用 Microsoft Foundry,也請新增:

dotnet add package Anthropic.Foundry --prerelease

Configuration

環境變數

設定 Anthropic 驗證所需的環境變數:

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

您可以從 Anthropic 控制台取得 API 金鑰。

適用於使用 API 金鑰的 Microsoft Foundry

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

適用於使用 Azure CLI 的 Microsoft Foundry

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

備註

透過 Azure CLI 使用 Microsoft Foundry 時,請確保您已使用 az login 登入,並且可存取 Foundry 資源。 欲了解更多資訊,請參閱Azure CLI文件。

創建人類代理

基本代理程式建立 (Anthropic Public API)

使用公開 API 建立 Anthropic 代理最簡單的方法:

var apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY");
var deploymentName = Environment.GetEnvironmentVariable("ANTHROPIC_CHAT_MODEL_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?"));

在 Foundry 上使用 Anthropic

在 Microsoft Foundry 上設定好 Anthropic 後,你可以搭配 API 金鑰驗證一起使用:

API 金鑰認證

var resource = Environment.GetEnvironmentVariable("ANTHROPIC_RESOURCE");
var apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY");
var deploymentName = Environment.GetEnvironmentVariable("ANTHROPIC_CHAT_MODEL_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 Microsoft Foundry.");

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

Azure 認證驗證

對於偏好使用 Azure 憑證的環境:

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

AnthropicClient client = new AnthropicFoundryClient(
    new AnthropicFoundryIdentityTokenCredentials(
        new DefaultAzureCredential(),
        resource,
        ["https://ai.azure.com/.default"]));

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

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

Warning

DefaultAzureCredential 開發方便,但在生產過程中需謹慎考量。 在生產環境中,建議使用特定的憑證(例如 ManagedIdentityCredential),以避免延遲問題、意外的憑證探測,以及備援機制帶來的安全風險。

Tip

完整可執行範例請參閱 .NET 範例 。

Tools

Tool 現況 註釋
函式工具 ✅ 透過 AIFunctionFactory.Create(...) 的標準 AIFunction 執行個體。
工具核准 ✅ 由支援函式呼叫的聊天用戶端提供;適用於任何函式工具呼叫。
程式碼解譯器 ❌ 目前.NET Anthropic客戶端不支援。
檔案搜尋 ❌ 不支援。
網路搜尋 ❌ 目前.NET Anthropic客戶端不支援。
託管 MCP 工具 ✅ 支援。
本地 MCP 工具 ✅ 支援。

延展性思考

透過原始訊息表示法來設定 Anthropic 推理,並從一般或串流回應中取用 TextReasoningContent。

人類技能

由 Anthropic 管理的技能可以透過託管的程式碼執行環境建立檔案。 範例列出可用技能、設定 PowerPoint 技能,並下載產生的檔案。

使用代理程式

代理程式是標準 AIAgent ,支援所有標準代理程式作業。

請參閱 代理程式入門教學課程 ,以取得如何執行代理程式並與代理程式互動的詳細資訊。

Prerequisites

安裝 Microsoft Agent Framework Anthropic 套件。

pip install agent-framework-anthropic --pre

Configuration

環境變數

設定 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 金鑰。

使用者入門

從代理程式架構匯入所需的類別:

import asyncio
from agent_framework import Agent
from agent_framework.anthropic import AnthropicClient

創建人類代理

基本代理程式創建

創建一個 Anthropic 智能體的最簡單方法:

from agent_framework import Agent

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

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

使用明確配置

您可以提供明確的設定,而不是依賴環境變數:

from agent_framework import Agent

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

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

Anthropic SDK 1.x 不支援 temperature、 top_p或 top_k 選項。 Agent Framework 會忽略這些選項,如果您提供這些選項,就會記錄警告。

使用自訂基礎網址

將 base_url 直接傳遞至 AnthropicClient,以指向任何與 Anthropic 相容的端點,例如 Foundry 託管的部署。 這樣你就能保留相同的 AnthropicClient 程式碼,只修改端點,而不必切換到 AnthropicFoundryClient:

from agent_framework import Agent

async def custom_base_url_example():
    agent = Agent(
        client=AnthropicClient(
            model="claude-haiku-4-5",
            api_key="your-api-key-here",
            base_url="https://your-foundry-resource.services.ai.azure.com/models/anthropic",
        ),
        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 上使用 Anthropic

在 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 import Agent
from agent_framework.anthropic import AnthropicFoundryClient

async def foundry_example():
    agent = Agent(
        client=AnthropicFoundryClient(),
        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。

在 Amazon Bedrock 上使用 Anthropic

AnthropicBedrockClient 透過 Amazon Bedrock 處理 Claude 模型推論。

AWS_ACCESS_KEY_ID="<access-key>"
AWS_SECRET_ACCESS_KEY="<secret-key>"
AWS_REGION="us-east-1"
# Optional:
AWS_PROFILE="<profile>"
AWS_SESSION_TOKEN="<session-token>"
ANTHROPIC_BEDROCK_BASE_URL="<custom-endpoint>"
ANTHROPIC_CHAT_MODEL="anthropic.claude-3-5-sonnet-20241022-v2:0"

目前尚無可執行的代理框架範例公開。AnthropicBedrockClient

在 Google Vertex AI 上使用 Anthropic

AnthropicVertexClient 透過 Google Vertex AI 路由 Claude 模型推論。

CLOUD_ML_REGION="us-east5"
ANTHROPIC_VERTEX_PROJECT_ID="<google-cloud-project>"
ANTHROPIC_CHAT_MODEL="claude-sonnet-4@20250514"
# Optional:
ANTHROPIC_VERTEX_BASE_URL="<custom-endpoint>"

目前尚無可執行的代理框架範例公開。AnthropicVertexClient

處理請求失敗情況

無論是串流或非串流執行,Anthropic SDK 的請求失敗都會透過代理框架例外揭露。 驗證與權限失敗會發生 ChatClientInvalidAuthException,其他 HTTP 4xx 失敗也會發生 ChatClientInvalidRequestException,所有其他提供者失敗也會產生 ChatClientException。

如果 Anthropic 在本地函式呼叫開始後使回應失效,Agent Framework 會引發 ResponseInvalidatedException,且不會執行或保存已失效的呼叫。 串流消費者在例外發生時可能已經收到部分更新;丟棄這些更新,而不是把它們當作已完成的回覆來處理。

當相同的錯誤處理應套用於不同聊天提供者時,請擷取ChatClientException。

繼續已暫停的伺服器工具回合

Anthropic 伺服器工具的呼叫與結果在訊息序列化時,會保留由適配器擁有的重播元資料。 不要修改 Content.additional_properties["anthropic"]["server_tool_block"];它可以包含原生區塊類型、結構化結果內容,以及 Anthropic 進行重放所需的加密值。

當 Anthropic 回傳 pause_turn 時,當每個區塊都能忠實重建時,客戶端會自動繼續使用相同的工具。 最多只能提出 10 次接續要求。 若無法重建原生內容、串流的 MCP 呼叫缺少保留參數 delta,或回應在限制後仍被暫停,客戶端會回傳 finish_reason="pause_turn" ,讓應用程式決定如何繼續。

Tools

除了標準函式工具支援外,AnthropicClient 還會公開託管的 Anthropic 工具工廠。 使用client.get_*_tool(...)建立工具,並透過tools=在Agent(...)上傳遞它。

Tool 工廠/建設 現況 註釋
函式工具 傳遞任何 Python 可呼叫或 @ai_function ✅ 在你的 Python 程序中本地調用。
工具核准 由框架中支援函式呼叫的聊天用戶端處理 ✅ 適用於任何函式工具呼叫。
程式碼解譯器 client.get_code_interpreter_tool() ✅ Anthropic Skills 所必需。
檔案搜尋 n/a ❌ Anthropic API 並未公開。
網路搜尋 client.get_web_search_tool() ✅ 託管的 Anthropic Web 搜尋。
託管 MCP 工具 client.get_mcp_tool(name=..., url=...) ✅ 由 Anthropic 呼叫的遠端 MCP 伺服器。
本地 MCP 工具 MCPStreamableHTTPTool / MCPStdioTool ✅ 在您的程序中執行。

如需更豐富的範例 — 結合託管 MCP、Web 搜尋、延伸思考和 Anthropic 技能 — 請參閱下方的託管工具。

代理功能

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."

from agent_framework import Agent

async def tools_example():
    agent = Agent(
        client=AnthropicClient(),
        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)

串流回應

取得即時產生的回應,以提供更好的使用者體驗:

from agent_framework import Agent

async def streaming_example():
    agent = Agent(
        client=AnthropicClient(),
        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 import Agent
from agent_framework.anthropic import AnthropicClient

async def hosted_tools_example():
    client = AnthropicClient()
    agent = Agent(
        client=client,
        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 import Agent
from agent_framework.anthropic import AnthropicClient

async def thinking_example():
    client = AnthropicClient()
    agent = Agent(
        client=client,
        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 typing import cast

from agent_framework import Agent, Content
from agent_framework.anthropic import AnthropicClient
from anthropic import AsyncAnthropic

async def skills_example():
    client = AnthropicClient()
    anthropic_client = cast(AsyncAnthropic, client.anthropic_client)

    # Create an agent with the pptx skill enabled
    # Skills require the Code Interpreter tool
    agent = Agent(
        client=client,
        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):
            if file.file_id is None:
                continue
            file_content = await anthropic_client.files.download(
                file_id=file.file_id
            )
            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 Agent, 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 = Agent(
        client=AnthropicClient(),
        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 = Agent(
        client=AnthropicClient(),
        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()

Tip

完整範例請參見 Anthropic 範例。

下一步