Remarque
L’accès à cette page requiert une autorisation. Vous pouvez essayer de vous connecter ou de modifier des répertoires.
L’accès à cette page requiert une autorisation. Vous pouvez essayer de modifier des répertoires.
Microsoft Agent Framework prend en charge la création d’agents qui utilisent les modèles Claude d’Anthropic.
Getting Started
Ajoutez les packages NuGet requis à votre projet.
dotnet add package Microsoft.Agents.AI.Anthropic --prerelease
Si vous utilisez Azure Foundry, ajoutez également :
dotnet add package Anthropic.Foundry --prerelease
dotnet add package Azure.Identity
Paramétrage
Variables d’environnement
Configurez les variables d’environnement requises pour l’authentification anthropice :
# 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
Vous pouvez obtenir une clé API à partir de la console anthropice.
Pour les points de terminaison Anthropic hébergés par un fournisseur, le package Python expose également AnthropicFoundryClient, AnthropicBedrockClient et AnthropicVertexClient.
Pour Azure Foundry avec la clé 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"
Pour Azure Foundry avec Azure CLI
$env:ANTHROPIC_RESOURCE="your-foundry-resource-name" # Subdomain before .services.ai.azure.com
$env:ANTHROPIC_DEPLOYMENT_NAME="claude-haiku-4-5"
Note
Lorsque vous utilisez Azure Foundry avec Azure CLI, assurez-vous d'être connecté avec az login et d'avoir accès à la ressource Azure Foundry. Pour plus d’informations, consultez la documentation Azure CLI.
Création d’un agent anthropique
Création d’agent de base (API publique anthropice)
La façon la plus simple de créer un agent anthropic à l’aide de l’API publique :
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?"));
Utilisation d’Anthropic sur Azure Foundry avec la clé API
Une fois que vous avez configuré Anthropic sur Azure Foundry, vous pouvez l’utiliser avec l’authentification par clé 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?"));
Utilisation d’Anthropic sur Azure Foundry avec des informations d’identification Azure (exemple d’informations d’identification Azure Cli)
Pour les environnements où les informations d’identification Azure sont préférées :
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);
}
}
Avertissement
DefaultAzureCredential est pratique pour le développement, mais nécessite une considération minutieuse en production. En production, envisagez d’utiliser des informations d’identification spécifiques (par exemple ManagedIdentityCredential) pour éviter les problèmes de latence, la détection involontaire des informations d’identification et les risques de sécurité potentiels liés aux mécanismes de secours.
Conseil / Astuce
Consultez les exemples .NET pour obtenir des exemples exécutables complets.
Tools
| Tool | État | Remarques |
|---|---|---|
| Outils de fonction | ✅ | Instances standard AIFunction via AIFunctionFactory.Create(...). |
| Approbation de l’outil | ✅ | Fourni par le client de chat qui invoque la fonction ; fonctionne avec tout appel à un outil-fonction. |
| Interpréteur de code | ❌ | Non pris en charge par le client .NET Anthropic aujourd’hui. |
| Recherche de fichiers | ❌ | Non pris en charge. |
| Recherche web | ❌ | Non pris en charge par le client .NET Anthropic aujourd’hui. |
| Outils MCP hébergés | ✅ | Supported. |
| Outils MCP locaux | ✅ | Supported. |
Utilisation de l’agent
L’agent est standard AIAgent et prend en charge toutes les opérations d’agent standard.
Pour plus d’informations sur l’exécution et l’interaction avec les agents, consultez les didacticiels de prise en main de l’agent .
Prerequisites
Installez le package Microsoft Agent Framework Anthropic.
pip install agent-framework-anthropic --pre
Paramétrage
Variables d’environnement
Configurez les variables d’environnement requises pour l’authentification anthropice :
# 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"
Vous pouvez également utiliser un .env fichier à la racine de votre projet :
ANTHROPIC_API_KEY=your-anthropic-api-key
ANTHROPIC_CHAT_MODEL=claude-sonnet-4-5-20250929
# ANTHROPIC_BASE_URL=https://your-custom-endpoint.com # optional
Vous pouvez obtenir une clé API à partir de la console anthropice.
Getting Started
Importez les classes requises à partir de Agent Framework :
import asyncio
from agent_framework.anthropic import AnthropicClient
Création d’un agent anthropique
Création d'un agent basique
La façon la plus simple de créer un agent anthropice :
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)
Utilisation de la configuration explicite
Vous pouvez fournir une configuration explicite au lieu de vous appuyer sur des variables d’environnement :
async def explicit_config_example():
agent = AnthropicClient(
model="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)
Utilisation d’une URL de base personnalisée
Passez base_url directement à AnthropicClient pour le pointer vers n’importe quel point de terminaison compatible Anthropic, tel qu’un déploiement hébergé par Foundry. Cela vous permet de conserver le même AnthropicClient code et de modifier uniquement le point de terminaison, plutôt que de passer à AnthropicFoundryClient:
async def custom_base_url_example():
agent = AnthropicClient(
model="claude-haiku-4-5",
api_key="your-api-key-here",
base_url="https://your-foundry-resource.services.ai.azure.com/models/anthropic",
).as_agent(
name="HelpfulAssistant",
instructions="You are a helpful assistant.",
)
result = await agent.run("What can you do?")
print(result.text)
base_url revient à la variable d'environnement ANTHROPIC_BASE_URL lorsqu'elle n'est pas passée explicitement.
Utilisation d’Anthropic sur Foundry
Une fois que vous avez configuré Anthropic on Foundry, vérifiez que les variables d’environnement suivantes sont définies :
ANTHROPIC_FOUNDRY_API_KEY="your-foundry-api-key"
ANTHROPIC_FOUNDRY_RESOURCE="your-foundry-resource-name"
ANTHROPIC_CHAT_MODEL="claude-haiku-4-5"
Créez ensuite l’agent comme suit :
from agent_framework.foundry import AnthropicFoundryClient
async def foundry_example():
agent = AnthropicFoundryClient().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)
Note
Si vous préférez configurer un point de terminaison complet compatible avec Anthropic au lieu d’un nom de ressource, définissez ANTHROPIC_FOUNDRY_BASE_URL en plus de ANTHROPIC_FOUNDRY_API_KEY.
Tools
AnthropicClient propose les fabriques d’outils hébergées par Anthropic ainsi que la prise en charge des outils de fonction standard. Utilisez client.get_*_tool(...) pour créer un outil et le faire passer via tools= sur as_agent(...) ou Agent(...).
| Tool | Usine / construction | État | Remarques |
|---|---|---|---|
| Outils de fonction | Transmettez un objet appelable Python ou @ai_function |
✅ | Appelé localement dans votre processus de Python. |
| Approbation de l’outil | Géré par le client de conversation d’invocation de fonctions du framework | ✅ | Fonctionne avec tout appel de fonction-outil. |
| Interpréteur de code | client.get_code_interpreter_tool() |
✅ | Obligatoire pour Anthropic Skills. |
| Recherche de fichiers | n/a | ❌ | Non exposé par l’API Anthropic. |
| Recherche web | client.get_web_search_tool() |
✅ | Recherche web hébergée Anthropic. |
| Outils MCP hébergés | client.get_mcp_tool(name=..., url=...) |
✅ | Serveurs MCP distants appelés par Anthropic. |
| Outils MCP locaux | MCPStreamableHTTPTool / MCPStdioTool |
✅ | S’exécute au sein de votre processus. |
Pour obtenir des exemples plus riches : combinaison de MCP hébergés, de recherche web, de pensée étendue et de compétences Anthropic, consultez Hosted Tools ci-dessous.
Fonctionnalités de l’agent
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)
Réponses en continu
Obtenez des réponses à mesure qu’elles sont générées pour une meilleure expérience utilisateur :
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()
Outils hébergés
Les agents anthropices prennent en charge les outils hébergés tels que la recherche web, MCP (Model Context Protocol) et l’exécution du code :
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)
Pensée étendue (raisonnement)
Anthropic prend en charge les capacités de pensée étendues par le biais de la thinking fonctionnalité, ce qui permet au modèle de montrer son processus de raisonnement :
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()
Compétences anthropices
Anthropic fournit des compétences managées qui étendent les fonctionnalités de l’agent, telles que la création de présentations PowerPoint. Les compétences nécessitent que l’outil Interpréteur de code fonctionne :
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.")
Exemple complet
# 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())
Utilisation de l’agent
L’agent est standard Agent et prend en charge toutes les opérations d’agent standard.
Pour plus d’informations sur l’exécution et l’interaction avec les agents, consultez les didacticiels de prise en main de l’agent .