Udostępnij przez


Agenci Antropiczni

Program Microsoft Agent Framework obsługuje tworzenie agentów korzystających z modeli Claude firmy Anthropic.

Wprowadzenie

Dodaj wymagane pakiety NuGet do projektu.

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

Jeśli używasz usługi Azure Foundry, dodaj również następujące elementy:

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

Konfiguracja

Zmienne środowiskowe

Skonfiguruj wymagane zmienne środowiskowe na potrzeby uwierzytelniania antropicznego:

# 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

Klucz API można uzyskać z konsoli Anthropic.

Dla Azure Foundry z kluczem API

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

W przypadku usługi Azure Foundry z interfejsem wiersza polecenia platformy Azure

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

Uwaga / Notatka

W przypadku korzystania z usługi Azure Foundry za pomocą Azure CLI upewnij się, że jesteś zalogowany przy użyciu az login i masz dostęp do zasobu Azure Foundry. Aby uzyskać więcej informacji, zobacz dokumentację interfejsu wiersza polecenia platformy Azure.

Tworzenie agenta antropicznego

Tworzenie podstawowego agenta (antropiczny publiczny interfejs API)

Najprostszym sposobem utworzenia agenta antropicznego przy użyciu publicznego interfejsu API:

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

Korzystanie z Anthropic na platformie Azure Foundry z kluczem API

Po skonfigurowaniu aplikacji Anthropic w usłudze Azure Foundry możesz użyć jej z uwierzytelnianiem klucza interfejsu 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?"));

Korzystanie z Anthropic na Azure Foundry z poświadczeniami Azure (przykład poświadczeń Azure CLI)

W przypadku środowisk, w których preferowane są poświadczenia platformy 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 DefaultAzureCredential(), 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);
    }
}

Ostrzeżenie

DefaultAzureCredential jest wygodne do programowania, ale wymaga starannego rozważenia w środowisku produkcyjnym. W środowisku produkcyjnym rozważ użycie określonego poświadczenia (np. ManagedIdentityCredential), aby uniknąć problemów z opóźnieniami, niezamierzonego sondowania poświadczeń i potencjalnych zagrożeń bezpieczeństwa wynikających z mechanizmów awaryjnych.

Tip

Zobacz przykłady dla platformy .NET , aby uzyskać pełne przykłady możliwych do uruchomienia.

Korzystanie z agenta

Agent jest standardowy AIAgent i obsługuje wszystkie standardowe operacje agenta.

Aby uzyskać więcej informacji na temat uruchamiania agentów i interakcji z nimi, zobacz samouczki wprowadzające Agenta.

Wymagania wstępne

Zainstaluj pakiet antropiczny programu Microsoft Agent Framework.

pip install agent-framework-anthropic --pre

Konfiguracja

Zmienne środowiskowe

Skonfiguruj wymagane zmienne środowiskowe na potrzeby uwierzytelniania antropicznego:

# 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

Alternatywnie możesz użyć pliku .env w katalogu głównym projektu.

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

Klucz API można uzyskać z konsoli Anthropic.

Wprowadzenie

Zaimportuj wymagane klasy z programu Agent Framework:

import asyncio
from agent_framework.anthropic import AnthropicClient

Tworzenie agenta antropicznego

Tworzenie podstawowego agenta

Najprostszym sposobem utworzenia agenta antropicznego:

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)

Korzystanie z konfiguracji jawnej

Możesz podać jawną konfigurację zamiast polegać na zmiennych środowiskowych:

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)

Korzystanie z Anthropic na platformie Foundry

Po skonfigurowaniu platformy Anthropic w witrynie Foundry upewnij się, że ustawiono następujące zmienne środowiskowe:

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

Następnie utwórz agenta w następujący sposób:

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)

Uwaga: to wymaga zainstalowania anthropic>=0.74.0.

Funkcje agenta

Narzędzia funkcji

Wyposażyć agenta w funkcje niestandardowe:

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)

Odpowiedzi w strumieniowaniu

Uzyskuj odpowiedzi w miarę ich generowania w celu lepszego doświadczenia użytkownika.

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

Narzędzia hostowane

Agenciropijni obsługują hostowane narzędzia, takie jak wyszukiwanie w Internecie, protokół MCP (protokół kontekstu modelu) i wykonywanie kodu:

from agent_framework.anthropic import AnthropicClient

async def hosted_tools_example():
    client = AnthropicClient()
    agent = client.as_agent(
        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(),
        ],
        max_tokens=20000,
    )

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

Rozszerzone Myślenie (Rozumowanie)

Anthropic wspiera rozszerzone możliwości myślenia za pomocą thinking funkcji, która umożliwia modelowi pokazanie jego procesu rozumowania.

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

async def thinking_example():
    client = AnthropicClient()
    agent = client.as_agent(
        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 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()

Umiejętności antropotyczne

Anthropic zapewnia zarządzane umiejętności, które rozszerzają możliwości agenta, takie jak tworzenie prezentacji programu PowerPoint. Umiejętności wymagają, aby narzędzie Interpreter kodu działało:

from agent_framework import 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=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[HostedFileContent] = []
    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.")

Kompletny przykład

# Copyright (c) Microsoft. All rights reserved.

import asyncio
from random import randint
from typing import Annotated

from agent_framework import 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 = AnthropicClient(
    ).as_agent(
        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 = 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(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())

Korzystanie z agenta

Agent jest standardowy Agent i obsługuje wszystkie standardowe operacje agenta.

Aby uzyskać więcej informacji na temat uruchamiania agentów i interakcji z nimi, zobacz samouczki wprowadzające Agenta.

Dalsze kroki