共用方式為


人類特工

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

使用者入門

將必要的 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 金鑰。

針對 Azure Foundry 使用 API Key

$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 Foundry 搭配 Azure CLI 時,請確保你已使用 Azure CLI az login 登入,並能存取 Azure Foundry 資源。 如需詳細資訊,請參閱 Azure CLI 檔

創建人類代理

基本代理建立(Anthropic Public 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?"));

在 Azure Foundry 上使用 API Key 的 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 Foundry 上使用 Anthropic 搭配 Azure 憑證(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 AzureCliCredential(), 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);
    }
}

使用代理程式

代理程式是標準 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_ID="claude-sonnet-4-5-20250929"  # or your preferred model

您也可以在專案根目錄中使用一個 .env 檔案:

ANTHROPIC_API_KEY=your-anthropic-api-key
ANTHROPIC_CHAT_MODEL_ID=claude-sonnet-4-5-20250929

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

使用者入門

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

import asyncio
from agent_framework.anthropic import AnthropicClient

創建人類代理

基本代理程式創建

創建一個 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_id="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)

在 Foundry 上使用 Anthropic

在 Foundry 上設定好 Anthropic 後,請確保你設定了以下環境變數:

ANTHROPIC_FOUNDRY_API_KEY="your-foundry-api-key"
ANTHROPIC_FOUNDRY_RESOURCE="your-foundry-resource-name"

接著建立代理人如下:

from agent_framework.anthropic import AnthropicClient
from anthropic import AsyncAnthropicFoundry

async def foundry_example():
    agent = AnthropicClient(
        anthropic_client=AsyncAnthropicFoundry()
    ).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>=0.74.0

代理功能

功能工具

為您的代理程式配備自訂功能:

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_stream(query):
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print()

託管工具

Anthropic 代理程式支援託管工具,例如 Web 搜尋、MCP(模型上下文協定)和程式碼執行:

from agent_framework import HostedMCPTool, HostedWebSearchTool

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

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

延伸思考(推理)

Anthropic 透過該 thinking 功能支援擴展思考能力,該功能允許模型展示其推理過程:

from agent_framework import TextReasoningContent, UsageContent
from agent_framework.anthropic import AnthropicClient

async def thinking_example():
    agent = AnthropicClient().as_agent(
        name="DocsAgent",
        instructions="You are a helpful agent.",
        tools=[HostedWebSearchTool()],
        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_stream(query):
        for content in chunk.contents:
            if isinstance(content, TextReasoningContent):
                # Display thinking in a different color
                print(f"\033[32m{content.text}\033[0m", end="", flush=True)
            if isinstance(content, UsageContent):
                print(f"\n\033[34m[Usage: {content.details}]\033[0m\n", end="", flush=True)
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print()

人類技能

Anthropic 提供可管理的技能,擴展客服人員的能力,例如製作 PowerPoint 簡報。 技能需要程式碼解譯工具才能運作:

from agent_framework import HostedCodeInterpreterTool, HostedFileContent
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=HostedCodeInterpreterTool(),
        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[HostedFileContent] = []
    async for chunk in agent.run_stream(query):
        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.")

使用代理程式

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

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

後續步驟