Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Build LLM-powered apps with the Anthropic Claude API or SDK across Python, TypeScript, Java, Go, Ruby, C#, and PHP.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
csharp/claude-api.md
1# Claude API — C#23> **Note:** The C# SDK is the official Anthropic SDK for C#. Tool use is supported via the Messages API. A class-annotation-based tool runner is not available; use raw tool definitions with JSON schema. The SDK also supports Microsoft.Extensions.AI IChatClient integration with function invocation.45## Installation67```bash8dotnet add package Anthropic9```1011## Client Initialization1213```csharp14using Anthropic;1516// Default (uses ANTHROPIC_API_KEY env var)17AnthropicClient client = new();1819// Explicit API key (use environment variables — never hardcode keys)20AnthropicClient client = new() {21ApiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")22};23```2425---2627## Basic Message Request2829```csharp30using Anthropic.Models.Messages;3132var parameters = new MessageCreateParams33{34Model = Model.ClaudeOpus4_6,35MaxTokens = 16000,36Messages = [new() { Role = Role.User, Content = "What is the capital of France?" }]37};38var response = await client.Messages.Create(parameters);3940// ContentBlock is a union wrapper. .Value unwraps to the variant object,41// then OfType<T> filters to the type you want. Or use the TryPick* idiom42// shown in the Thinking section below.43foreach (var text in response.Content.Select(b => b.Value).OfType<TextBlock>())44{45Console.WriteLine(text.Text);46}47```4849---5051## Streaming5253```csharp54using Anthropic.Models.Messages;5556var parameters = new MessageCreateParams57{58Model = Model.ClaudeOpus4_6,59MaxTokens = 64000,60Messages = [new() { Role = Role.User, Content = "Write a haiku" }]61};6263await foreach (RawMessageStreamEvent streamEvent in client.Messages.CreateStreaming(parameters))64{65if (streamEvent.TryPickContentBlockDelta(out var delta) &&66delta.Delta.TryPickText(out var text))67{68Console.Write(text.Text);69}70}71```7273**`RawMessageStreamEvent` TryPick methods** (naming drops the `Message`/`Raw` prefix): `TryPickStart`, `TryPickDelta`, `TryPickStop`, `TryPickContentBlockStart`, `TryPickContentBlockDelta`, `TryPickContentBlockStop`. There is no `TryPickMessageStop` — use `TryPickStop`.7475---7677## Thinking7879**Adaptive thinking is the recommended mode for Claude 4.6+ models.** Claude decides dynamically when and how much to think.8081```csharp82using Anthropic.Models.Messages;8384var response = await client.Messages.Create(new MessageCreateParams85{86Model = Model.ClaudeOpus4_6,87MaxTokens = 16000,88// ThinkingConfigParam? implicitly converts from the concrete variant classes —89// no wrapper needed.90Thinking = new ThinkingConfigAdaptive(),91Messages =92[93new() { Role = Role.User, Content = "Solve: 27 * 453" },94],95});9697// ThinkingBlock(s) precede TextBlock in Content. TryPick* narrows the union.98foreach (var block in response.Content)99{100if (block.TryPickThinking(out ThinkingBlock? t))101{102Console.WriteLine($"[thinking] {t.Thinking}");103}104else if (block.TryPickText(out TextBlock? text))105{106Console.WriteLine(text.Text);107}108}109```110111> **Deprecated:** `new ThinkingConfigEnabled { BudgetTokens = N }` (fixed-budget extended thinking) still works on Claude 4.6 but is deprecated. Use adaptive thinking above.112113Alternative to `TryPick*`: `.Select(b => b.Value).OfType<ThinkingBlock>()` (same LINQ pattern as the Basic Message example).114115---116117## Tool Use118119### Defining a tool120121`Tool` (NOT `ToolParam`) with an `InputSchema` record. `InputSchema.Type` is auto-set to `"object"` by the constructor — don't set it. `ToolUnion` has an implicit conversion from `Tool`, triggered by the collection expression `[...]`.122123```csharp124using System.Text.Json;125using Anthropic.Models.Messages;126127var parameters = new MessageCreateParams128{129Model = Model.ClaudeSonnet4_6,130MaxTokens = 16000,131Tools = [132new Tool {133Name = "get_weather",134Description = "Get the current weather in a given location",135InputSchema = new() {136Properties = new Dictionary<string, JsonElement> {137["location"] = JsonSerializer.SerializeToElement(138new { type = "string", description = "City name" }),139},140Required = ["location"],141},142},143],144Messages = [new() { Role = Role.User, Content = "Weather in Paris?" }],145};146```147148Derived from `anthropic-sdk-csharp/src/Anthropic/Models/Messages/Tool.cs` and `ToolUnion.cs:799` (implicit conversion).149150See [shared tool use concepts](../shared/tool-use-concepts.md) for the loop pattern.151### Converting response content to the follow-up assistant message152153When echoing Claude's response back in the assistant turn, **there is no `.ToParam()` helper** — manually reconstruct each `ContentBlock` variant as its `*Param` counterpart. Do NOT use `new ContentBlockParam(block.Json)`: it compiles and serializes, but `.Value` stays `null` so `TryPick*`/`Validate()` fail (degraded JSON pass-through, not the typed path).154155```csharp156using Anthropic.Models.Messages;157158Message response = await client.Messages.Create(parameters);159160// No .ToParam() — reconstruct per variant. Implicit conversions from each161// *Param type to ContentBlockParam mean no explicit wrapper.162List<ContentBlockParam> assistantContent = [];163List<ContentBlockParam> toolResults = [];164foreach (ContentBlock block in response.Content)165{166if (block.TryPickText(out TextBlock? text))167{168assistantContent.Add(new TextBlockParam { Text = text.Text });169}170else if (block.TryPickThinking(out ThinkingBlock? thinking))171{172// Signature MUST be preserved — the API rejects tampering173assistantContent.Add(new ThinkingBlockParam174{175Thinking = thinking.Thinking,176Signature = thinking.Signature,177});178}179else if (block.TryPickRedactedThinking(out RedactedThinkingBlock? redacted))180{181assistantContent.Add(new RedactedThinkingBlockParam { Data = redacted.Data });182}183else if (block.TryPickToolUse(out ToolUseBlock? toolUse))184{185// ToolUseBlock has required Caller; ToolUseBlockParam.Caller is optional — don't copy it186assistantContent.Add(new ToolUseBlockParam187{188ID = toolUse.ID,189Name = toolUse.Name,190Input = toolUse.Input,191});192// Execute the tool; collect ONE result per tool_use block — the API193// rejects the follow-up if any tool_use ID lacks a matching tool_result.194string result = ExecuteYourTool(toolUse.Name, toolUse.Input);195toolResults.Add(new ToolResultBlockParam196{197ToolUseID = toolUse.ID,198Content = result,199});200}201}202203// Follow-up: prior messages + assistant echo + user tool_result(s)204List<MessageParam> followUpMessages =205[206.. parameters.Messages,207new() { Role = Role.Assistant, Content = assistantContent },208new() { Role = Role.User, Content = toolResults },209];210```211212`ToolResultBlockParam` has no tuple constructor — use the object initializer. `Content` is a string-or-list union; a plain `string` implicitly converts.213214---215216## Context Editing / Compaction (Beta)217218**Beta-namespace prefix is inconsistent** (source-verified against `src/Anthropic/Models/Beta/Messages/*.cs` @ 12.9.0). No prefix: `MessageCreateParams`, `MessageCountTokensParams`, `Role`. **Everything else has the `Beta` prefix**: `BetaMessageParam`, `BetaMessage`, `BetaContentBlock`, `BetaToolUseBlock`, all block param types. The unprefixed `Role` WILL collide with `Anthropic.Models.Messages.Role` if you import both namespaces (CS0104). Safest: import only Beta; if mixing, alias the beta `Role`:219220```csharp221using Anthropic.Models.Beta.Messages;222using NonBeta = Anthropic.Models.Messages; // only if you also need non-beta types223// Now: MessageCreateParams, BetaMessageParam, Role (beta's), NonBeta.Role (if needed)224```225226227`BetaMessage.Content` is `IReadOnlyList<BetaContentBlock>` — a 15-variant discriminated union. Narrow with `TryPick*`. **Response `BetaContentBlock` is NOT assignable to param `BetaContentBlockParam`** — there's no `.ToParam()` in C#. Round-trip by converting each block:228229```csharp230using Anthropic.Models.Beta.Messages;231232var betaParams = new MessageCreateParams // no Beta prefix — one of only 2 unprefixed233{234Model = Model.ClaudeOpus4_6,235MaxTokens = 16000,236Betas = ["compact-2026-01-12"],237ContextManagement = new BetaContextManagementConfig238{239Edits = [new BetaCompact20260112Edit()],240},241Messages = messages,242};243BetaMessage resp = await client.Beta.Messages.Create(betaParams);244245foreach (BetaContentBlock block in resp.Content)246{247if (block.TryPickCompaction(out BetaCompactionBlock? compaction))248{249// Content is nullable — compaction can fail server-side250Console.WriteLine($"compaction summary: {compaction.Content}");251}252}253254// Context-edit metadata lives on a separate nullable field255if (resp.ContextManagement is { } ctx)256{257foreach (var edit in ctx.AppliedEdits)258Console.WriteLine($"cleared {edit.ClearedInputTokens} tokens");259}260261// ROUND-TRIP: BetaMessageParam.Content is BetaMessageParamContent (a string|list262// union). It implicit-converts from List<BetaContentBlockParam>, NOT from the263// response's IReadOnlyList<BetaContentBlock>. Convert each block:264List<BetaContentBlockParam> paramBlocks = [];265foreach (var b in resp.Content)266{267if (b.TryPickText(out var t)) paramBlocks.Add(new BetaTextBlockParam { Text = t.Text });268else if (b.TryPickCompaction(out var c)) paramBlocks.Add(new BetaCompactionBlockParam { Content = c.Content });269// ... other variants as needed270}271messages.Add(new BetaMessageParam { Role = Role.Assistant, Content = paramBlocks });272```273274All 15 `BetaContentBlock.TryPick*` variants: `Text`, `Thinking`, `RedactedThinking`, `ToolUse`, `ServerToolUse`, `WebSearchToolResult`, `WebFetchToolResult`, `CodeExecutionToolResult`, `BashCodeExecutionToolResult`, `TextEditorCodeExecutionToolResult`, `ToolSearchToolResult`, `McpToolUse`, `McpToolResult`, `ContainerUpload`, `Compaction`.275276**`BetaToolUseBlock.Input` is `IReadOnlyDictionary<string, JsonElement>`** — index by key then call the `JsonElement` extractor:277278```csharp279if (block.TryPickToolUse(out BetaToolUseBlock? tu))280{281int a = tu.Input["a"].GetInt32();282string s = tu.Input["name"].GetString()!;283}284```285286---287288## Effort Parameter289290Effort is nested under `OutputConfig`, NOT a top-level property. `ApiEnum<string, Effort>` has an implicit conversion from the enum, so assign `Effort.High` directly.291292```csharp293OutputConfig = new OutputConfig { Effort = Effort.High },294```295296Values: `Effort.Low`, `Effort.Medium`, `Effort.High`, `Effort.Max`. Combine with `Thinking = new ThinkingConfigAdaptive()` for cost-quality control.297298---299300## Prompt Caching301302`System` takes `MessageCreateParamsSystem?` — a union of `string` or `List<TextBlockParam>`. There is no `SystemTextBlockParam`; use plain `TextBlockParam`. The implicit conversion needs the concrete `List<TextBlockParam>` type (array literals won't convert). For placement patterns and the silent-invalidator audit checklist, see `shared/prompt-caching.md`.303304```csharp305System = new List<TextBlockParam> {306new() {307Text = longSystemPrompt,308CacheControl = new CacheControlEphemeral(), // auto-sets Type = "ephemeral"309},310},311```312313Optional `Ttl` on `CacheControlEphemeral`: `new() { Ttl = Ttl.Ttl1h }` or `Ttl.Ttl5m`. `CacheControl` also exists on `Tool.CacheControl` and top-level `MessageCreateParams.CacheControl`.314315Verify hits via `response.Usage.CacheCreationInputTokens` / `response.Usage.CacheReadInputTokens`.316317---318319## Token Counting320321```csharp322MessageTokensCount result = await client.Messages.CountTokens(new MessageCountTokensParams {323Model = Model.ClaudeOpus4_6,324Messages = [new() { Role = Role.User, Content = "Hello" }],325});326long tokens = result.InputTokens;327```328329`MessageCountTokensParams.Tools` uses a different union type (`MessageCountTokensTool`) than `MessageCreateParams.Tools` (`ToolUnion`) — if you're passing tools, the compiler will tell you when it matters.330331---332333## Structured Output334335```csharp336OutputConfig = new OutputConfig {337Format = new JsonOutputFormat {338Schema = new Dictionary<string, JsonElement> {339["type"] = JsonSerializer.SerializeToElement("object"),340["properties"] = JsonSerializer.SerializeToElement(341new { name = new { type = "string" } }),342["required"] = JsonSerializer.SerializeToElement(new[] { "name" }),343},344},345},346```347348`JsonOutputFormat.Type` is auto-set to `"json_schema"` by the constructor. `Schema` is `required`.349350---351352## PDF / Document Input353354`DocumentBlockParam` takes a `DocumentBlockParamSource` union: `Base64PdfSource` / `UrlPdfSource` / `PlainTextSource` / `ContentBlockSource`. `Base64PdfSource` auto-sets `MediaType = "application/pdf"` and `Type = "base64"`.355356```csharp357new MessageParam {358Role = Role.User,359Content = new List<ContentBlockParam> {360new DocumentBlockParam { Source = new Base64PdfSource { Data = base64String } },361new TextBlockParam { Text = "Summarize this PDF" },362},363}364```365366---367368## Server-Side Tools369370Web search, bash, text editor, and code execution are built-in server tools. Type names are version-suffixed; constructors auto-set `name`/`type`. All implicit-convert to `ToolUnion`.371372```csharp373Tools = [374new WebSearchTool20260209(),375new ToolBash20250124(),376new ToolTextEditor20250728(),377new CodeExecutionTool20260120(),378],379```380381Also available: `WebFetchTool20260209`, `MemoryTool20250818`. `WebSearchTool20260209` optionals: `AllowedDomains`, `BlockedDomains`, `MaxUses`, `UserLocation`.382383---384385## Files API (Beta)386387Files live under `client.Beta.Files` (namespace `Anthropic.Models.Beta.Files`). `BinaryContent` implicit-converts from `Stream` and `byte[]`.388389```csharp390using Anthropic.Models.Beta.Files;391using Anthropic.Models.Beta.Messages;392393FileMetadata meta = await client.Beta.Files.Upload(394new FileUploadParams { File = File.OpenRead("doc.pdf") });395396// Referencing the uploaded file requires Beta message types:397new BetaRequestDocumentBlock {398Source = new BetaFileDocumentSource { FileID = meta.ID },399}400```401402The non-beta `DocumentBlockParamSource` union has no file-ID variant — file references need `client.Beta.Messages.Create()`.403