Anthropic

Microsoft Agent Framework는 Anthropic의 Claude 모델을 사용하는 에이전트 만들기를 지원합니다.

직접 모델 유추와 Claude 에이전트 SDK 비교

에이전트 프레임워크의 Anthropic 지원에는 두 가지 고유한 형식이 있습니다.

통합 Type 에이전트 루프 및 도구 사용 시기
직접 모델 유추(이 페이지) AnthropicClient 로 래핑된 공급자 호스팅 변형 Agent(client=...) 애플리케이션은 에이전트 프레임워크 루프, 세션, 미들웨어, 함수 도구 및 지원되는 Anthropic 호스트된 도구를 소유합니다. 표준 애플리케이션 소유 에이전트 프레임워크 에이전트 뒤에 있는 모델로 Claude를 원합니다.
Anthropic Claude 에이전트 SDK ClaudeAgent, 직접 생성 Claude의 코딩 에이전트 런타임은 세션, 권한, 기본 제공 파일 및 셸 도구 및 MCP 동작을 소유합니다. Claude의 관리형 코딩 에이전트 런타임 및 권한 모델을 원합니다.

Getting Started

필요한 NuGet 패키지를 프로젝트에 추가합니다.

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

Microsoft Foundry를 사용하는 경우 다음을 추가합니다.

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

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

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 에이전트 생성하기

기본 에이전트 만들기(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 상태 Notes
함수 도구 AIFunction를 통한 표준 AIFunctionFactory.Create(...) 인스턴스
도구 승인 함수 호출 채팅 클라이언트에서 제공합니다. 함수 도구 호출과 함께 작동합니다.
코드 해석기 현재 .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 기술을 구성하고, 생성된 파일을 다운로드합니다.

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.LatestVersion})");
    }
}
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");

// Run the agent with a request to create a presentation
AgentResponse response = await agent.RunAsync("Create a simple 3-slide presentation about renewable energy sources. Include a title slide, a slide about solar energy, and a slide about wind energy.");
// 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);

        Console.WriteLine($"  Saved to: {fileName}");

에이전트 사용

에이전트는 표준 AIAgent 이며 모든 표준 에이전트 작업을 지원합니다.

에이전트를 실행하고 상호 작용하는 방법에 대한 자세한 내용은 에이전트 시작 자습서 를 참조하세요.

사전 요구 사항

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

Anthropic 콘솔에서 API 키를 가져올 수 있습니다.

Getting Started

에이전트 프레임워크에서 필요한 클래스를 가져옵니다.

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

Anthropic 에이전트 생성하기

기본 에이전트 만들기

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)

사용자 지정 기본 URL 사용

base_urlAnthropicClient에 직접 전달하여 Foundry에서 호스팅된 배포와 같은 Anthropic 호환 엔드포인트를 가리키도록 합니다. 동일한 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_FOUNDRY_BASE_URLANTHROPIC_FOUNDRY_API_KEY 대신 전체 Anthropic 호환 가능한 엔드포인트를 구성하려면 ANTHROPIC_FOUNDRY_BASE_URLANTHROPIC_FOUNDRY_API_KEY를 설정하십시오.

아마존 베드록에서 Anthropic 사용

AnthropicBedrockClient 는 Amazon Bedrock을 통해 클로드 모델 유추를 라우팅합니다.

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 꼭짓점 AI에서 Anthropic 사용

AnthropicVertexClient 는 Google 꼭짓점 AI를 통해 클로드 모델 유추를 라우팅합니다.

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있지 않습니다.

Tools

AnthropicClient는 표준 함수 도구 지원 기능과 함께 Anthropic에서 호스팅하는 도구 팩토리를 제공합니다. 도구를 빌드하고 이를 전달하는 tools=Agent(...)데 사용합니다client.get_*_tool(...).

Tool 공장/시공 상태 Notes
함수 도구 Python 호출 가능한 객체 또는 @ai_function를 전달하세요. Python 프로세스에서 로컬로 호출됩니다.
도구 승인 프레임워크의 함수 호출 채팅 클라이언트에서 처리 모든 함수 도구 호출과 호환됩니다.
코드 해석기 client.get_code_interpreter_tool() Anthropic 스킬에 필요합니다.
파일 검색 n/a Anthropic API에서 노출되지 않습니다.
웹 검색 client.get_web_search_tool() 호스트된 Anthropic 웹 검색.
호스트된 MCP 도구 client.get_mcp_tool(name=..., url=...) Anthropic에 의해 호출되는 원격 MCP 서버
로컬 MCP 도구 MCPStreamableHTTPTool / MCPStdioTool 사용자의 프로세스에서 실행됩니다.

호스트된 MCP, 웹 검색, 확장 사고 및 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 에이전트는 웹 검색, 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 agent_framework import Agent, 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 = 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):
            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 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를 사용하여 에이전트를 만듭니다.

설치

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 샘플을 참조하세요.

다음 단계