Anthropic.SDK 3.0.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package Anthropic.SDK --version 3.0.1
NuGet\Install-Package Anthropic.SDK -Version 3.0.1
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Anthropic.SDK" Version="3.0.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Anthropic.SDK --version 3.0.1
#r "nuget: Anthropic.SDK, 3.0.1"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Anthropic.SDK as a Cake Addin
#addin nuget:?package=Anthropic.SDK&version=3.0.1

// Install Anthropic.SDK as a Cake Tool
#tool nuget:?package=Anthropic.SDK&version=3.0.1

Anthropic.SDK

.NET Nuget

Anthropic.SDK is an unofficial C# client designed for interacting with the Claude AI API. This powerful interface simplifies the integration of the Claude AI into your C# applications. It targets NetStandard 2.0, .NET 6.0, and .NET 8.0.

Table of Contents

Installation

Install Anthropic.SDK via the NuGet package manager:

PM> Install-Package Anthropic.SDK

API Keys

You can load the API Key from an environment variable named ANTHROPIC_API_KEY by default. Alternatively, you can supply it as a string to the AnthropicClient constructor.

HttpClient

The AnthropicClient can optionally take a custom HttpClient, which allows you to control elements such as retries and timeouts.

Usage

To start using the Claude AI API, simply create an instance of the AnthropicClient class.

Examples

Non-Streaming Call

Here's an example of a non-streaming call to the Claude AI API to the new Claude 3 Sonnet model:

var client = new AnthropicClient();
var messages = new List<Message>();
messages.Add(new Message()
{
    Role = RoleType.User,
    Content = "Write me a sonnet about the Statue of Liberty"
});
var parameters = new MessageParameters()
{
    Messages = messages,
    MaxTokens = 512,
    Model = AnthropicModels.Claude3Sonnet,
    Stream = false,
    Temperature = 1.0m,
};
var res = await client.Messages.GetClaudeMessageAsync(parameters);

Streaming Call

The following is an example of a streaming call to the Claude AI API Model 3 Opus that provides an image for analysis:

string resourceName = "Anthropic.SDK.Tests.Red_Apple.jpg";

// Get the current assembly
Assembly assembly = Assembly.GetExecutingAssembly();

// Get a stream to the embedded resource
await using Stream stream = assembly.GetManifestResourceStream(resourceName);
// Read the stream into a byte array
byte[] imageBytes;
using (var memoryStream = new MemoryStream())
{
    await stream.CopyToAsync(memoryStream);
    imageBytes = memoryStream.ToArray();
}

// Convert the byte array to a base64 string
string base64String = Convert.ToBase64String(imageBytes);

