C# SDK
為 .NET 應用程式安裝並設定 Anthropic C# SDK,並整合 IChatClient
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 UserMessageParam { Content = "Hello, Claude" }],
Model = Model.ClaudeOpus5_5,
};
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」(區塊)串流的方法,每個區塊一抵達即可個別處理,而不必等待完整回應。串流方法通常對應於 SSE 或 JSONL 回應。
串流方法的名稱一律帶有 Streaming 後綴,即使它沒有非串流的版本也是如此。
這些串流方法會回傳 IAsyncEnumerable:
using System;
using Anthropic.Models.Messages;
MessageCreateParams parameters = new()
{
MaxTokens = 1024,
Messages = [new UserMessageParam { Content = "Hello, Claude" }],
Model = Model.ClaudeOpus5_5,
};
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 次,並在請求之間採用短暫的指數退避。
只有下列錯誤類型會被重試:
- 連線錯誤(例如,因網路連線問題所致)
- 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-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=debugOpenTelemetry 追蹤
當您的應用程式使用 AddSource("com.anthropic.sdk.csharp*") 將 SDK 的來源加入其 OpenTelemetry tracer provider 時,SDK 會為其傳送的每個請求發出一個 span。若要將這些 span 傳送至您的可觀測性平台,請參閱搭配 Claude SDK 設定 OpenTelemetry。
未記載的 API 功能
SDK 針對已記載的 API 提供型別,以便於使用。不過,它也支援使用 API 中未記載或尚未支援的部分。
平台整合
C# SDK 透過個別的 NuGet 套件支援下列平台:
- Agent Platform:
Anthropic.Vertex。用戶端設定請參閱 Claude Models on Google Cloud (Google managed)。 - 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。請將AnthropicFoundryClient搭配DefaultAnthropicFoundryCredentials.FromEnv()或明確的憑證使用。
新專案請使用 AnthropicBedrockMantleClient;AnthropicBedrockClient 則保留給使用 Bedrock InvokeModel API 的現有應用程式。
C# SDK 也透過 Anthropic.GoogleCloud 套件中的 AnthropicGoogleCloudClient 支援 Claude Models on Google Cloud (Anthropic managed)。此用戶端目前為 beta 版。請在選用的 GoogleCloudClientOptions 值上設定 WorkspaceId,或設定 ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID 環境變數。請參閱專案、位置與工作區解析。
語意化版本
此 SDK 的每個主要版本預設會在 anthropic-version 標頭中傳送一個 API 版本,且每個新的 API 版本都會伴隨一個新的主要版本。第一個傳送 2026-10-21 的主要版本是 13.0.0;請參閱遷移至 API 版本 2026-10-21。
此套件大致遵循 SemVer 慣例,但某些不具回溯相容性的變更可能會以次要版本發布:
- 對程式庫內部的變更,這些內部在技術上是公開的,但並非設計或記載供外部使用。
- 預期實際上不會影響絕大多數使用者的變更。
我們非常重視回溯相容性,以確保您能享有順暢的升級體驗。
其他資源
Was this page helpful?