Anthropic

O Microsoft Agent Framework dá suporte à criação de agentes que usam modelos Claude da Antropic.

Aviso

Trate o modelo ou a saída de embedding e as chamadas de ferramenta geradas por modelo, quando houver suporte, como entrada de aplicativo não confiável. Valide-os antes que o código execute efeitos colaterais ou renderize o conteúdo. Se você configurar um ponto de extremidade personalizado, verifique se confia em sua URL e operador.

Inferência de modelo direto versus o SDK do Claude Agent

O suporte à Anthropic no Agent Framework tem duas formas distintas.

Integration Tipo Ciclo do agente e ferramentas Usar quando
Inferência de modelo direto (esta página) AnthropicClient e variantes hospedadas pelo provedor, encapsuladas com Agent(client=...) Sua aplicação controla o loop do Agent Framework, as sessões, o middleware, as ferramentas de função e as ferramentas hospedadas pela Anthropic que são suportadas. Você quer o Claude como o modelo por trás de um agente padrão do Agent Framework de propriedade da aplicação.
SDK do agente de Anthropic Claude ClaudeAgent, construído diretamente O ambiente de execução do agente de codificação do Claude é responsável por sessões, permissões, ferramentas integradas de arquivo e shell e pelo comportamento do MCP. Você quer o ambiente de execução gerenciado do agente de programação Claude e o modelo de permissões.

Introdução

Adicione os pacotes NuGet necessários ao seu projeto.

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

Se você estiver usando Microsoft Foundry, adicione também:

dotnet add package Anthropic.Foundry --prerelease

Configuration

Variáveis de ambiente

Configure as variáveis de ambiente necessárias para autenticação antropática:

# 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

Você pode obter uma chave de API no Anthropic Console.

Para Microsoft Foundry com chave de API

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

Para Microsoft Foundry com CLI do Azure

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

Note

Ao usar o Microsoft Foundry com a CLI do Azure, verifique se você está conectado usando az login e se tem acesso ao recurso do Foundry. Para obter mais informações, consulte a documentação da CLI do Azure.

Criando um agente antropático

Criação básica de agente (API pública do Anthropic)

A maneira mais simples de criar um agente antropo usando a API pública:

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?"));

Usando o Anthropic no Foundry

Depois de configurar Anthropic no Microsoft Foundry, você poderá usá-lo com a autenticação de chave de API:

Autenticação da chave de 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?"));

autenticação de credencial Azure

Para ambientes em que as Credenciais do Azure são preferenciais:

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?"));

Aviso

DefaultAzureCredential é conveniente para o desenvolvimento, mas requer uma consideração cuidadosa na produção. Em produção, considere o uso de uma credencial específica (por exemplo, ManagedIdentityCredential) para evitar problemas de latência, investigação de credenciais não intencionais e possíveis riscos de segurança de mecanismos de fallback.

Tip

Consulte os exemplos do .NET para obter exemplos executáveis completos.

Tools

Tool Status Notes
Ferramentas de Funções ✅ Instâncias padrão AIFunction por meio de AIFunctionFactory.Create(...).
Aprovação da ferramenta ✅ Fornecido pelo cliente de chat que invoca a função; funciona com qualquer chamada de ferramenta de função.
Interpretador de Código ❌ Não há suporte para o cliente .NET Anthropic hoje.
Pesquisa de Arquivo ❌ Sem suporte.
Pesquisa na Web ❌ Não há suporte para o cliente .NET Anthropic hoje.
Ferramentas MCP hospedadas ✅ Suportado.
Ferramentas MCP locais ✅ Suportado.

Pensamento estendido

Configure o raciocínio da Anthropic por meio da representação bruta da mensagem e consuma TextReasoningContent a partir de respostas padrão ou via streaming.

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);
        }
    }
}

Habilidades antropáticas

As habilidades gerenciadas pela Anthropic podem criar arquivos no ambiente hospedado de execução de código. O exemplo lista as habilidades disponíveis, configura a habilidade PowerPoint e baixa o arquivo gerado.

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

Usando o agente

O agente é um AIAgent padrão e suporta todas as operações de agente padrão.

Consulte os tutoriais de introdução do Agente para obter mais informações sobre como executar e interagir com agentes.

Prerequisites

Instale o pacote Anthropic do Microsoft Agent Framework.

pip install agent-framework-anthropic --pre

Configuration

Variáveis de ambiente

Configure as variáveis de ambiente necessárias para autenticação antropática:

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

Como alternativa, você pode usar um .env arquivo na raiz do projeto:

ANTHROPIC_API_KEY=your-anthropic-api-key
ANTHROPIC_CHAT_MODEL=claude-sonnet-4-5-20250929
# ANTHROPIC_BASE_URL=https://your-custom-endpoint.com  # optional

Você pode obter uma chave de API no Anthropic Console.

Introdução

Importe as classes necessárias do Agent Framework:

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

Criando um agente antropático

Criação básica de agente

A maneira mais simples de criar um agente antropo:

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)

Usando configuração explícita

Você pode fornecer uma configuração explícita em vez de depender de variáveis de ambiente:

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)

O Anthropic SDK 1.x não dá suporte às opções temperature, top_k ou top_p. O Agent Framework ignora essas opções e registra um aviso se você as fornecer.

Usando uma URL base personalizada

Passe base_url diretamente para AnthropicClient para apontá-lo para qualquer ponto de extremidade compatível com o Anthropic, como uma implantação hospedada no Foundry. Isso permite que você mantenha o mesmo AnthropicClient código e altere apenas o ponto de extremidade, em vez de alternar para 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 volta para a variável de ANTHROPIC_BASE_URL ambiente quando não é passada explicitamente.

Usando o Anthropic no Foundry

