Repository Public
1---2title: C# SDK3url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/csharp4description: Install and configure the Anthropic C# SDK for .NET applications with IChatClient integration5---67The Anthropic C# SDK provides convenient access to the Claude API from applications written in C#.89<Info>10 For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers C#-specific SDK features and configuration.11</Info>1213<Warning>14 As of version 10+, the `Anthropic` package is now the official Anthropic SDK for C#. Package versions 3.X and below were previously used for the tryAGI community-built SDK, which has moved to [`tryAGI.Anthropic`](https://www.nuget.org/packages/tryagi.Anthropic/). If you need to continue using the former client in your project, update your package reference to `tryAGI.Anthropic`.15</Warning>1617## Installation1819Install the package from [NuGet](https://www.nuget.org/packages/Anthropic):2021```bash22dotnet add package Anthropic23```2425## Requirements2627This library requires .NET Standard 2.0 or later.2829## Usage3031```csharp32using System;33using Anthropic;34using Anthropic.Models.Messages;3536AnthropicClient client = new();3738MessageCreateParams parameters = new()39{40 MaxTokens = 1024,41 Messages =42 [43 new()44 {45 Role = Role.User,46 Content = "Hello, Claude",47 },48 ],49 Model = Model.ClaudeOpus5,50};5152var message = await client.Messages.Create(parameters);5354foreach (var block in message.Content)55{56 if (block.TryPickText(out var textBlock))57 {58 Console.WriteLine(textBlock.Text);59 }60}61```6263For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). If your API key is a [personal or service account key](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) with access to multiple workspaces, set the workspace ID in the `anthropic-workspace-id` request header; [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace) shows the per-request option for this SDK.6465## Client configuration6667Configure the client using environment variables:6869```csharp70using Anthropic;7172// Configured using the ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN and ANTHROPIC_BASE_URL environment variables73AnthropicClient client = new();74```7576Or manually:7778```csharp79using Anthropic;8081AnthropicClient client = new() { ApiKey = "my-anthropic-api-key" };82```8384Or using a combination of the two approaches.8586See this table for the available options:8788| Property | Environment variable | Required | Default value |89| ----------- | ---------------------- | -------- | ----------------------------- |90| `ApiKey` | `ANTHROPIC_API_KEY` | false | - |91| `AuthToken` | `ANTHROPIC_AUTH_TOKEN` | false | - |92| `BaseUrl` | `ANTHROPIC_BASE_URL` | true | `"https://api.anthropic.com"` |9394### Modifying configuration9596To temporarily use a modified client configuration, while reusing the same connection and thread pools, call `WithOptions` on any client or service:9798```csharp99using System;100101var message = await client102 .WithOptions(options =>103 options with104 {105 BaseUrl = "https://example.com",106 Timeout = TimeSpan.FromSeconds(42),107 }108 )109 .Messages.Create(parameters);110111Console.WriteLine(message);112```113114Using a [`with` expression](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression) makes it easy to construct the modified options.115116The `WithOptions` method does not affect the original client or service.117118## Streaming119120The SDK defines methods that return response "chunk" streams, where each chunk can be individually processed as soon as it arrives instead of waiting on the full response. Streaming methods generally correspond to [SSE](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) or [JSONL](https://jsonlines.org) responses.121122A streaming method always has a `Streaming` suffix in its name, even if it doesn't have a non-streaming variant.123124These streaming methods return [`IAsyncEnumerable`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.iasyncenumerable-1):125126```csharp127using System;128using Anthropic.Models.Messages;129130MessageCreateParams parameters = new()131{132 MaxTokens = 1024,133 Messages =134 [135 new()136 {137 Role = Role.User,138 Content = "Hello, Claude",139 },140 ],141 Model = Model.ClaudeOpus5,142};143144await foreach (var message in client.Messages.CreateStreaming(parameters))145{146 Console.WriteLine(message);147}148```149150## Error handling151152The SDK throws custom unchecked exception types:153154* `AnthropicApiException`: Base class for API errors. See this table for which exception subclass is thrown for each HTTP status code:155156| Status | Exception |157| ------ | ---------------------------------------- |158| 400 | `AnthropicBadRequestException` |159| 401 | `AnthropicUnauthorizedException` |160| 403 | `AnthropicForbiddenException` |161| 404 | `AnthropicNotFoundException` |162| 422 | `AnthropicUnprocessableEntityException` |163| 429 | `AnthropicRateLimitException` |164| 5xx | `Anthropic5xxException` |165| others | `AnthropicUnexpectedStatusCodeException` |166167Additionally, all 4xx errors inherit from `Anthropic4xxException`.168169* `AnthropicSseException`: thrown for errors encountered during SSE streaming after a successful initial HTTP response.170171* `AnthropicIOException`: I/O networking errors.172173* `AnthropicInvalidDataException`: Failure to interpret successfully parsed data. For example, when accessing a property that's supposed to be required, but the API unexpectedly omitted it from the response.174175* `AnthropicException`: Base class for all exceptions.176177## Retries178179The SDK automatically retries 2 times by default, with a short exponential backoff between requests.180181Only the following error types are retried:182183* Connection errors (for example, because of a network connectivity problem)184* 408 Request Timeout185* 409 Conflict186* 429 Rate Limit187* 5xx Internal188189The API may also explicitly instruct the SDK to retry or not retry a request.190191To set a custom number of retries, configure the client using the `MaxRetries` property:192193```csharp194using Anthropic;195196AnthropicClient client = new() { MaxRetries = 3 };197```198199Or configure a single method call using `WithOptions`:200201```csharp202using System;203204var message = await client205 .WithOptions(options =>206 options with { MaxRetries = 3 }207 )208 .Messages.Create(parameters);209210Console.WriteLine(message);211```212213## Timeouts214215Requests time out after 10 minutes by default.216217To set a custom timeout, configure the client using the `Timeout` option:218219```csharp220using System;221using Anthropic;222223AnthropicClient client = new() { Timeout = TimeSpan.FromSeconds(42) };224```225226Or configure a single method call using `WithOptions`:227228```csharp229using System;230231var message = await client232 .WithOptions(options =>233 options with { Timeout = TimeSpan.FromSeconds(42) }234 )235 .Messages.Create(parameters);236237Console.WriteLine(message);238```239240## Pagination241242The SDK defines methods that return paginated lists of results. It provides convenient ways to access the results either one page at a time or item-by-item across all pages.243244### Auto-pagination245246To iterate through all results across all pages, use the `Paginate` method, which automatically fetches more pages as needed. The method returns an [`IAsyncEnumerable`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.iasyncenumerable-1):247248```csharp249using System;250251var page = await client.Messages.Batches.List(parameters);252await foreach (var item in page.Paginate())253{254 Console.WriteLine(item);255}256```257258### Manual pagination259260To access individual page items and manually request the next page, use the `Items` property, and `HasNext` and `Next` methods:261262```csharp263var page = await client.Messages.Batches.List();264while (true)265{266 foreach (var item in page.Items)267 {268 Console.WriteLine(item);269 }270 if (!page.HasNext())271 {272 break;273 }274 page = await page.Next();275}276```277278## Response validation279280In rare cases, the API may return a response that doesn't match the expected type. By default, the SDK does not throw an exception in this case. It throws `AnthropicInvalidDataException` only if you directly access the property.281282If you would prefer to check that the response is completely well-typed upfront, then either call `Validate`:283284```csharp285var message = await client.Messages.Create(parameters);286message.Validate();287```288289Or configure the client using the `ResponseValidation` option:290291```csharp292using Anthropic;293294AnthropicClient client = new() { ResponseValidation = true };295```296297Or configure a single method call using `WithOptions`:298299```csharp300using System;301302var message = await client303 .WithOptions(options =>304 options with { ResponseValidation = true }305 )306 .Messages.Create(parameters);307308Console.WriteLine(message);309```310311## IChatClient integration312313The SDK provides an implementation of the `IChatClient` interface from the `Microsoft.Extensions.AI.Abstractions` library. This enables `AnthropicClient` (and `Anthropic.Services.IBetaService`) to be used with other libraries that integrate with these core abstractions. For example, tools in the MCP C# SDK (`ModelContextProtocol`) library can be used directly with an `AnthropicClient` exposed through `IChatClient`.314315```csharp316using Anthropic;317using Microsoft.Extensions.AI;318using ModelContextProtocol.Client;319320// Configured using the ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN and ANTHROPIC_BASE_URL environment variables321AnthropicClient client = new();322323IChatClient chatClient = client.AsIChatClient("claude-opus-5")324 .AsBuilder()325 .UseFunctionInvocation()326 .Build();327328// Using McpClient from the MCP C# SDK329McpClient learningServer = await McpClient.CreateAsync(330 new HttpClientTransport(new() { Endpoint = new("https://learn.microsoft.com/api/mcp") }));331332ChatOptions options = new() { Tools = [.. await learningServer.ListToolsAsync()] };333334Console.WriteLine(await chatClient.GetResponseAsync("Tell me about IChatClient", options));335```336337## Requests and responses338339To send a request to the Claude API, build an instance of a `Params` class and pass it to the corresponding client method. When the response is received, it's deserialized into an instance of a C# class.340341For example, `client.Messages.Create` should be called with an instance of `MessageCreateParams`, and it will return an instance of `Task<Message>`.342343## Advanced usage344345### Binary responses346347The SDK defines methods that return binary responses, which are used for API responses that shouldn't necessarily be parsed, like non-JSON data.348349These methods return `HttpResponse`:350351```csharp352using System;353using Anthropic.Models.Files;354355FileDownloadParams parameters = new() { FileID = "file_id" };356357var response = await client.Files.Download(parameters);358359Console.WriteLine(response);360```361362To save the response content to a file, or any [`Stream`](https://learn.microsoft.com/en-us/dotnet/api/system.io.stream), use the [`CopyToAsync`](https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.copytoasync) method:363364```csharp365using System.IO;366367using var response = await client.Files.Download(parameters);368using var contentStream = await response.ReadAsStream();369using var fileStream = File.Open(path, FileMode.OpenOrCreate);370await contentStream.CopyToAsync(fileStream); // Or any other Stream371```372373### Raw responses374375The SDK defines methods that deserialize responses into instances of C# classes. To access response headers, status code, or the raw response body, prefix any HTTP method call on a client or service with `WithRawResponse`:376377```csharp378var response = await client.WithRawResponse.Messages.Create(parameters);379var statusCode = response.StatusCode;380var headers = response.Headers;381```382383The raw `HttpResponseMessage` can also be accessed through the `RawMessage` property.384385For non-streaming responses, you can deserialize the response into an instance of a C# class if needed:386387```csharp388using System;389using Anthropic.Models.Messages;390391var response = await client.WithRawResponse.Messages.Create(parameters);392Message deserialized = await response.Deserialize();393Console.WriteLine(deserialized);394```395396For streaming responses, you can deserialize the response to an `IAsyncEnumerable` if needed:397398```csharp399using System;400401var response = await client.WithRawResponse.Messages.CreateStreaming(parameters);402await foreach (var item in response.Enumerate())403{404 Console.WriteLine(item);405}406```407408### Logging409410<Warning>411 All log messages are intended for debugging only. The format and content of log messages may change between releases.412</Warning>413414Enable debug logging by setting an environment variable:415416```bash417export ANTHROPIC_LOG=debug418```419420### Undocumented API functionality421422The SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.423424## Platform integrations425426<Note>427 For detailed platform setup guides with code examples, see:428429 * [Amazon Bedrock](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock)430 * [Amazon Bedrock (Opus 4.6 and earlier)](https://platform.claude.com/docs/en/build-with-claude/claude-on-amazon-bedrock-legacy)431 * [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws)432 * [Google Cloud](https://platform.claude.com/docs/en/build-with-claude/claude-on-vertex-ai)433 * [Microsoft Foundry](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry)434</Note>435436The C# SDK supports the following platforms through separate NuGet packages:437438* **Agent Platform:** `Anthropic.Vertex`. See [Claude on Google Cloud](https://platform.claude.com/docs/en/build-with-claude/claude-on-vertex-ai) for client setup.439* **Bedrock:** `Anthropic.Bedrock`. Use `AnthropicBedrockMantleClient` for the Messages-API Bedrock endpoint, or `AnthropicBedrockClient` (`bedrock-runtime` path). `AnthropicBedrockMantleClient` takes an optional `MantleAwsClientOptions` config object; `AnthropicBedrockClient` accepts `AnthropicBedrockCredentialsHelper.FromEnv()` or explicit credentials.440* **Claude Platform on AWS:** `Anthropic.Aws`. Use `AnthropicAwsClient`; set `WorkspaceId` on the client or the `ANTHROPIC_AWS_WORKSPACE_ID` environment variable (see [Workspaces](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws#workspaces)). Available in beta.441* **Foundry:** `Anthropic.Foundry`. Use `AnthropicFoundryClient` with `DefaultAnthropicFoundryCredentials.FromEnv()` or explicit credentials.442443Use `AnthropicBedrockMantleClient` for new projects; `AnthropicBedrockClient` remains for existing applications using the Bedrock `InvokeModel` API.444445## Semantic versioning446447This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backward-incompatible changes may be released as minor versions:4484491. Changes to library internals that are technically public but not intended or documented for external use.4502. Changes that aren't expected to impact the vast majority of users in practice.451452Backward-compatibility is taken seriously to ensure you can rely on a smooth upgrade experience.453454## Additional resources455456* [GitHub repository](https://github.com/anthropics/anthropic-sdk-csharp)457* [NuGet package](https://www.nuget.org/packages/Anthropic)458* [API reference](https://platform.claude.com/docs/en/api/overview)459* [Streaming Messages](https://platform.claude.com/docs/en/build-with-claude/streaming)460