Anthropic

Microsoft Agent 框架支持创建使用 Anthropic 的 Claude 模型的代理。

Warning

在支持的情况下,将模型或嵌入输出以及模型生成的工具调用视为不受信任的应用程序输入。 在代码执行副作用或呈现内容之前对其进行验证。 如果配置自定义终结点,请验证是否信任其 URL 和运营者。

直接模型推理与 Claude 代理 SDK 的对比

代理框架中的 Anthropic 支持分为两种不同形式。

Integration 类型 代理循环和工具 何时使用
直接模型推理 (本页) AnthropicClient和提供程序托管的变体,使用Agent(client=...)进行包装 您的应用程序负责 Agent Framework 循环机制、会话、中间件、函数工具以及受支持的 Anthropic 托管工具。 你希望将 Claude 用作标准应用程序自有代理框架代理的底层模型。
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

环境变量

为人类身份验证设置所需的环境变量:

# 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

可以从 人类控制台获取 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"

注释

使用 Microsoft Foundry 和 Azure CLI 时,请确保已使用 az login 登录,并且拥有对 Foundry 资源的访问权限。 有关详细信息,请参阅 Azure CLI 文档。

创建人类代理

基本智能体创建(Anthropic 公共 API)

使用公共 API 创建人类代理的最简单方法:

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

工具 地位 注释
函数工具 ✅ 通过 AIFunctionFactory.Create(...) 的标准 AIFunction 实例。
工具审批 ✅ 由支持函数调用的聊天客户端提供;可与任何函数工具调用配合使用。
代码解释器 ❌ .NET Anthropic 客户端目前尚不支持此功能。
文件搜索 ❌ 不支持。
Web 搜索 ❌ .NET Anthropic 客户端目前尚不支持此功能。
托管 MCP 工具 ✅ 支持.
本地 MCP 工具 ✅ 支持.

拓展思维

通过原始消息表示形式配置 Anthropic 推理,并从常规响应或流式响应中使用TextReasoningContent。

人类技能

由 Anthropic 管理的技能可以通过托管代码执行环境创建文件。 该示例列出了可用的技能,配置PowerPoint技能,并下载生成的文件。

使用代理

代理是标准 AIAgent 代理,支持所有标准代理操作。

有关如何运行和与代理交互的详细信息,请参阅 代理入门教程 。

Prerequisites

安装 Microsoft Agent Framework Anthropic 包。

pip install agent-framework-anthropic --pre

Configuration

环境变量

为人类身份验证设置所需的环境变量:

# 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

可以从 人类控制台获取 API 密钥。

入门

从代理框架导入所需的类:

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

创建人类代理

基本代理创建

创建人类代理的最简单方法:

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 选项。 如果提供这些选项,代理框架将忽略这些选项并记录警告。

使用自定义基础 URL

将 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_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 的请求失败会通过 Agent Framework 异常暴露出来。 身份验证和权限失败会引发 ChatClientInvalidAuthException,其他 HTTP 4xx 失败会引发 ChatClientInvalidRequestException,而所有其他提供程序错误会引发 ChatClientException。

如果在本地函数调用开始后 Anthropic 使响应失效,Agent Framework 会引发ResponseInvalidatedException,并且不会执行或持久化该已失效的调用。 发生异常时,流式消费者可能已经收到部分更新;应丢弃这些更新,而不要将其视为已完成的响应。

当需要跨聊天提供商应用相同的错误处理时,捕获 ChatClientException。

继续已暂停的服务器工具轮次

Anthropic服务器工具调用和结果在序列化消息时保留适配器拥有的重播元数据。 请勿修改Content.additional_properties["anthropic"]["server_tool_block"];它可以包含本机块类型、结构化结果内容和Anthropic重播所需的加密值。

当Anthropic返回pause_turn时,当每个块可以忠实地重建时,客户端会自动继续使用相同的工具。 它最多发出 10 个延续请求。 如果无法重新构造原生内容,流式 MCP 调用缺少保留的参数增量,或者响应在达到限制后仍处于暂停状态,客户端将返回 finish_reason="pause_turn",以便应用程序决定如何继续。

Tools

AnthropicClient 公开托管的 Anthropic 工具工厂以及标准函数工具支持。 使用 client.get_*_tool(...) 来构建一个工具,并在 Agent(...) 上通过 tools= 传递它。

工具 工厂/建筑 地位 注释
函数工具 传递任何 Python 可调用对象或 @ai_function ✅ 在Python进程中本地调用。
工具审批 由框架的函数调用型聊天客户端处理 ✅ 适用于任何函数或工具调用。
代码解释器 client.get_code_interpreter_tool() ✅ Anthropic Skills 所必需。
文件搜索 n/a ❌ Anthropic API 未公开。
Web 搜索 client.get_web_search_tool() ✅ 托管的 Anthropic Web 搜索。
托管 MCP 工具 client.get_mcp_tool(name=..., url=...) ✅ 由 Anthropic 调用的远程 MCP 服务器。
本地 MCP 工具 MCPStreamableHTTPTool / MCPStdioTool ✅ 在你的进程中运行。

有关更丰富的示例 — 结合托管的 MCP、Web 搜索、扩展思维和 Anthropic Skills — 请参阅下面的托管工具。

代理功能

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()

托管工具

人类代理支持托管的工具,例如 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示例。

后续步骤