Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
Microsoft Agent Framework, Antropik'in Claude modellerini kullanan aracılar oluşturmayı destekler.
Doğrudan model çıkarımı ve Claude Aracısı SDK'sı karşılaştırması
Agent Framework'teki Anthropic desteğinin iki ayrı biçimi vardır.
| Bütünleştirme | Türü | Aracı döngüsü ve araçları | Şu durumlarda kullanın: |
|---|---|---|---|
| Doğrudan model çıkarımı (bu sayfa) |
AnthropicClient ve sağlayıcı tarafından barındırılan çeşitler, ile sarmalanmış Agent(client=...) |
Uygulamanız Agent Framework döngüsüne, oturumlara, ara yazılıma, işlev araçlarına ve desteklenen Anthropic barındırılan araçlara sahiptir. | Claude'un standart bir uygulamaya ait Agent Framework aracısının arkasındaki model olmasını istiyorsunuz. |
| Anthropic Claude Aracısı SDK'sı |
ClaudeAgent, doğrudan inşa edilir |
Claude'un kodlama aracısı çalışma zamanı oturumlara, izinlere, yerleşik dosya ve kabuk araçlarına ve MCP davranışına sahiptir. | Claude'un yönetilen kodlama aracısı çalışma zamanını ve izin modelini istiyorsunuz. |
Getting Started
Projenize gerekli NuGet paketlerini ekleyin.
dotnet add package Microsoft.Agents.AI.Anthropic --prerelease
Microsoft Foundry kullanıyorsanız şunları da ekleyin:
dotnet add package Anthropic.Foundry --prerelease
dotnet add package Azure.Identity
Configuration
Ortam Değişkenleri
Antropik kimlik doğrulaması için gerekli ortam değişkenlerini ayarlayın:
# 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
Antropik Konsolu'ndan bir API anahtarı alabilirsiniz.
API Anahtarı ile Microsoft Dökümhanesi için
$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 ile Microsoft Dökümhanesi için
$env:ANTHROPIC_RESOURCE="your-foundry-resource-name" # Subdomain before .services.ai.azure.com
$env:ANTHROPIC_CHAT_MODEL_NAME="claude-haiku-4-5"
Uyarı
Azure CLI ile Microsoft Foundry kullanırken, ile az login oturum açtığınızdan ve Foundry kaynağına erişiminiz olduğundan emin olun. Daha fazla bilgi için Azure CLI belgelerine bakın.
Antropik Aracı Oluşturma
Temel Aracı Oluşturma (Antropik Genel API)
Genel API'yi kullanarak Antropik aracı oluşturmanın en basit yolu:
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?"));
Anthropic'i Dökümhanede Kullanma
Microsoft Foundry'de Anthropic ayarladıktan sonra API anahtarı kimlik doğrulaması ile kullanabilirsiniz:
API anahtarı kimlik doğrulaması
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?"));
kimlik bilgisi kimlik doğrulaması Azure
Azure Kimlik Bilgilerinin tercih edildiği ortamlar için:
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 geliştirme için uygundur ancak üretimde dikkatli bir şekilde dikkate alınması gerekir. Üretimde gecikme sorunları, istenmeyen kimlik bilgisi yoklama ve geri dönüş mekanizmalarından kaynaklanan olası güvenlik risklerini önlemek için belirli bir kimlik bilgisi (ör ManagedIdentityCredential. ) kullanmayı göz önünde bulundurun.
İpucu
Çalıştırılabilir örneklerin tamamı için .NET örneklerine bakın.
Tools
| Araç | Statü | Notlar |
|---|---|---|
| İşlev Araçları | ✅ | Standart AIFunction örnekleri AIFunctionFactory.Create(...) aracılığıyla. |
| Araç Onayı | ✅ | İşlev çağıran sohbet istemcisi tarafından sağlanır; herhangi bir işlev aracı çağrısıyla çalışır. |
| Kod Yorumlayıcısı | ❌ | bugün .NET Anthropic istemcisi tarafından desteklenmiyor. |
| Dosya Arama | ❌ | Desteklenmiyor. |
| Web Araması | ❌ | bugün .NET Anthropic istemcisi tarafından desteklenmiyor. |
| Barındırılan MCP Araçları | ✅ | Supported. |
| Yerel MCP Araçları | ✅ | Supported. |
Genişletilmiş düşünce
Ham ileti gösterimi aracılığıyla Anthropic mantığı yapılandırın ve normal veya akış yanıtlarından kullanınTextReasoningContent.
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);
}
}
}
Antropik Beceriler
Anthropic yönetilen beceriler barındırılan kod yürütme ortamı aracılığıyla dosya oluşturabilir. Örnekte kullanılabilir beceriler listelenir, PowerPoint becerisini yapılandırılır ve oluşturulan dosya indirilir.
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}");
Ajanı Kullanma
Aracı standart bir AIAgent'dir ve tüm standart aracı işlemleri destekler.
Aracıları çalıştırma ve aracılarla etkileşim kurma hakkında daha fazla bilgi için bkz. Aracı kullanmaya başlama öğreticileri .
Prerequisites
Microsoft Agent Framework Antropik paketini yükleyin.
pip install agent-framework-anthropic --pre
Configuration
Ortam Değişkenleri
Antropik kimlik doğrulaması için gerekli ortam değişkenlerini ayarlayın:
# 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"
Alternatif olarak, proje kökünde bir .env dosya kullanabilirsiniz:
ANTHROPIC_API_KEY=your-anthropic-api-key
ANTHROPIC_CHAT_MODEL=claude-sonnet-4-5-20250929
# ANTHROPIC_BASE_URL=https://your-custom-endpoint.com # optional
Antropik Konsolu'ndan bir API anahtarı alabilirsiniz.
Getting Started
Aracı Çerçevesi'nden gerekli sınıfları içeri aktarın:
import asyncio
from agent_framework import Agent
from agent_framework.anthropic import AnthropicClient
Antropik Aracı Oluşturma
Temel Ajan Oluşturma
Antropik aracı oluşturmanın en basit yolu:
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)
Açık Yapılandırma Kullanma
Ortam değişkenlerine güvenmek yerine açık yapılandırma sağlayabilirsiniz:
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)
Özel Temel URL kullanma
base_url'yi doğrudan AnthropicClient'e göndererek Foundry tarafından barındırılan dağıtım gibi Anthropic uyumlu bir uç noktaya yönlendirin. Bu, aynı AnthropicClient kodu korumanızı ve öğeye geçiş yapmak yerine sadece uç noktayı değiştirmenize olanak tanır:
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 açıkça geçirilmediğinde ortam değişkenine ANTHROPIC_BASE_URL geri döner.
Anthropic'i Dökümhanede Kullanma
Anthropic'i Foundry'de ayarladıktan sonra aşağıdaki ortam değişkenlerini ayarladığınızdan emin olun:
ANTHROPIC_FOUNDRY_API_KEY="your-foundry-api-key"
ANTHROPIC_FOUNDRY_RESOURCE="your-foundry-resource-name"
ANTHROPIC_CHAT_MODEL="claude-haiku-4-5"
Ardından aracıyı aşağıdaki gibi oluşturun:
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)
Uyarı
Kaynak adı yerine tam Antropik uyumlu bir uç nokta yapılandırmayı tercih ediyorsanız, ANTHROPIC_FOUNDRY_BASE_URL öğesini ANTHROPIC_FOUNDRY_API_KEY ek olarak ayarlayın.
Amazon Bedrock'ta Anthropic kullanma
AnthropicBedrockClient Claude modeli çıkarımlarını Amazon Bedrock aracılığıyla yönlendirir.
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"
şu anda için AnthropicBedrockClientçalıştırılabilir Agent Framework örneği yayımlanmaz.
Google Köşe yapay zekada Anthropic kullanma
AnthropicVertexClient Claude modeli çıkarımlarını Google Vertex AI aracılığıyla yönlendirir.
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>"
şu anda için AnthropicVertexClientçalıştırılabilir Agent Framework örneği yayımlanmaz.
Tools
AnthropicClient standart fonksiyon araçları desteğinin yanı sıra Anthropic tarafından barındırılan araç fabrikalarını da sunar. Bir araç oluşturmak ve üzerinden geçirmek tools=Agent(...)için kullanınclient.get_*_tool(...).
| Araç | Fabrika / inşaat | Statü | Notlar |
|---|---|---|---|
| İşlev Araçları | Herhangi bir Python çağrılabilirini veya @ai_function geçirin |
✅ | Python işleminizde yerel olarak çağrılır. |
| Araç Onayı | Çerçevenin işlev çağıran sohbet istemcisi tarafından işlenir | ✅ | Herhangi bir işlev/aracı çağrısıyla çalışır. |
| Kod Yorumlayıcısı | client.get_code_interpreter_tool() |
✅ | Anthropic Skills için gereklidir. |
| Dosya Arama | Yok | ❌ | Anthropic API aracılığıyla sunulmaz. |
| Web Araması | client.get_web_search_tool() |
✅ | Anthropic barındırmalı web’de arama. |
| Barındırılan MCP Araçları | client.get_mcp_tool(name=..., url=...) |
✅ | Anthropic tarafından çağrılan uzak MCP sunucuları. |
| Yerel MCP Araçları | MCPStreamableHTTPTool / MCPStdioTool |
✅ | İşleminizde çalışır. |
Barındırılan MCP, web araması, genişletilmiş düşünme ve Anthropic Becerilerini birleştiren daha zengin örnekler için aşağıdaki Hosted Tools bölümüne bakın.
Temsilci Özellikleri
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)
Akış Yanıtları
Daha iyi bir kullanıcı deneyimi için oluşturulan yanıtları alın:
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()
Barındırılan Araçlar
Antropik aracılar web araması, MCP (Model Bağlam Protokolü) ve kod yürütme gibi barındırılan araçları destekler:
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)
Genişletilmiş Düşünme (Akıl Yürütme)
Antropik, modelin thinking akıl yürütme sürecini göstermesini sağlayan özellik aracılığıyla genişletilmiş düşünme özelliklerini destekler:
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()
Antropik Beceriler
Antropik, PowerPoint sunuları oluşturma gibi aracı özelliklerini genişleten yönetilen beceriler sağlar. Becerilerin çalışması için Kod Yorumlayıcı aracının çalışması gerekir:
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.")
Tam örnek
# 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())
Ajanı Kullanma
Aracı standart bir Agent'dir ve tüm standart aracı işlemleri destekler.
Aracıları çalıştırma ve aracılarla etkileşim kurma hakkında daha fazla bilgi için bkz. Aracı kullanmaya başlama öğreticileri .
Anthropic
Paket, anthropicprovider Anthropic API'sini kullanarak aracılar oluşturur.
Kurulum
go get github.com/microsoft/agent-framework-go
Anthropic ajanı oluşturun
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()
Özel seçenekler
Anthropic'e özgü parametreleri anthropicprovider.MessageNewParams kullanarak iletin:
resp, err := a.RunText(ctx, "Hello!",
anthropicprovider.MessageNewParams(anthropic.MessageNewParams{
MaxTokens: 500,
}),
).Collect()
İpucu
Tam bir örnek için Anthropic örneğine bakın.