C# SDK
安裝並設定 Anthropic C# SDK,以用於具備 IChatClient 整合的 .NET 應用程式
Anthropic C# SDK 讓以 C# 撰寫的應用程式能夠便利地存取 Claude API。
安裝
從 NuGet 安裝套件:
dotnet add package Anthropic需求
此函式庫需要 .NET Standard 2.0 或更新版本。
使用方式
using System;
using Anthropic;
using Anthropic.Models.Messages;
AnthropicClient client = new();
MessageCreateParams parameters = new()
{
MaxTokens = 1024,
Messages =
[
new()
{
Role = Role.User,
Content = "Hello, Claude",
},
],
Model = Model.ClaudeOpus5,
};
var message = await client.Messages.Create(parameters);
foreach (var block in message.Content)
{
if (block.TryPickText(out var textBlock))
{
Console.WriteLine(textBlock.Text);
}
}如需了解包括 Workload Identity Federation(工作負載身分聯合)在內的驗證選項,請參閱驗證。如果您的 API 金鑰是可存取多個工作區的個人或服務帳戶金鑰,請在 anthropic-workspace-id 請求標頭中設定工作區 ID;選擇工作區說明了此 SDK 的逐請求選項。
用戶端設定
使用環境變數設定用戶端:
using Anthropic;
// 使用 ANTHROPIC_API_KEY、ANTHROPIC_AUTH_TOKEN 與 ANTHROPIC_BASE_URL 環境變數進行設定
AnthropicClient client = new();或手動設定:
using Anthropic;
AnthropicClient client = new() { ApiKey = "my-anthropic-api-key" };或結合使用這兩種方式。
可用選項請參閱下表:
| 屬性 | 環境變數 | 必填 | 預設值 |
|---|---|---|---|
ApiKey | ANTHROPIC_API_KEY | false | - |
AuthToken | ANTHROPIC_AUTH_TOKEN | false | - |
BaseUrl | ANTHROPIC_BASE_URL | true | "https://api.anthropic.com" |
修改設定
若要暫時使用修改過的用戶端設定,同時重複使用相同的連線與執行緒集區,請在任何用戶端或服務上呼叫 WithOptions:
using System;
var message = await client
.WithOptions(options =>
options with
{
BaseUrl = "https://example.com",
Timeout = TimeSpan.FromSeconds(42),
}
)
.Messages.Create(parameters);
Console.WriteLine(message);使用 with 運算式可以輕鬆建構修改後的選項。
WithOptions 方法不會影響原始的用戶端或服務。
串流
SDK 定義了會回傳回應「區塊」(chunk)串流的方法,每個區塊一抵達即可個別處理,而不必等待完整回應。「Streaming」(串流)方法通常對應於 SSE 或 JSONL 回應。
串流方法的名稱一律帶有 Streaming 後綴,即使它沒有非串流的變體也是如此。
這些串流方法會回傳 IAsyncEnumerable:
using System;
using Anthropic.Models.Messages;
MessageCreateParams parameters = new()
{
MaxTokens = 1024,
Messages =
[
new()
{
Role = Role.User,
Content = "Hello, Claude",
},
],
Model = Model.ClaudeOpus5,
};
await foreach (var message in client.Messages.CreateStreaming(parameters))
{
Console.WriteLine(message);
}錯誤處理
SDK 會擲出自訂的非受檢(unchecked)例外類型:
AnthropicApiException:API 錯誤的基底類別。各 HTTP 狀態碼所擲出的例外子類別請參閱下表:
| 狀態碼 | 例外 |
|---|---|
| 400 | AnthropicBadRequestException |
| 401 | AnthropicUnauthorizedException |
| 403 | AnthropicForbiddenException |
| 404 | AnthropicNotFoundException |
| 422 | AnthropicUnprocessableEntityException |
| 429 | AnthropicRateLimitException |
| 5xx | Anthropic5xxException |
| 其他 | AnthropicUnexpectedStatusCodeException |
此外,所有 4xx 錯誤皆繼承自 Anthropic4xxException。
-
AnthropicSseException:在初始 HTTP 回應成功之後,於 SSE 串流期間遇到錯誤時擲出。 -
AnthropicIOException:I/O 網路錯誤。 -
AnthropicInvalidDataException:無法解讀已成功剖析的資料。例如,存取一個應為必填的屬性,但 API 卻意外地在回應中省略了它。 -
AnthropicException:所有例外的基底類別。
重試
SDK 預設會自動重試 2 次,並在請求之間採用短暫的指數退避(exponential backoff)。
僅會重試下列錯誤類型:
- 連線錯誤(例如因網路連線問題所致)
- 408 Request Timeout
- 409 Conflict
- 429 Rate Limit
- 5xx Internal
API 也可能明確指示 SDK 重試或不重試某個請求。
若要設定自訂的重試次數,請使用 MaxRetries 屬性設定用戶端:
using Anthropic;
AnthropicClient client = new() { MaxRetries = 3 };或使用 WithOptions 設定單一方法呼叫:
using System;
var message = await client
.WithOptions(options =>
options with { MaxRetries = 3 }
)
.Messages.Create(parameters);
Console.WriteLine(message);逾時
請求預設在 10 分鐘後逾時。
若要設定自訂逾時,請使用 Timeout 選項設定用戶端:
using System;
using Anthropic;
AnthropicClient client = new() { Timeout = TimeSpan.FromSeconds(42) };或使用 WithOptions 設定單一方法呼叫:
using System;
var message = await client
.WithOptions(options =>
options with { Timeout = TimeSpan.FromSeconds(42) }
)
.Messages.Create(parameters);
Console.WriteLine(message);分頁
SDK 定義了會回傳分頁結果清單的方法。它提供便利的方式,讓您可以一次存取一頁結果,或跨所有頁面逐項存取結果。
自動分頁
若要遍歷所有頁面的全部結果,請使用 Paginate 方法,它會視需要自動擷取更多頁面。此方法會回傳 IAsyncEnumerable:
using System;
var page = await client.Messages.Batches.List(parameters);
await foreach (var item in page.Paginate())
{
Console.WriteLine(item);
}手動分頁
若要存取個別頁面的項目並手動請求下一頁,請使用 Items 屬性,以及 HasNext 與 Next 方法:
var page = await client.Messages.Batches.List();
while (true)
{
foreach (var item in page.Items)
{
Console.WriteLine(item);
}
if (!page.HasNext())
{
break;
}
page = await page.Next();
}回應驗證
在極少數情況下,API 可能會回傳與預期類型不符的回應。預設情況下,SDK 在此情況下不會擲出例外。只有在您直接存取該屬性時,它才會擲出 AnthropicInvalidDataException。
如果您希望事先檢查回應是否完全符合類型,可以呼叫 Validate:
var message = await client.Messages.Create(parameters);
message.Validate();或使用 ResponseValidation 選項設定用戶端:
using Anthropic;
AnthropicClient client = new() { ResponseValidation = true };或使用 WithOptions 設定單一方法呼叫:
using System;
var message = await client
.WithOptions(options =>
options with { ResponseValidation = true }
)
.Messages.Create(parameters);
Console.WriteLine(message);IChatClient 整合
SDK 提供了 Microsoft.Extensions.AI.Abstractions 函式庫中 IChatClient 介面的實作。這使得 AnthropicClient(以及 Anthropic.Services.IBetaService)能夠與其他整合這些核心抽象的函式庫搭配使用。例如,MCP C# SDK(ModelContextProtocol)函式庫中的工具可以直接與透過 IChatClient 公開的 AnthropicClient 搭配使用。
using Anthropic;
using Microsoft.Extensions.AI;
using ModelContextProtocol.Client;
// 使用 ANTHROPIC_API_KEY、ANTHROPIC_AUTH_TOKEN 與 ANTHROPIC_BASE_URL 環境變數進行設定
AnthropicClient client = new();
IChatClient chatClient = client.AsIChatClient("claude-opus-5")
.AsBuilder()
.UseFunctionInvocation()
.Build();
// 使用 MCP C# SDK 中的 McpClient
McpClient learningServer = await McpClient.CreateAsync(
new HttpClientTransport(new() { Endpoint = new("https://learn.microsoft.com/api/mcp") }));
ChatOptions options = new() { Tools = [.. await learningServer.ListToolsAsync()] };
Console.WriteLine(await chatClient.GetResponseAsync("Tell me about IChatClient", options));請求與回應
若要向 Claude API 傳送請求,請建構一個 Params 類別的實例,並將其傳遞給對應的用戶端方法。收到回應後,它會被反序列化為 C# 類別的實例。
例如,client.Messages.Create 應以 MessageCreateParams 的實例呼叫,並會回傳 Task<Message> 的實例。
進階用法
二進位回應
SDK 定義了會回傳二進位回應的方法,用於不一定需要剖析的 API 回應,例如非 JSON 資料。
這些方法會回傳 HttpResponse:
using System;
using Anthropic.Models.Files;
FileDownloadParams parameters = new() { FileID = "file_id" };
var response = await client.Files.Download(parameters);
Console.WriteLine(response);若要將回應內容儲存至檔案或任何 Stream,請使用 CopyToAsync 方法:
using System.IO;
using var response = await client.Files.Download(parameters);
using var contentStream = await response.ReadAsStream();
using var fileStream = File.Open(path, FileMode.OpenOrCreate);
await contentStream.CopyToAsync(fileStream); // Or any other Stream原始回應
SDK 定義了會將回應反序列化為 C# 類別實例的方法。若要存取回應標頭、狀態碼或原始回應主體,請在用戶端或服務上的任何 HTTP 方法呼叫前加上 WithRawResponse:
var response = await client.WithRawResponse.Messages.Create(parameters);
var statusCode = response.StatusCode;
var headers = response.Headers;原始的 HttpResponseMessage 也可以透過 RawMessage 屬性存取。
對於非串流回應,您可以視需要將回應反序列化為 C# 類別的實例:
using System;
using Anthropic.Models.Messages;
var response = await client.WithRawResponse.Messages.Create(parameters);
Message deserialized = await response.Deserialize();
Console.WriteLine(deserialized);對於串流回應,您可以視需要將回應反序列化為 IAsyncEnumerable:
using System;
var response = await client.WithRawResponse.Messages.CreateStreaming(parameters);
await foreach (var item in response.Enumerate())
{
Console.WriteLine(item);
}日誌記錄
透過設定環境變數來啟用除錯日誌記錄:
export ANTHROPIC_LOG=debug未記載的 API 功能
SDK 具備型別定義,以便於使用已記載的 API。不過,它也支援使用 API 中未記載或尚未支援的部分。
平台整合
C# SDK 透過個別的 NuGet 套件支援下列平台:
- Agent Platform:
Anthropic.Vertex。用戶端設定請參閱 Google Cloud 上的 Claude。 - Bedrock:
Anthropic.Bedrock。針對 Messages-API Bedrock 端點請使用AnthropicBedrockMantleClient,或使用AnthropicBedrockClient(bedrock-runtime路徑)。AnthropicBedrockMantleClient接受一個選用的MantleAwsClientOptions設定物件;AnthropicBedrockClient接受AnthropicBedrockCredentialsHelper.FromEnv()或明確的憑證。 - Claude Platform on AWS:
Anthropic.Aws。請使用AnthropicAwsClient;在用戶端上設定WorkspaceId,或設定ANTHROPIC_AWS_WORKSPACE_ID環境變數(請參閱工作區)。目前以 beta 形式提供。 - Foundry:
Anthropic.Foundry。請搭配DefaultAnthropicFoundryCredentials.FromEnv()或明確的憑證使用AnthropicFoundryClient。
新專案請使用 AnthropicBedrockMantleClient;AnthropicBedrockClient 則保留給使用 Bedrock InvokeModel API 的既有應用程式。
語意化版本
此套件大致遵循 SemVer 慣例,但某些不向後相容的變更可能會以次要版本發布:
- 對函式庫內部的變更,這些內部在技術上是公開的,但並非預期供外部使用,也未針對外部使用加以記載。
- 預期在實務上不會影響絕大多數使用者的變更。
我們非常重視向後相容性,以確保您能享有順暢的升級體驗。
其他資源
Was this page helpful?