Anthropic

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

直接模型推論與 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。

var apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY") ?? throw new InvalidOperationException("ANTHROPIC_API_KEY is not set.");
var model = Environment.GetEnvironmentVariable("ANTHROPIC_CHAT_MODEL_NAME") ?? "claude-haiku-4-5";
var maxTokens = 4096;
var thinkingTokens = 2048;

var agent = new AnthropicClient(new ClientOptions { ApiKey = apiKey })
    .AsAIAgent(
        model: model,
        clientFactory: (chatClient) => chatClient
            .AsBuilder()
            .ConfigureOptions(
                options => options.RawRepresentationFactory = (_) => new MessageCreateParams()
                {
                    Model = options.ModelId ?? model,
                    MaxTokens = options.MaxOutputTokens ?? maxTokens,
                    Messages = [],
                    Thinking = new ThinkingConfigParam(new ThinkingConfigEnabled(budgetTokens: thinkingTokens))
                })
            .Build());

Console.WriteLine("1. Non-streaming:");
var response = await agent.RunAsync("Solve this problem step by step: If a train travels 60 miles per hour and needs to cover 180 miles, how long will the journey take? Show your reasoning.");

Console.WriteLine("#### Start Thinking ####");
Console.WriteLine($"\e[92m{string.Join("\n", response.Messages.SelectMany(m => m.Contents.OfType<TextReasoningContent>().Select(c => c.Text)))}\e[0m");
Console.WriteLine("#### End Thinking ####");

Console.WriteLine("\n#### Final Answer ####");
Console.WriteLine(response.Text);

Console.WriteLine("Token usage:");
Console.WriteLine($"Input: {response.Usage?.InputTokenCount}, Output: {response.Usage?.OutputTokenCount}, {string.Join(", ", response.Usage?.AdditionalCounts ?? [])}");
Console.WriteLine();

Console.WriteLine("2. Streaming");
await foreach (var update in agent.RunStreamingAsync("Explain the theory of relativity in simple terms."))
{
    foreach (var item in update.Contents)
    {
        if (item is TextReasoningContent reasoningContent)
        {
            Console.WriteLine($"\e[92m{reasoningContent.Text}\e[0m");
        }
        else if (item is TextContent textContent)
        {
            Console.WriteLine(textContent.Text);
        }
    }
}

人類技能

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

using Microsoft.Extensions.AI;

string apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY") ?? throw new InvalidOperationException("ANTHROPIC_API_KEY is not set.");
// Skills require Claude 4.5 models (Sonnet 4.5, Haiku 4.5, or Opus 4.5)
string model = Environment.GetEnvironmentVariable("ANTHROPIC_CHAT_MODEL_NAME") ?? "claude-sonnet-4-5-20250929";

// Create the Anthropic client
AnthropicClient anthropicClient = new() { ApiKey = apiKey };

// List available Anthropic-managed skills (optional - API may not be available in all regions)
Console.WriteLine("Available Anthropic-managed skills:");
try
{
    SkillListPage skills = await anthropicClient.Beta.Skills.List(
        new SkillListParams { Source = "anthropic", Betas = [AnthropicBeta.Skills2025_10_02] });

    foreach (var skill in skills.Items)
    {
        Console.WriteLine($"  {skill.Source}: {skill.ID} (version: {skill.LatestVersionID})");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"  (Skills listing not available: {ex.Message})");
}

Console.WriteLine();

// Define the pptx skill - the SDK handles all beta flags and container configuration automatically
// when using AsAITool(), so no manual RawRepresentationFactory configuration is needed.
BetaSkillParams pptxSkill = new()
{
    Type = BetaSkillParamsType.Anthropic,
    SkillID = "pptx",
    Version = "latest"
};

// Create an agent with the pptx skill enabled.
// Skills require extended thinking and higher max tokens for complex file generation.
// The SDK's AsAITool() handles beta flags and container config automatically.
ChatClientAgent agent = anthropicClient.Beta.AsAIAgent(
    model: model,
    instructions: "You are a helpful agent for creating PowerPoint presentations.",
    tools: [pptxSkill.AsAITool()],
    clientFactory: (chatClient) => chatClient
        .AsBuilder()
        .ConfigureOptions(options =>
        {
            options.RawRepresentationFactory = (_) => new MessageCreateParams()
            {
                Model = model,
                MaxTokens = 20000,
                Messages = [],
                Thinking = new BetaThinkingConfigParam(
                    new BetaThinkingConfigEnabled(budgetTokens: 10000))
            };
        })
        .Build());

Console.WriteLine("Creating a presentation about renewable energy...\n");

}

// Collect generated files from CodeInterpreterToolResultContent outputs
List<HostedFileContent> hostedFiles = response.Messages
    .SelectMany(m => m.Contents.OfType<CodeInterpreterToolResultContent>())
    .Where(c => c.Outputs is not null)
    .SelectMany(c => c.Outputs!.OfType<HostedFileContent>())
    .ToList();

if (hostedFiles.Count > 0)
{
    Console.WriteLine("\n#### Generated Files ####");
    foreach (HostedFileContent file in hostedFiles)
    {
        Console.WriteLine($"  FileId: {file.FileId}");

        // Download the file using the Anthropic Files API
        using HttpResponse fileResponse = await anthropicClient.Beta.Files.Download(
            file.FileId,
            new FileDownloadParams { Betas = ["files-api-2025-04-14"] });

        // Save the file to disk
        string fileName = $"presentation_{file.FileId.Substring(0, 8)}.pptx";
        using FileStream fileStream = File.Create(fileName);
        Stream contentStream = await fileResponse.ReadAsStream();
        await contentStream.CopyToAsync(fileStream);

使用代理程式

代理程式是標準 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 選項。 代理框架會忽略這些選項,如果你提供這些選項,便會記錄警告。

使用自訂基礎網址

將 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。

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 範例。

下一步