### Vertex AI Client Usage Example Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/advanced-features.md Demonstrates how to instantiate and use the VertexAIClient to get a message response from a Vertex AI Claude model. ```csharp var auth = new VertexAIAuthentication { ProjectId = "my-project", Region = "us-central1" }; var client = new VertexAIClient(auth); var response = await client.Messages.GetClaudeMessageAsync(parameters); ``` -------------------------------- ### Example JSON Output from Tool Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md This is an example of the JSON output that might be returned when a tool is used, containing descriptive fields and color information. ```json { "description": "This image shows a close-up view of a ripe, red apple with shades of yellow and orange. The apple has a shiny, waxy surface with water droplets visible, giving it a fresh appearance.", "estimated_year": 2020, "key_colors": [ { "r": 1, "g": 0.2, "b": 0.2, "name": "red" }, { "r": 1, "g": 0.6, "b": 0.2, "name": "orange" }, { "r": 0.8, "g": 0.8, "b": 0.2, "name": "yellow" } ] } ``` -------------------------------- ### Install Anthropic.SDK via NuGet Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Install the Anthropic.SDK package using the NuGet Package Manager Console. ```bash PM> Install-Package Anthropic.SDK ``` -------------------------------- ### Install Anthropic.SDK Package Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/README.md Use the dotnet CLI to add the Anthropic.SDK package to your project. ```bash dotnet add package Anthropic.SDK ``` -------------------------------- ### Skill Directory Structure Example Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/SkillsEndpoint.md Illustrates the expected file structure for a skill, including the mandatory SKILL.md file at the root. ```plaintext my_skill/ ├── SKILL.md ├── handler.py ├── requirements.txt └── utils.py ``` -------------------------------- ### Complete Batch Workflow Example Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/BatchesEndpoint.md Demonstrates a full workflow for using the Batches Endpoint: creating a batch, polling for its completion status, and then processing the results. ```csharp var client = new AnthropicClient(); // Step 1: Create batch var batchRequests = new List { /* ... */ }; var batch = await client.Batches.CreateBatchAsync(batchRequests); Console.WriteLine($"Created batch: {batch.Id}"); // Step 2: Poll for completion while (true) { var status = await client.Batches.RetrieveBatchStatusAsync(batch.Id); if (status.ProcessingStatus == "ended") break; await Task.Delay(5000); // Wait 5 seconds } // Step 3: Process results await foreach (var result in client.Batches.RetrieveBatchResultsAsync(batch.Id)) { Console.WriteLine($"{result.CustomId}: {result.Result?.Message}"); } ``` -------------------------------- ### APIAuthentication Usage Examples Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/types.md Demonstrates different ways to instantiate and use APIAuthentication, including direct initialization, implicit conversion, and loading from environment variables. ```csharp var auth = new APIAuthentication("sk-ant-..."); // or implicit from string APIAuthentication auth = "sk-ant-..."; // or from environment var auth = APIAuthentication.LoadFromEnv(); ``` -------------------------------- ### ThinkingParameters Usage Example Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/types.md Demonstrates how to instantiate and configure ThinkingParameters for API requests. ```csharp var thinking = new ThinkingParameters { Type = ThinkingType.enabled, BudgetTokens = 5000, Effort = ThinkingEffort.high }; ``` -------------------------------- ### Initialize AnthropicClient Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Create a new instance of the AnthropicClient to start interacting with the Claude AI API. ```csharp var client = new AnthropicClient(); ``` -------------------------------- ### Install MCP Package Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Install the ModelContextProtocol NuGet package using the dotnet CLI. This package is required for client-side MCP integration. ```bash dotnet add package ModelContextProtocol --prerelease ``` -------------------------------- ### Usage examples for Message Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/types.md Demonstrates how to create Message objects for different scenarios, including user text, tool results, and reconstructing from streaming data. ```csharp // User text message var msg = new Message(RoleType.User, "Hello, Claude!"); // Tool result var toolMsg = new Message(functionCall, "{ \"result\": \"value\" }"); // Reconstruct from streaming var fullMessage = new Message(streamingResponses); ``` -------------------------------- ### Connect to MCP Server for Tool Calls Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Demonstrates how to configure and use the MCP connector with the AnthropicClient for server-side tool calls. This example specifies the MCP server URL and name, and sends a user query. ```csharp var client = new AnthropicClient(); var parameters = new MessageParameters() { Model = AnthropicModels.Claude46Sonnet, MaxTokens = 5000, Temperature = 1, MCPServers = new List() { new MCPServer() { Url = "https://mcp.deepwiki.com/sse", Name = "DeepWiki", } } }; var messages = new List { new Message { Role = RoleType.User, Content = new List { new TextContent { Text = "Tell me about the repo tghamm/Anthropic.SDK" } } } }; parameters.Messages = messages; var res = await client.Messages.GetClaudeMessageAsync(parameters); Console.WriteLine("----------------------------------------------"); Console.WriteLine("Final Result:"); Console.WriteLine(res.Content.OfType().Last().Text); ``` -------------------------------- ### Authenticate with gcloud CLI Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Authenticate your environment using the gcloud CLI. This is a one-time setup for CLI authentication. ```bash gcloud auth login ``` ```bash gcloud auth print-access-token ``` -------------------------------- ### Configure MCP Server Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/advanced-features.md Configure an MCP server for connecting Claude to external tools. This example sets up a server of type 'stdio' with command, arguments, and environment variables. ```csharp var mcpServers = new List { new MCPServer { Type = "stdio", Name = "my-tool", Command = "/path/to/tool", Arguments = new[] { "--arg1", "--arg2" }, Env = new Dictionary { { "API_KEY", "secret" } } } }; var parameters = new MessageParameters { Model = "claude-opus-4-7", MaxTokens = 1024, MCPServers = mcpServers, Messages = new List { new Message(RoleType.User, "Use the tool to get information") } }; var response = await client.Messages.GetClaudeMessageAsync(parameters); ``` -------------------------------- ### AnthropicClient Usage Examples Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/AnthropicClient.md Demonstrates various ways to instantiate and use the AnthropicClient, including basic usage, explicit API key configuration, custom HttpClient, and request interceptors. Also shows proper disposal using a `using` statement. ```csharp // Basic usage with environment variable var client = new AnthropicClient(); // With explicit API key var client = new AnthropicClient(new APIAuthentication("sk-ant-...")); // With custom HttpClient var httpClient = new HttpClient(); var client = new AnthropicClient(null, httpClient); // With request interceptor for logging var client = new AnthropicClient(null, null, new LoggingInterceptor()); // Access endpoints var response = await client.Messages.GetClaudeMessageAsync(parameters); var batches = await client.Batches.ListBatchesAsync(); var models = await client.Models.ListModelsAsync(); // Proper disposal using (var client = new AnthropicClient()) { // Use client } // HttpClient automatically disposed ``` -------------------------------- ### Create ChatClient with Semantic Kernel Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Integrate AnthropicClient with Microsoft.SemanticKernel by building a ChatClient. This example shows how to set up the Kernel builder and register the chat client. ```csharp using Microsoft.SemanticKernel; IChatClient CreateChatClient(IServiceProvider _) => new ChatClientBuilder(new AnthropicClient().Messages) .UseFunctionInvocation() .Build(); var sk = Kernel.CreateBuilder(); sk.Plugins.AddFromType("Weather"); sk.Services.AddSingleton(CreateChatClient); ``` -------------------------------- ### CacheControl Usage Example Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/types.md Shows how to apply cache control settings to a SystemMessage, enabling ephemeral caching for one hour. ```csharp var systemMsg = new SystemMessage { Text = "System prompt...", CacheControl = new CacheControl { Type = CacheControlType.ephemeral, TTL = CacheDuration.CacheDuration1Hour } }; ``` -------------------------------- ### Handle Conversations with Tool Use Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/advanced-features.md Extend conversation management to handle tool calls. This example shows how to integrate tool use within a multi-turn conversation loop, including executing tools and processing their results. ```csharp public async Task ChatWithToolsAsync(string userInput) { _messages.Add(new Message(RoleType.User, userInput)); var response = await _client.Messages.GetClaudeMessageAsync( new MessageParameters { Model = "claude-opus-4-7", MaxTokens = 1024, Tools = GetTools(), Messages = _messages }); // Handle tool calls while (response.ToolCalls.Count > 0) { var toolResults = new List(); foreach (var toolCall in response.ToolCalls) { var result = ExecuteTool(toolCall.Name, toolCall.Arguments); toolResults.Add(new Message(toolCall, JsonSerializer.Serialize(result))); } _messages.Add(response.Message); _messages.AddRange(toolResults); // Continue conversation response = await _client.Messages.GetClaudeMessageAsync( new MessageParameters { Model = "claude-opus-4-7", MaxTokens = 1024, Tools = GetTools(), Messages = _messages }); } _messages.Add(response.Message); return response.FirstMessage?.Text ?? ""; } ``` -------------------------------- ### Configure Connection Pooling for HttpClient Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/advanced-features.md Optimize performance by configuring `SocketsHttpHandler` for connection pooling. This example sets `PooledConnectionLifetime` and `PooledConnectionIdleTimeout` for efficient HTTP client usage. ```csharp var handler = new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2), PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1) }; var httpClient = new HttpClient(handler); var client = new AnthropicClient(null, httpClient); ``` -------------------------------- ### Streaming Tool Use with Static Function Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Illustrates how to use a tool with a streaming message call. This example shows the process of receiving streamed deltas and handling tool calls within the stream. ```csharp var client = new AnthropicClient(); var messages = new List(); messages.Add(new Message(RoleType.User, "What's the temperature in San diego right now in Fahrenheit?")); var tools = Common.Tool.GetAllAvailableTools(includeDefaults: false, forceUpdate: true, clearCache: true); var parameters = new MessageParameters() { Messages = messages, MaxTokens = 512, Model = AnthropicModels.Claude46Sonnet, Stream = true, Temperature = 1.0m, Tools = tools.ToList() }; var outputs = new List(); await foreach (var res in client.Messages.StreamClaudeMessageAsync(parameters)) { if (res.Delta != null) { Console.Write(res.Delta.Text); } outputs.Add(res); } messages.Add(new Message(outputs)); foreach (var output in outputs) { if (output.ToolCalls != null) { foreach (var toolCall in output.ToolCalls) { var response = await toolCall.InvokeAsync(); messages.Add(new Message(toolCall, response)); } } } await foreach (var res in client.Messages.StreamClaudeMessageAsync(parameters)) { if (res.Delta != null) { Console.Write(res.Delta.Text); } outputs.Add(res); } ``` -------------------------------- ### List Files with Default and Cursor Pagination Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/configuration.md Demonstrates how to list files using default settings and paginate through results using cursors with the Files endpoint. ```csharp // List with defaults var files = await client.Files.ListFilesAsync(); // Paginate using cursors var files = await client.Files.ListFilesAsync(limit: 50); if (!string.IsNullOrEmpty(files.LastId)) { var nextPage = await client.Files.ListFilesAsync(afterId: files.LastId); } ``` -------------------------------- ### Add Standard Hedging Handler for Idempotent Requests Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Utilize the hedging handler for idempotent GET requests to reduce latency by sending parallel requests. This example configures the total request timeout. ```csharp services.AddHttpClient() .AddStandardHedgingHandler() .Configure(options => { options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(60); }); ``` -------------------------------- ### Get Specific Model Asynchronously Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/ModelsEndpoint.md Retrieves detailed information for a specific Claude model by its ID. Use this to get details like display name, type, and creation date for a particular model. ```csharp public async Task GetModelAsync( string modelId, CancellationToken ctx = default) ``` ```csharp var model = await client.Models.GetModelAsync("claude-opus-4-7"); Console.WriteLine($"ID: {model.Id}"); Console.WriteLine($"Display Name: {model.DisplayName}"); Console.WriteLine($"Type: {model.Type}"); Console.WriteLine($"Created: {model.CreatedAt}"); ``` -------------------------------- ### Define and Use Tool from Object Instance Method Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Illustrates how to define a tool by referencing a method of an object instance. This is useful when the tool's functionality depends on the state of an object. ```csharp public class InstanceObjectTool { public string GetWeather(string location) { return "72 degrees and sunny"; } } var client = new AnthropicClient(); var messages = new List { new Message(RoleType.User, "What is the weather in San Francisco, CA?") } ``` -------------------------------- ### Auth Property Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/AnthropicClient.md Gets or sets the authentication credentials for API requests. ```APIDOC ### Auth ```csharp public APIAuthentication Auth { get; set; } ``` Authentication credentials for API requests. ``` -------------------------------- ### Auth Property Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/AnthropicClient.md Sets or gets the authentication credentials for API requests. ```csharp public APIAuthentication Auth { get; set; } ``` -------------------------------- ### Using MCP Tools Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/advanced-features.md Demonstrates how Claude can automatically invoke configured MCP tools. It also shows how to check the response for MCP tool usage. ```csharp // Claude will invoke MCP tools when appropriate var response = await client.Messages.GetClaudeMessageAsync(parameters); // Check if MCP tools were called if (response.Content.OfType().Any()) { Console.WriteLine("Claude called an MCP tool"); } ``` -------------------------------- ### Work with MCP Prompts and Resources Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Demonstrates how to list and use MCP prompts, and list and read MCP resources using extension methods provided by the MCP SDK. Converts MCP types to Microsoft.Extensions.AI types. ```csharp // List and use prompts var prompts = await mcpClient.ListPromptsAsync(); var promptResult = await prompts.First().GetAsync(); IList messages = promptResult.ToChatMessages(); // List and read resources var resources = await mcpClient.ListResourcesAsync(); var resourceResult = await mcpClient.ReadResourceAsync(resources.First().Uri); IList contents = resourceResult.Contents.ToAIContents(); ``` -------------------------------- ### Initialize Anthropic Client and Prepare Messages Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Initializes the `AnthropicClient` and prepares a list of messages for interaction, including user input with detailed instructions. ```csharp var client = new AnthropicClient(); var messages = new List(); messages.Add(new Message() { Role = RoleType.User, Content = new List() { new TextContent() { Text = """ Find Flights between ATL and NYC using a Google Search. Once you've searched for the flights and have viewed the initial results, switch the toggle to first class and take a screenshot of the results and tell me the price of the flights. """ } } }); ``` -------------------------------- ### Count Message Tokens Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Example of how to use the message token count endpoint. Ensure the AnthropicClient is initialized. ```csharp var client = new AnthropicClient(); var messages = new List(); messages.Add(new Message(RoleType.User, "Write me a sonnet about the Statue of Liberty")); var parameters = new MessageCountTokenParameters { Messages = messages, Model = AnthropicModels.Claude45Haiku }; var response = await client.Messages.CountMessageTokensAsync(parameters); Assert.IsTrue(res.InputTokens > 0); ``` -------------------------------- ### ApiVersion Property Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/AnthropicClient.md Gets or sets the REST API version. The default value is "v1". ```APIDOC ### ApiVersion ```csharp public string ApiVersion { get; set; } ``` REST API version. Default: `"v1"` ``` -------------------------------- ### ApiVersion Property Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/AnthropicClient.md Sets or gets the REST API version. The default value is `"v1"`. ```csharp public string ApiVersion { get; set; } ``` -------------------------------- ### IChatClient with Function Calling Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Demonstrates how to configure and use IChatClient for function invocation. Ensure the necessary AI function factory and model are set up. ```csharp //function calling IChatClient client = new AnthropicClient().Messages .AsBuilder() .UseFunctionInvocation() .Build(); ChatOptions options = new() { ModelId = AnthropicModels.Claude45Haiku, MaxOutputTokens = 512, Tools = [AIFunctionFactory.Create((string personName) => personName switch { "Alice" => "25", _ => "40" }, "GetPersonAge", "Gets the age of the person whose name is specified.")] }; var res = await client.GetResponseAsync("How old is Alice?", options); Assert.IsTrue( res.Message.Text?.Contains("25") is true, res.Message.Text); ``` -------------------------------- ### GetModelAsync Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/ModelsEndpoint.md Retrieve information for a specific model by its ID. This allows you to get details about a particular Claude model. ```APIDOC ## GetModelAsync ### Description Retrieve information for a specific model by its ID. This allows you to get details about a particular Claude model. ### Method GET ### Endpoint /v1/models/{model_id} ### Parameters #### Path Parameters - **model_id** (string) - Required - The model ID (e.g., "claude-opus-4-7"). ### Response #### Success Response (200) - **id** (string) - The unique identifier for the model. - **object** (string) - The type of object, usually "model". - **created_at** (string) - The timestamp when the model was created. - **owned_by** (string) - The organization that owns the model. - **permission** (array) - Permissions associated with the model. - **id** (string) - The unique identifier for the model. - **type** (string) - The type of the model (e.g., "completion"). - **name** (string) - The display name of the model. - **description** (string) - A description of the model. ### Response Example ```json { "id": "claude-opus-2024-05-03", "object": "model", "created_at": "2024-05-03T00:00:00.000Z", "owned_by": "anthropic", "permission": [], "name": "Claude Opus", "description": "Latest flagship model" } ``` ``` -------------------------------- ### Basic Skills API Usage in C# Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Demonstrates how to initialize the AnthropicClient and create a container with the built-in PowerPoint skill for a message request. Ensure the 'code_execution' tool is included for skill functionality. ```csharp var client = new AnthropicClient(); // Create a container with skills var container = new Container { Skills = new List { new Skill { Type = "anthropic", SkillId = "pptx", // Built-in PowerPoint skill Version = "latest" } } }; var parameters = new MessageParameters { Model = AnthropicModels.Claude4Sonnet, MaxTokens = 4096, Messages = new List { new Message(RoleType.User, "Create a presentation about renewable energy") }, Container = container, Tools = new List { new Function("code_execution", "code_execution_20250825", new Dictionary { { "name", "code_execution" } }) } }; var response = await client.Messages.GetClaudeMessageAsync(parameters); // The response will include the container ID for reuse var containerId = response.Container?.Id; ``` -------------------------------- ### List and Get Models Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Interact with the Models API to list all available models and retrieve details for a specific model. ```csharp var client = new AnthropicClient(); var res = await client.Models.ListModelsAsync(); Assert.IsNotNull(res.Models); var modelId = res.Models.First().Id; var model = await client.Models.GetModelAsync(modelId); Assert.IsNotNull(model); ``` -------------------------------- ### Get File Metadata Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/FilesEndpoint.md Retrieves metadata for a specific file using its ID. Ensure the fileId is not null or empty. ```csharp public async Task GetFileMetadataAsync( string fileId, CancellationToken cancellationToken = default) ``` ```csharp var metadata = await client.Files.GetFileMetadataAsync("file-abc123"); Console.WriteLine($"Filename: {metadata.Filename}"); Console.WriteLine($"Size: {metadata.Size} bytes"); Console.WriteLine($"Created: {metadata.CreatedAt}"); ``` -------------------------------- ### General Usage Pattern for Files Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/FilesEndpoint.md Demonstrates a typical workflow: initializing the client, uploading a file, using its ID in a message, and cleaning up by deleting the file. This pattern is useful for integrating file uploads into conversational AI workflows. ```csharp var client = new AnthropicClient(); // Upload file var metadata = await client.Files.UploadFileAsync("report.pdf"); Console.WriteLine($"Uploaded: {metadata.Id}"); // Use in message var response = await client.Messages.GetClaudeMessageAsync(new MessageParameters { Model = "claude-opus-4-7", MaxTokens = 1024, Messages = new List { new Message(RoleType.User, new DocumentContent { Type = ContentType.document, Source = new DocumentSource { Type = "file", FileId = metadata.Id } }) } }); // Later: cleanup await client.Files.DeleteFileAsync(metadata.Id); ``` -------------------------------- ### Define and Use Tool from Func Delegate Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Shows how to define a tool using a Func delegate, which is a concise way to represent inline functions. This is useful for simple, self-contained operations. ```csharp var client = new AnthropicClient(); var messages = new List { new Message(RoleType.User, "What is the weather in San Francisco, CA?") }; var tools = new List { Common.Tool.FromFunc("Get_Weather", ([FunctionParameter("Location of the weather", true)]string location)=> "72 degrees and sunny") }; var parameters = new MessageParameters() { Messages = messages, MaxTokens = 2048, Model = AnthropicModels.Claude46Sonnet, Stream = false, Temperature = 1.0m, Tools = tools }; var res = await client.Messages.GetClaudeMessageAsync(parameters); messages.Add(res.Message); foreach (var toolCall in res.ToolCalls) { var response = toolCall.Invoke(); messages.Add(new Message(toolCall, response)); } var finalResult = await client.Messages.GetClaudeMessageAsync(parameters); ``` -------------------------------- ### Models API Capabilities Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/APIReference.md The Models API supports listing models, getting model details, and retrieving version information. ```APIDOC ## Models API ### Description Provides capabilities for interacting with models. ### Capabilities - List: ✓ - Get Details: ✓ - Version Info: ✓ ``` -------------------------------- ### Initialize Vertex AI Client Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/configuration.md Initializes the VertexAIClient using provided project ID and region for authentication. ```csharp var auth = new VertexAIAuthentication(projectId: "my-project", region: "us-central1"); var client = new VertexAIClient(auth); // Use same API as AnthropicClient var response = await client.Messages.GetClaudeMessageAsync(parameters); ``` -------------------------------- ### AnthropicVersion Property Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/AnthropicClient.md Gets or sets the Anthropic API version header value. The default value is "2023-06-01". ```APIDOC ### AnthropicVersion ```csharp public string AnthropicVersion { get; set; } ``` Anthropic API version header value. Default: `"2023-06-01"` ``` -------------------------------- ### AnthropicVersion Property Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/AnthropicClient.md Sets or gets the Anthropic API version header value. The default value is `"2023-06-01"`. ```csharp public string AnthropicVersion { get; set; } ``` -------------------------------- ### Create Skill from Directory Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/SkillsEndpoint.md Use this method to create a new custom skill by uploading files from a local directory. Ensure the directory contains a SKILL.md file. ```csharp public async Task CreateSkillAsync( string displayTitle, string skillDirectoryPath, CancellationToken cancellationToken = default) { // Implementation details... } ``` ```csharp var skillResponse = await client.Skills.CreateSkillAsync( "My Custom Skill", "/path/to/skill/directory"); Console.WriteLine($ ``` -------------------------------- ### ToolChoice Class and Enum Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/types.md Controls how Claude utilizes tools, with options for automatic, any, or specific tool selection. Includes a usage example. ```csharp public class ToolChoice { public ToolChoiceType Type { get; set; } public string Name { get; set; } public bool? DisableParallelToolUse { get; set; } } public enum ToolChoiceType { auto, any, tool } ``` ```csharp var toolChoice = new ToolChoice { Type = ToolChoiceType.tool, Name = "get_weather", DisableParallelToolUse = false }; ``` -------------------------------- ### Create Skill Version from Directory Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/SkillsEndpoint.md Use this method to create a new version of an existing skill. Provide the skill ID and the path to the directory containing the updated skill files. ```csharp public async Task CreateSkillVersionAsync( string skillId, string skillDirectoryPath, CancellationToken cancellationToken = default) { // Implementation details... } ``` ```csharp var versionResponse = await client.Skills.CreateSkillVersionAsync( "skill-abc123", "/path/to/updated/skill"); Console.WriteLine($ ``` -------------------------------- ### Get Skill Version Details Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/SkillsEndpoint.md Retrieves detailed information for a specific skill version using its skill ID and version identifier. ```csharp public async Task GetSkillVersionAsync( string skillId, string version, CancellationToken cancellationToken = default) ``` ```csharp var version = await client.Skills.GetSkillVersionAsync("skill-abc123", "1759178010641129"); Console.WriteLine($"Version: {version.Id}"); Console.WriteLine($"Created: {version.CreatedAt}"); ``` -------------------------------- ### GetFileMetadataAsync Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/FilesEndpoint.md Retrieves the metadata for a specific file using its unique ID. This allows you to get details such as the filename, size, and creation date. ```APIDOC ## GetFileMetadataAsync ### Description Retrieves metadata for a specific file using its ID. ### Method GET (Implied by SDK method) ### Endpoint /v1/files/{file_id} ### Parameters #### Path Parameters - **fileId** (string) - Required - The ID of the file. ### Request Example ```csharp var metadata = await client.Files.GetFileMetadataAsync("file-abc123"); Console.WriteLine($"Filename: {metadata.Filename}"); Console.WriteLine($"Size: {metadata.Size} bytes"); Console.WriteLine($"Created: {metadata.CreatedAt}"); ``` ### Response #### Success Response (200) `FileMetadata` with file information. #### Response Example ```json { "id": "file-abc123", "filename": "document.pdf", "size": 102400, "createdAt": 1678886400, "purpose": "assistants" } ``` ``` -------------------------------- ### Configuring Multiple Built-in Skills Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Illustrates how to add multiple built-in skills (pptx, xlsx, docx, pdf) to a container. A maximum of 8 skills can be included per request. ```csharp var container = new Container { Skills = new List { new Skill { Type = "anthropic", SkillId = "pptx", Version = "latest" }, new Skill { Type = "anthropic", SkillId = "xlsx", Version = "latest" }, new Skill { Type = "anthropic", SkillId = "docx", Version = "latest" }, new Skill { Type = "anthropic", SkillId = "pdf", Version = "latest" } } }; ``` -------------------------------- ### AnthropicBetaVersion Property Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/AnthropicClient.md Gets or sets the beta API features enabled. The default value includes several features like prompt-caching and message-batches. ```APIDOC ### AnthropicBetaVersion ```csharp public string AnthropicBetaVersion { get; set; } ``` Beta API features enabled. Default includes: prompt-caching, message-batches, computer-use, pdfs, output-128k, mcp-client, code-execution, files-api. ``` -------------------------------- ### General Usage Pattern for Models Endpoint Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/ModelsEndpoint.md Demonstrates a common workflow for interacting with the Models Endpoint. This includes initializing the client, listing all models, and then retrieving a specific model to use in subsequent message requests. ```csharp var client = new AnthropicClient(); // List all models var allModels = await client.Models.ListModelsAsync(); Console.WriteLine($"Available models: {allModels.Data.Count}"); // Get specific model var model = await client.Models.GetModelAsync("claude-opus-4-7"); if (model != null) { // Use model in messages var response = await client.Messages.GetClaudeMessageAsync(new MessageParameters { Model = model.Id, MaxTokens = 1024, Messages = new List { new Message(RoleType.User, "Hello!") } }); } ``` -------------------------------- ### Using a Custom HttpClient with AnthropicClient Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/configuration.md Illustrates how to provide a custom `HttpClient` instance to the `AnthropicClient` and the importance of manually disposing the custom `HttpClient`. ```csharp var httpClient = new HttpClient(); var client = new AnthropicClient(null, httpClient); try { // Use client } finally { // You must dispose custom HttpClient httpClient?.Dispose(); } ``` -------------------------------- ### Manage Skills and Versions Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/SkillsEndpoint.md Demonstrates common skill management operations: creating a skill, creating a new version, listing custom skills, and deleting a skill. ```csharp var client = new AnthropicClient(); // Create skill var skill = await client.Skills.CreateSkillAsync( "My Assistant Tool", "/path/to/skill"); Console.WriteLine($"Created: {skill.Id}"); // Update skill with new version var updated = await client.Skills.CreateSkillVersionAsync( skill.Id, "/path/to/updated/skill"); Console.WriteLine($"Updated to version: {updated.Id}"); // List all custom skills var skills = await client.Skills.ListSkillsAsync(source: "custom"); // Clean up await client.Skills.DeleteSkillAsync(skill.Id); ``` -------------------------------- ### Define and Use Tool from Static Class Method Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Demonstrates defining a tool by referencing a method within a static class. This approach is suitable for organizing utility functions into static classes. ```csharp public static class StaticObjectTool { public static string GetWeather(string location) { return "72 degrees and sunny"; } } var client = new AnthropicClient(); var messages = new List { new Message(RoleType.User, "What is the weather in San Francisco, CA?") }; var tools = new List { Common.Tool.GetOrCreateTool(typeof(StaticObjectTool), nameof(GetWeather), "This function returns the weather for a given location") }; var parameters = new MessageParameters() { Messages = messages, MaxTokens = 2048, Model = AnthropicModels.Claude46Sonnet, Stream = false, Temperature = 1.0m, Tools = tools }; var res = await client.Messages.GetClaudeMessageAsync(parameters); messages.Add(res.Message); foreach (var toolCall in res.ToolCalls) { var response = toolCall.Invoke(); messages.Add(new Message(toolCall, response)); } var finalResult = await client.Messages.GetClaudeMessageAsync(parameters); ``` -------------------------------- ### Get Claude Message (Non-Streaming) Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/MessagesEndpoint.md Use this method for a single, non-streaming response from the Claude messages API. Ensure the 'Stream' parameter is set to false. ```csharp public async Task GetClaudeMessageAsync( MessageParameters parameters, CancellationToken ctx = default) ``` ```csharp var client = new AnthropicClient(); var parameters = new MessageParameters { Model = "claude-opus-4-7", MaxTokens = 1024, Messages = new List { new Message(RoleType.User, "Hello, what is 2+2?") } }; var response = await client.Messages.GetClaudeMessageAsync(parameters); Console.WriteLine(response.FirstMessage?.Text); // "2 + 2 = 4" Console.WriteLine($"Usage: {response.Usage.InputTokens} input, {response.Usage.OutputTokens} output"); ``` -------------------------------- ### List Models with Cursor Pagination Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/configuration.md Shows how to list available models and paginate through the results using cursor-based pagination. ```csharp var models = await client.Models.ListModelsAsync(limit: 50); // Cursor-based pagination if (!string.IsNullOrEmpty(models.LastId)) { var nextPage = await client.Models.ListModelsAsync(afterId: models.LastId); } ``` -------------------------------- ### ApiUrlFormat Property Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/AnthropicClient.md Gets or sets the base URL template for API requests. The default value is "https://api.anthropic.com/{0}/{1}". ```APIDOC ### ApiUrlFormat ```csharp public string ApiUrlFormat { get; set; } ``` Base URL template for API requests. Default: `"https://api.anthropic.com/{0}/{1}"` ``` -------------------------------- ### Define and Use Tools with Anthropic Client Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Demonstrates how to define custom tools and use them with the Anthropic client for message generation. This is useful when you need the model to interact with external functions. ```csharp var client = new AnthropicClient(); var messages = new List { new Message(RoleType.User, "What is the weather in San Francisco, CA in fahrenheit?") }; var inputschema = new InputSchema() { Type = "object", Properties = new Dictionary() { { "location", new Property() { Type = "string", Description = "The location of the weather" } }, { "tempType", new Property() { Type = "string", Enum = Enum.GetNames(typeof(TempType)), Description = "The unit of temperature, celsius or fahrenheit" } } }, Required = new List() { "location", "tempType" } }; JsonSerializerOptions jsonSerializationOptions = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, Converters = { new JsonStringEnumConverter() }, ReferenceHandler = ReferenceHandler.IgnoreCycles, }; string jsonString = JsonSerializer.Serialize(inputschema, jsonSerializationOptions); var tools = new List() { new Function("GetWeather", "This function returns the weather for a given location", JsonNode.Parse(jsonString)) }; var parameters = new MessageParameters() { Messages = messages, MaxTokens = 2048, Model = AnthropicModels.Claude46Sonnet, Stream = false, Temperature = 1.0m, Tools = tools }; var res = await client.Messages.GetClaudeMessageAsync(parameters); messages.Add(res.Message); var toolUse = res.Content.OfType().First(); var id = toolUse.Id; var param1 = toolUse.Input["location"].ToString(); var param2 = Enum.Parse(toolUse.Input["tempType"].ToString()); var weather = await GetWeather(param1, param2); messages.Add(new Message() { Role = RoleType.User, Content = new List() { new ToolResultContent() { ToolUseId = id, Content = new List() { new TextContent() { Text = weather } } } }}); var finalResult = await client.Messages.GetClaudeMessageAsync(parameters); ``` -------------------------------- ### ApiUrlFormat Property Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/AnthropicClient.md Sets or gets the base URL template for API requests. The default value is `"https://api.anthropic.com/{0}/{1}"`. ```csharp public string ApiUrlFormat { get; set; } ``` -------------------------------- ### List Skills with Pagination and Source Filtering Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/configuration.md Demonstrates listing skills with pagination using a 'page' parameter and filtering by 'source' (e.g., 'custom', 'anthropic'). ```csharp var skills = await client.Skills.ListSkillsAsync(limit: 50); if (!string.IsNullOrEmpty(skills.NextPage)) { var nextPage = await client.Skills.ListSkillsAsync(page: skills.NextPage); } // Filter by source var custom = await client.Skills.ListSkillsAsync(source: "custom"); var anthropic = await client.Skills.ListSkillsAsync(source: "anthropic"); ``` -------------------------------- ### Add Tracing to Requests Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/advanced-features.md Implement `TracingInterceptor` to add distributed tracing information to outgoing requests. It starts an activity and sets relevant HTTP tags. ```csharp public class TracingInterceptor : IRequestInterceptor { private readonly ActivitySource _activitySource; public async Task OnBeforeRequestAsync(HttpRequestMessage request) { using var activity = _activitySource.StartActivity("api_request"); activity?.SetTag("http.method", request.Method); activity?.SetTag("http.url", request.RequestUri); } public async Task OnAfterResponseAsync(HttpResponseMessage response) { // Log tracing data } } ``` -------------------------------- ### Create Skill Version from Zip File Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/SkillsEndpoint.md Use this method to create a new version of an existing skill by providing a path to a zip file containing the skill's updated files. Ensure the skill ID and zip file path are correct. ```csharp public async Task CreateSkillVersionFromZipAsync( string skillId, string zipFilePath, CancellationToken cancellationToken = default) { // ... implementation details ... } ``` ```csharp var versionResponse = await client.Skills.CreateSkillVersionFromZipAsync( "skill-abc123", "/path/to/updated-skill.zip"); ``` -------------------------------- ### Get Skill Details Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/SkillsEndpoint.md Use this method to retrieve detailed information for a specific skill using its ID. Ensure the skill ID is valid to avoid exceptions. ```csharp public async Task GetSkillAsync( string skillId, CancellationToken cancellationToken = default) { // ... implementation details ... } ``` ```csharp var skill = await client.Skills.GetSkillAsync("skill-abc123"); Console.WriteLine($"Name: {skill.Name}"); Console.WriteLine($"Current Version: {skill.VersionId}"); ``` -------------------------------- ### File Upload and Usage in Messages Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/APIReference.md This pattern demonstrates how to upload a file using the SDK, reference it within a message (e.g., for vision or document analysis), and then clean up by deleting the uploaded file. Ensure the file is uploaded before being referenced in a message. ```csharp // Upload file var metadata = await client.Files.UploadFileAsync("document.pdf"); // Use in message var response = await client.Messages.GetClaudeMessageAsync( new MessageParameters { Model = "claude-opus-4-7", MaxTokens = 1024, Messages = new List { new Message(RoleType.User, new DocumentContent { Source = new DocumentSource { Type = "file", FileId = metadata.Id } }) } }); // Cleanup await client.Files.DeleteFileAsync(metadata.Id); ``` -------------------------------- ### Skills API Capabilities Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/APIReference.md The Skills API supports creating, listing, getting details, updating (with versioning), deleting, zip uploading, and stream uploading skills. ```APIDOC ## Skills API ### Description Provides capabilities for managing skills. ### Capabilities - Create: ✓ - List: ✓ - Get Details: ✓ - Update (Versioning): ✓ - Delete: ✓ - Zip Upload: ✓ - Stream Upload: ✓ ``` -------------------------------- ### Download Skill Output Files Source: https://github.com/tghamm/anthropic.sdk/blob/main/README.md Use the `DownloadFilesAsync` extension method to download all file outputs from a skill execution to a specified directory. Alternatively, retrieve file IDs for manual download. ```csharp using Anthropic.SDK.Extensions; var response = await client.Messages.GetClaudeMessageAsync(parameters); // Download all file outputs to a specified directory var downloadedFiles = await response.DownloadFilesAsync( client, @"C:\Output\SkillFiles" ); foreach (var filePath in downloadedFiles) { Console.WriteLine($"Downloaded: {filePath}"); } // Or just get the file IDs if you want to handle downloads manually var fileIds = response.GetFileIds(); foreach (var fileId in fileIds) { var metadata = await client.Files.GetFileMetadataAsync(fileId); Console.WriteLine($"File: {metadata.Filename} ({metadata.SizeBytes} bytes)"); } ``` -------------------------------- ### GetClaudeMessageAsync Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/api-reference/MessagesEndpoint.md Performs a non-streaming call to the Claude messages API to get a single message response. It requires MessageParameters where the 'stream' property must be set to false. ```APIDOC ## GetClaudeMessageAsync ### Description Non-streaming call to the Claude messages API. This method retrieves a single message response from the model. ### Method `POST` (inferred from C# method signature and typical SDK patterns) ### Endpoint `/v1/messages` (inferred from typical API structure) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **parameters** (MessageParameters) - Required - Request parameters including model, messages, tools, max tokens, etc. Stream must be false. - **ctx** (CancellationToken) - Optional - Optional cancellation token. ### Request Example ```csharp var client = new AnthropicClient(); var parameters = new MessageParameters { Model = "claude-opus-4-7", MaxTokens = 1024, Messages = new List { new Message(RoleType.User, "Hello, what is 2+2?") } }; var response = await client.Messages.GetClaudeMessageAsync(parameters); Console.WriteLine(response.FirstMessage?.Text); // "2 + 2 = 4" Console.WriteLine($"Usage: {response.Usage.InputTokens} input, {response.Usage.OutputTokens} output"); ``` ### Response #### Success Response (200) - **MessageResponse** - Contains the model's response, usage information, and content (text, tool calls, thinking, etc.). #### Response Example (Response structure depends on MessageResponse content, e.g., text, tool calls) ### Error Handling - `ArgumentException` if stream is set to true - `HttpRequestException` on API errors ``` -------------------------------- ### Explicit Service Account Authentication for Vertex AI Source: https://github.com/tghamm/anthropic.sdk/blob/main/_autodocs/advanced-features.md Shows how to configure Vertex AI authentication using explicit service account credentials loaded from a file. ```csharp var auth = new VertexAIAuthentication { ProjectId = "my-project", Region = "us-central1", Credentials = File.ReadAllText("service-account.json") }; ```