var client = new AnthropicClient();
var messages = new List<Message>();
messages.Add(new Message()
{
    Role = RoleType.User,
    Content = new dynamic[]
    {
        new ImageContent()
        {
            Source = new ImageSource()
            {
                MediaType = "image/jpeg",
                Data = base64String
            }
        },
        new TextContent()
        {
            Text = "What is this a picture of?"
        }
    }
});
var parameters = new MessageParameters()
{
    Messages = messages,
    MaxTokens = 512,
    Model = AnthropicModels.Claude3Opus,
    Stream = true,
    Temperature = 1.0m,
};
var outputs = new List<MessageResponse>();
await foreach (var res in client.Messages.StreamClaudeMessageAsync(parameters))
{
    if (res.Delta != null)
    {
        Console.Write(res.Delta.Text);
    }

    outputs.Add(res);
}
Console.WriteLine(string.Empty);
Console.WriteLine($@"Used Tokens - Input:{outputs.First().StreamStartMessage.Usage.InputTokens}.
                            Output: {outputs.Last().Usage.OutputTokens}");

Tools

The AnthropicClient supports function-calling through a variety of methods, see some examples below or check out the unit tests in this repo (note function-calling is currently only supported in non-streaming calls by Claude at the moment):

//Global tool discovery method
public enum TempType
{
    Fahrenheit,
    Celsius
}

[Function("This function returns the weather for a given location")]
public static async Task<string> GetWeather([FunctionParameter("Location of the weather", true)]string location,
    [FunctionParameter("Unit of temperature, celsius or fahrenheit", true)] TempType tempType)
{
    return "72 degrees and sunny";
}

var client = new AnthropicClient();
var messages = new List<Message>
{
    new Message()
    {
        Role = RoleType.User,
        Content = "What is the weather in San Francisco, CA in fahrenheit?"
    }
};
var tools = Common.Tool.GetAllAvailableTools(includeDefaults: false, 
    forceUpdate: true, clearCache: true);

var parameters = new MessageParameters()
{
    Messages = messages,
    MaxTokens = 2048,
    Model = AnthropicModels.Claude3Sonnet,
    Stream = false,
    Temperature = 1.0m,
};
var res = await client.Messages.GetClaudeMessageAsync(parameters, tools.ToList());

messages.Add(res.Content.AsAssistantMessage());

foreach (var toolCall in res.ToolCalls)
{
    var response = await toolCall.InvokeAsync<string>();
    
    messages.Add(new Message(toolCall, response));
}

var finalResult = await client.Messages.GetClaudeMessageAsync(parameters);

//The weather in San Francisco, CA is currently 72 degrees Fahrenheit and sunny.


//From a Func:
var client = new AnthropicClient();
var messages = new List<Message>
{
    new Message()
    {
        Role = RoleType.User,
        Content = "What is the weather in San Francisco, CA?"
    }
};
var tools = new List<Common.Tool>
{
    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.Claude3Sonnet,
    Stream = false,
    Temperature = 1.0m,
};
var res = await client.Messages.GetClaudeMessageAsync(parameters, tools.ToList());

messages.Add(res.Content.AsAssistantMessage());

foreach (var toolCall in res.ToolCalls)
{
    var response = toolCall.Invoke<string>();

    messages.Add(new Message(toolCall, response));
}

var finalResult = await client.Messages.GetClaudeMessageAsync(parameters);


//From a static Object
public static class StaticObjectTool
{
    
    public static string GetWeather(string location)
    {
        return "72 degrees and sunny";
    }
}

var client = new AnthropicClient();
var messages = new List<Message>
{
    new Message()
    {
        Role = RoleType.User,
        Content = "What is the weather in San Francisco, CA?"
    }
};

var tools = new List<Common.Tool>
{
    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.Claude3Sonnet,
    Stream = false,
    Temperature = 1.0m,
};
var res = await client.Messages.GetClaudeMessageAsync(parameters, tools.ToList());

messages.Add(res.Content.AsAssistantMessage());

foreach (var toolCall in res.ToolCalls)
{
    var response = toolCall.Invoke<string>();

    messages.Add(new Message(toolCall, response));
}

var finalResult = await client.Messages.GetClaudeMessageAsync(parameters);

//From an object instance
public class InstanceObjectTool
{

    public string GetWeather(string location)
    {
        return "72 degrees and sunny";
    }
}
var client = new AnthropicClient();
var messages = new List<Message>
{
    new Message()
    {
        Role = RoleType.User,
        Content = "What is the weather in San Francisco, CA?"
    }
};

var objectInstance = new InstanceObjectTool();
var tools = new List<Common.Tool>
{
    Common.Tool.GetOrCreateTool(objectInstance, nameof(GetWeather), "This function returns the weather for a given location")
};
....

//From Scratch

var client = new AnthropicClient();
var messages = new List<Message>
{
    new Message()
    {
        Role = RoleType.User,
        Content = "What is the weather in San Francisco, CA in fahrenheit?"
    }
};

var parameters = new MessageParameters()
{
    Messages = messages,
    MaxTokens = 2048,
    Model = AnthropicModels.Claude3Sonnet,
    Stream = false,
    Temperature = 1.0m,
    Tools = new List<Tool>()
    {
        new Tool()
        {
            Name = "GetWeather", Description = "This function returns the weather for a given location",
            InputSchema = new InputSchema()
            {
                Type = "object",
                Properties = new Dictionary<string, Property>()
                {
                    {"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<string>() {"location", "tempType"}
            }
        }
    }
};
var res = await client.Messages.GetClaudeMessageAsync(parameters);

messages.Add(res.Content.AsAssistantMessage());

var toolUse = res.Content.FirstOrDefault(c => c.Type == ContentType.tool_use) as ToolUseContent;
var id = toolUse.Id;
var input = toolUse.Input;
var param1 = input["location"].ToString();
var param2 = Enum.Parse<TempType>(input["tempType"].ToString());

var weather = await GetWeather(param1, param2);

messages.Add(new Message()
{
    Role = RoleType.User,
    Content = new[] { new ToolResultContent()
    {
        ToolUseId = id,
        Content = weather
    }
}});

var finalResult = await client.Messages.GetClaudeMessageAsync(parameters);


Contributing

Pull requests are welcome. If you're planning to make a major change, please open an issue first to discuss your proposed changes.

License

This project is licensed under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on Anthropic.SDK:

Package Downloads
LangChain.Providers.Anthropic

Anthropic API LLM and Chat model provider.

BotSharp.Plugin.AnthropicAI

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
3.2.1 2,085 4/25/2024
3.2.0 2,625 4/24/2024
3.1.0 495 4/17/2024
3.0.1 474 4/12/2024
3.0.0 161 4/11/2024
2.0.1 4,456 3/17/2024
2.0.0 1,130 3/5/2024
1.3.0 1,879 11/21/2023
1.2.0 6,362 8/19/2023
1.1.2 1,668 8/9/2023
1.1.1 1,060 7/24/2023
1.1.0 986 7/16/2023
1.0.0 1,167 7/1/2023

Bug fix for HttpClient disposal