Depois de configurar o Antropic no Foundry, verifique se você tem as seguintes variáveis de ambiente definidas:

ANTHROPIC_FOUNDRY_API_KEY="your-foundry-api-key"
ANTHROPIC_FOUNDRY_RESOURCE="your-foundry-resource-name"
ANTHROPIC_CHAT_MODEL="claude-haiku-4-5"

Em seguida, crie o agente da seguinte maneira:

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)

Note

Se você preferir configurar um endpoint completo compatível com Anthropic em vez de um nome de recurso, defina ANTHROPIC_FOUNDRY_BASE_URL junto com ANTHROPIC_FOUNDRY_API_KEY.

Usando Anthropic na Amazon Bedrock

AnthropicBedrockClient encaminha a inferência do modelo Claude por meio do 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"

Nenhum exemplo do Agent Framework executável está publicado no momento para AnthropicBedrockClient.

Usando Anthropic com o Google Vertex AI

AnthropicVertexClient encaminha a inferência do modelo Claude pelo Google Vertex 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>"

Nenhum exemplo do Agent Framework executável está publicado no momento para AnthropicVertexClient.

Lidar com falhas de requisição

Para execuções com streaming e sem streaming, as falhas nas solicitações do SDK da Anthropic são expostas por meio de exceções do Agent Framework. Falhas de autenticação e permissão geram ChatClientInvalidAuthException, outras falhas HTTP 4xx geram ChatClientInvalidRequestException, e todas as outras falhas do provedor geram ChatClientException.

Se a Anthropic invalidar uma resposta depois que uma chamada de função local for iniciada, o Agent Framework gerará ResponseInvalidatedException e não executará nem persistirá a chamada invalidada. Um consumidor de streaming pode já ter recebido atualizações parciais quando a exceção ocorre; descarte essas atualizações em vez de tratá-las como uma resposta concluída.

Use Catch ChatClientException quando o mesmo tratamento de erros deve ser aplicado em diferentes provedores de chat.

Continuar rodadas pausadas da ferramenta de servidor

Chamadas e resultados de ferramentas do servidor Anthropic retêm metadados de reprodução de propriedade do adaptador quando as mensagens são serializadas. Não modifique Content.additional_properties["anthropic"]["server_tool_block"]; ele pode conter o tipo de bloco nativo, o conteúdo do resultado estruturado e os valores criptografados que a Anthropic requer para reexecução.

Quando Anthropic retornapause_turn, o cliente continua automaticamente com as mesmas ferramentas quando cada bloco pode ser reconstruído fielmente. Ele faz no máximo 10 solicitações de continuação. Se o conteúdo nativo não puder ser reconstruído, uma chamada MCP transmitida não tem deltas de argumento retidos ou a resposta ainda estará pausada após o limite, o cliente retornará finish_reason="pause_turn" para que o aplicativo possa decidir como continuar.

Tools

AnthropicClient expõe fábricas de ferramentas do Anthropic hospedadas, juntamente com suporte a ferramentas de função padrão. Use client.get_*_tool(...) para criar uma ferramenta e passe-a por tools= em Agent(...).

Tool Fábrica/construção Status Notes
Ferramentas de Funções Passe qualquer função Python ou @ai_function ✅ Invocado localmente em seu processo de Python.
Aprovação da ferramenta Gerenciado pelo cliente de chat com invocação de função do framework ✅ Funciona com qualquer chamada de ferramenta de função.
Interpretador de Código client.get_code_interpreter_tool() ✅ Necessário para Anthropic Skills.
Pesquisa de Arquivo n/a ❌ Não exposto pela API do Anthropic.
Pesquisa na Web client.get_web_search_tool() ✅ Pesquisa na Web hospedada pela Anthropic.
Ferramentas MCP hospedadas client.get_mcp_tool(name=..., url=...) ✅ Servidores MCP remotos invocados por Anthropic.
Ferramentas MCP locais MCPStreamableHTTPTool / MCPStdioTool ✅ É executado em seu processo.

Para exemplos mais completos — combinando MCP hospedado, pesquisa na web, pensamento estendido e habilidades do Anthropic — consulte Ferramentas hospedadas abaixo.

Funcionalidades do agente

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)

Respostas de transmissão contínua

Obtenha respostas conforme elas são geradas para uma melhor experiência do usuário:

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

Ferramentas Hospedadas

Os agentes antropáticos dão suporte a ferramentas hospedadas, como pesquisa na Web, MCP (Protocolo de Contexto de Modelo) e execução de código:

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)

Pensamento Estendido (Raciocínio)

Anthropic dá suporte a recursos de pensamento estendido por meio do thinking, que permite que o modelo mostre seu processo de raciocínio.

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

Habilidades antropáticas

O Antropic fornece habilidades gerenciadas que estendem os recursos do agente, como a criação de apresentações do PowerPoint. As habilidades exigem que a ferramenta Interpretador de Código funcione:

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

Exemplo completo

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

Usando o agente

O agente é um Agent padrão e suporta todas as operações de agente padrão.

Consulte os tutoriais de introdução do Agente para obter mais informações sobre como executar e interagir com agentes.

Anthropic

O anthropicprovider pacote cria agentes usando a API Anthropic.

Installation

go get github.com/microsoft/agent-framework-go

Crie um agente do 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()

Opções personalizadas

Passe parâmetros específicos da Anthropic usando anthropicprovider.MessageNewParams:

resp, err := a.RunText(ctx, "Hello!",
    anthropicprovider.MessageNewParams(anthropic.MessageNewParams{
        MaxTokens: 500,
    }),
).Collect()

Tip

Consulte o exemplo de Anthropic para obter um exemplo completo.

Próximas Etapas