Anthropic provides a feature called Citations that allows Claude to provide citations for information extracted from documents. This feature enables Claude to reference specific parts of the source material when answering questions, making it easier to verify information and understand the context of responses.
+
Citations can be enabled for documents and will return references to the specific locations in the source material where information was found. This library provides comprehensive support for citations through strongly-typed models that represent different types of citation locations.
+
Enabling Citations for Documents
+
You can enable citations for documents by setting the Citations property on DocumentContent instances:
+
using AnthropicClient;
+using AnthropicClient.Models;
+
+var request = new MessageRequest(
+ model: AnthropicModels.Claude35Sonnet,
+ messages: [
+ new(MessageRole.User, [
+ new DocumentContent(new TextSource("The grass is green. The sky is blue."))
+ {
+ Title = "My Document",
+ Context = "This is a trustworthy document.",
+ Citations = new() { Enabled = true }
+ },
+ new TextContent("What color is the grass and sky?")
+ ])
+ ]
+);
+
+var response = await client.CreateMessageAsync(request);
+
+if (response.IsSuccess is false)
+{
+ Console.WriteLine("Failed to create message");
+ Console.WriteLine("Error Type: {0}", response.Error.Error.Type);
+ Console.WriteLine("Error Message: {0}", response.Error.Error.Message);
+ return;
+}
+
+foreach (var content in response.Value.Content)
+{
+ switch (content)
+ {
+ case TextContent textContent:
+ Console.WriteLine("Response: {0}", textContent.Text);
+
+ if (textContent.Citations is not null)
+ {
+ Console.WriteLine("Citations:");
+ foreach (var citation in textContent.Citations)
+ {
+ Console.WriteLine(" - Cited Text: {0}", citation.CitedText);
+ Console.WriteLine(" Document: {0}", citation.DocumentTitle);
+ Console.WriteLine(" Type: {0}", citation.Type);
+
+ switch (citation)
+ {
+ case CharacterLocationCitation charCitation:
+ Console.WriteLine(
+ " Character Range: {0}-{1}",
+ charCitation.StartCharIndex, charCitation.EndCharIndex
+ );
+ break;
+ case PageLocationCitation pageCitation:
+ Console.WriteLine(
+ " Page Range: {0}-{1}",
+ pageCitation.StartPageNumber, pageCitation.EndPageNumber
+ );
+ break;
+ case ContentBlockLocationCitation blockCitation:
+ Console.WriteLine(
+ " Block Range: {0}-{1}",
+ blockCitation.StartBlockIndex, blockCitation.EndBlockIndex
+ );
+ break;
+ }
+ }
+ }
+ break;
+ }
+}
+
+
Citations with PDF Documents
+
Citations work particularly well with PDF documents, providing page-level references:
+
using AnthropicClient;
+using AnthropicClient.Models;
+
+var pdfBytes = await File.ReadAllBytesAsync("document.pdf");
+var base64Data = Convert.ToBase64String(pdfBytes);
+
+var request = new MessageRequest(
+ model: AnthropicModels.Claude35Sonnet,
+ messages: [
+ new(MessageRole.User, [
+ new DocumentContent("application/pdf", base64Data)
+ {
+ Title = "Research Paper",
+ Citations = new() { Enabled = true }
+ },
+ new TextContent("Summarize the key findings from this research paper.")
+ ])
+ ]
+);
+
+var response = await client.CreateMessageAsync(request);
+
+if (response.IsSuccess is false)
+{
+ Console.WriteLine("Failed to create message");
+ Console.WriteLine("Error Type: {0}", response.Error.Error.Type);
+ Console.WriteLine("Error Message: {0}", response.Error.Error.Message);
+ return;
+}
+
+foreach (var content in response.Value.Content)
+{
+ switch (content)
+ {
+ case TextContent textContent:
+ Console.WriteLine("Summary: {0}", textContent.Text);
+
+ if (textContent.Citations is not null)
+ {
+ Console.WriteLine("\nCitations:");
+ foreach (var citation in textContent.Citations.OfType<PageLocationCitation>())
+ {
+ Console.WriteLine(
+ " - \"{0}\" (Pages {1}-{2})",
+ citation.CitedText,
+ citation.StartPageNumber,
+ citation.EndPageNumber
+ );
+ }
+ }
+ break;
+ }
+}
+
+
Citations in Streaming Responses
+
Citations are also supported in streaming responses through the CitationDelta events:
+
using AnthropicClient;
+using AnthropicClient.Models;
+
+var request = new StreamMessageRequest(
+ model: AnthropicModels.Claude35Sonnet,
+ messages: [
+ new(MessageRole.User, [
+ new DocumentContent(new TextSource("The grass is green. The sky is blue."))
+ {
+ Citations = new() { Enabled = true }
+ },
+ new TextContent("What color is the grass?")
+ ])
+ ]
+);
+
+var events = client.CreateMessageAsync(request);
+
+await foreach (var e in events)
+{
+ switch (e.Data)
+ {
+ case ContentDeltaEventData contentData:
+ switch (contentData.Delta)
+ {
+ case CitationDelta citationDelta:
+ Console.WriteLine("Citation: {0}", citationDelta.Citation.CitedText);
+ Console.WriteLine("Type: {0}", citationDelta.Citation.Type);
+ break;
+ case TextDelta textDelta:
+ Console.Write(textDelta.Text);
+ break;
+ }
+ break;
+ }
+}
+
Message Batches
Anthropic provides a feature called Message Batches that allows you to send multiple messages in a single request. This feature is covered in depth in Anthropic's API Documentation.
Create a message batch
diff --git a/docs/index.json b/docs/index.json
index 7c06a8c..c4c06cf 100644
--- a/docs/index.json
+++ b/docs/index.json
@@ -59,6 +59,11 @@
"title": "Class AutoToolChoice | AnthropicClient",
"summary": "Class AutoToolChoice Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents the auto tool choice mode. public class AutoToolChoice : ToolChoice Inheritance object ToolChoice AutoToolChoice Inherited Members ToolChoice.Type object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors AutoToolChoice() Initializes a new instance of the AutoToolChoice class. public AutoToolChoice()"
},
+ "api/AnthropicClient.Models.Base64Source.html": {
+ "href": "api/AnthropicClient.Models.Base64Source.html",
+ "title": "Class Base64Source | AnthropicClient",
+ "summary": "Class Base64Source Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a base64 source. public class Base64Source : Source Inheritance object Source Base64Source Derived DocumentSource ImageSource Inherited Members Source.Type object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors Base64Source(string, string) Initializes a new instance of the Base64Source class. public Base64Source(string mediaType, string data) Parameters mediaType string The media type of the source. data string The data of the source. Exceptions ArgumentException Thrown when the media type is invalid. ArgumentNullException Thrown when the media type or data is null. Properties Data Gets the data of the source. public string Data { get; init; } Property Value string MediaType Gets the media type of the source. [JsonPropertyName(\"media_type\")] public string MediaType { get; init; } Property Value string"
+ },
"api/AnthropicClient.Models.BaseMessageRequest.html": {
"href": "api/AnthropicClient.Models.BaseMessageRequest.html",
"title": "Class BaseMessageRequest | AnthropicClient",
@@ -79,15 +84,45 @@
"title": "Class CanceledMessageBatchResult | AnthropicClient",
"summary": "Class CanceledMessageBatchResult Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a message batch result that was cancelled. public class CanceledMessageBatchResult : MessageBatchResult Inheritance object MessageBatchResult CanceledMessageBatchResult Inherited Members MessageBatchResult.Type object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors CanceledMessageBatchResult() Initializes a new instance of the CanceledMessageBatchResult class. public CanceledMessageBatchResult()"
},
+ "api/AnthropicClient.Models.CharacterLocationCitation.html": {
+ "href": "api/AnthropicClient.Models.CharacterLocationCitation.html",
+ "title": "Class CharacterLocationCitation | AnthropicClient",
+ "summary": "Class CharacterLocationCitation Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a citation for specific locations within text content. public class CharacterLocationCitation : Citation Inheritance object Citation CharacterLocationCitation Inherited Members Citation.Type Citation.CitedText Citation.DocumentIndex Citation.DocumentTitle object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors CharacterLocationCitation() Initializes a new instance of the CharacterLocationCitation class. public CharacterLocationCitation() Properties EndCharIndex Gets the end character index of the citation. [JsonPropertyName(\"end_char_index\")] public int EndCharIndex { get; init; } Property Value int StartCharIndex Gets the start character index of the citation. [JsonPropertyName(\"start_char_index\")] public int StartCharIndex { get; init; } Property Value int"
+ },
+ "api/AnthropicClient.Models.Citation.html": {
+ "href": "api/AnthropicClient.Models.Citation.html",
+ "title": "Class Citation | AnthropicClient",
+ "summary": "Class Citation Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a citation public abstract class Citation Inheritance object Citation Derived CharacterLocationCitation ContentBlockLocationCitation PageLocationCitation Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors Citation(string) Initializes a new instance of the Citation class with a specified type. protected Citation(string type) Parameters type string The type of the citation. Properties CitedText Gets the text that is cited. [JsonPropertyName(\"cited_text\")] public string CitedText { get; init; } Property Value string DocumentIndex Gets the document index of the citation. [JsonPropertyName(\"document_index\")] public int DocumentIndex { get; init; } Property Value int DocumentTitle Gets the title of the document from which the citation is made. [JsonPropertyName(\"document_title\")] public string DocumentTitle { get; init; } Property Value string Type Gets the type of the citation. public string Type { get; init; } Property Value string"
+ },
+ "api/AnthropicClient.Models.CitationDelta.html": {
+ "href": "api/AnthropicClient.Models.CitationDelta.html",
+ "title": "Class CitationDelta | AnthropicClient",
+ "summary": "Class CitationDelta Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a citation delta. public class CitationDelta : ContentDelta Inheritance object ContentDelta CitationDelta Inherited Members ContentDelta.Type object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors CitationDelta(Citation) Initializes a new instance of the CitationDelta class. public CitationDelta(Citation citation) Parameters citation Citation The citation to associate with this delta. Exceptions ArgumentNullException Thrown when citation is null. Properties Citation Gets the citation associated with this delta. public Citation Citation { get; init; } Property Value Citation"
+ },
+ "api/AnthropicClient.Models.CitationOption.html": {
+ "href": "api/AnthropicClient.Models.CitationOption.html",
+ "title": "Class CitationOption | AnthropicClient",
+ "summary": "Class CitationOption Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents whether citations are enabled for a document. public class CitationOption Inheritance object CitationOption Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Properties Enabled Gets a value indicating whether citations are enabled for the document. public bool Enabled { get; init; } Property Value bool"
+ },
+ "api/AnthropicClient.Models.CitationType.html": {
+ "href": "api/AnthropicClient.Models.CitationType.html",
+ "title": "Class CitationType | AnthropicClient",
+ "summary": "Class CitationType Namespace AnthropicClient.Models Assembly AnthropicClient.dll The types of citations that can be returned by the Anthropic API. public static class CitationType Inheritance object CitationType Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Fields CharacterLocation A citation that refers to a specific character in the text. public const string CharacterLocation = \"char_location\" Field Value string ContentBlockLocation A citation that refers to a specific section in the text. public const string ContentBlockLocation = \"content_block_location\" Field Value string PageLocation A citation that refers to a specific page in the text. public const string PageLocation = \"page_location\" Field Value string"
+ },
"api/AnthropicClient.Models.Content.html": {
"href": "api/AnthropicClient.Models.Content.html",
"title": "Class Content | AnthropicClient",
"summary": "Class Content Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents part of the content of a message. public abstract class Content Inheritance object Content Derived DocumentContent ImageContent TextContent ToolResultContent ToolUseContent Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors Content(string) Initializes a new instance of the Content class. protected Content(string type) Parameters type string The type of the content. Content(string, CacheControl) Initializes a new instance of the Content class. protected Content(string type, CacheControl cacheControl) Parameters type string The type of the content. cacheControl CacheControl The cache control to be used for the content. Properties CacheControl Gets the cache control to be used for the content. [JsonPropertyName(\"cache_control\")] public CacheControl? CacheControl { get; set; } Property Value CacheControl Type Gets the type of the content. public string Type { get; init; } Property Value string"
},
+ "api/AnthropicClient.Models.ContentBlockLocationCitation.html": {
+ "href": "api/AnthropicClient.Models.ContentBlockLocationCitation.html",
+ "title": "Class ContentBlockLocationCitation | AnthropicClient",
+ "summary": "Class ContentBlockLocationCitation Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a citation for content blocks within custom content. public class ContentBlockLocationCitation : Citation Inheritance object Citation ContentBlockLocationCitation Inherited Members Citation.Type Citation.CitedText Citation.DocumentIndex Citation.DocumentTitle object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors ContentBlockLocationCitation() Initializes a new instance of the ContentBlockLocationCitation class. public ContentBlockLocationCitation() Properties EndBlockIndex Gets the end block index of the citation. [JsonPropertyName(\"end_block_index\")] public int EndBlockIndex { get; init; } Property Value int StartBlockIndex Gets the start block index of the citation. [JsonPropertyName(\"start_block_index\")] public int StartBlockIndex { get; init; } Property Value int"
+ },
"api/AnthropicClient.Models.ContentDelta.html": {
"href": "api/AnthropicClient.Models.ContentDelta.html",
"title": "Class ContentDelta | AnthropicClient",
- "summary": "Class ContentDelta Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a content delta. public abstract class ContentDelta Inheritance object ContentDelta Derived JsonDelta TextDelta Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors ContentDelta(string) Initializes a new instance of the ContentDelta class. protected ContentDelta(string type) Parameters type string The type of the content delta. Properties Type Gets the type of the content delta. public string Type { get; init; } Property Value string"
+ "summary": "Class ContentDelta Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a content delta. public abstract class ContentDelta Inheritance object ContentDelta Derived CitationDelta JsonDelta TextDelta Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors ContentDelta(string) Initializes a new instance of the ContentDelta class. protected ContentDelta(string type) Parameters type string The type of the content delta. Properties Type Gets the type of the content delta. public string Type { get; init; } Property Value string"
},
"api/AnthropicClient.Models.ContentDeltaEventData.html": {
"href": "api/AnthropicClient.Models.ContentDeltaEventData.html",
@@ -97,7 +132,7 @@
"api/AnthropicClient.Models.ContentDeltaType.html": {
"href": "api/AnthropicClient.Models.ContentDeltaType.html",
"title": "Class ContentDeltaType | AnthropicClient",
- "summary": "Class ContentDeltaType Namespace AnthropicClient.Models Assembly AnthropicClient.dll Provides constants for content delta types. public static class ContentDeltaType Inheritance object ContentDeltaType Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Fields JsonDelta The input_json_delta. public const string JsonDelta = \"input_json_delta\" Field Value string TextDelta The text_delta. public const string TextDelta = \"text_delta\" Field Value string"
+ "summary": "Class ContentDeltaType Namespace AnthropicClient.Models Assembly AnthropicClient.dll Provides constants for content delta types. public static class ContentDeltaType Inheritance object ContentDeltaType Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Fields CitationDelta The citation_delta. public const string CitationDelta = \"citations_delta\" Field Value string JsonDelta The input_json_delta. public const string JsonDelta = \"input_json_delta\" Field Value string TextDelta The text_delta. public const string TextDelta = \"text_delta\" Field Value string"
},
"api/AnthropicClient.Models.ContentStartEventData.html": {
"href": "api/AnthropicClient.Models.ContentStartEventData.html",
@@ -119,15 +154,20 @@
"title": "Class CountMessageTokensRequest | AnthropicClient",
"summary": "Class CountMessageTokensRequest Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a request to count the number of tokens in a message. public class CountMessageTokensRequest Inheritance object CountMessageTokensRequest Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors CountMessageTokensRequest(string, List, ToolChoice?, List?, List?) Initializes a new instance of the CountMessageTokensRequest class. public CountMessageTokensRequest(string model, List messages, ToolChoice? toolChoice = null, List? tools = null, List? systemPrompt = null) Parameters model string The model ID to use for the request. messages List The messages to count the number of tokens in. toolChoice ToolChoice The tool choice mode to use for the request. tools List The tools to use for the request. systemPrompt List The system prompt to use for the request. Exceptions ArgumentNullException Thrown when model or messages is null. ArgumentException Thrown when messages is empty. Properties Messages Gets the messages to count the number of tokens in. public List Messages { get; init; } Property Value List Model Gets the model ID to be used for the request. public string Model { get; init; } Property Value string SystemPrompt Gets the system prompt to use for the request. [JsonPropertyName(\"system\")] public List? SystemPrompt { get; init; } Property Value List ToolChoice Gets the tool choice mode to use for the request. [JsonPropertyName(\"tool_choice\")] public ToolChoice? ToolChoice { get; init; } Property Value ToolChoice Tools Gets the tools to use for the request. public List? Tools { get; init; } Property Value List"
},
+ "api/AnthropicClient.Models.CustomSource.html": {
+ "href": "api/AnthropicClient.Models.CustomSource.html",
+ "title": "Class CustomSource | AnthropicClient",
+ "summary": "Class CustomSource Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a custom source that contains a list of text content. public class CustomSource : Source Inheritance object Source CustomSource Inherited Members Source.Type object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors CustomSource(List) Initializes a new instance of the CustomSource class. public CustomSource(List content) Parameters content List Exceptions ArgumentNullException Thrown when the content is null. Properties Content Gets the list of text content that makes up the custom source. public List Content { get; init; } Property Value List"
+ },
"api/AnthropicClient.Models.DocumentContent.html": {
"href": "api/AnthropicClient.Models.DocumentContent.html",
"title": "Class DocumentContent | AnthropicClient",
- "summary": "Class DocumentContent Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents content from a document that is part of a message. public class DocumentContent : Content Inheritance object Content DocumentContent Inherited Members Content.Type Content.CacheControl object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors DocumentContent(string, string) Initializes a new instance of the DocumentContent class. public DocumentContent(string mediaType, string data) Parameters mediaType string The media type of the document. data string The data of the document. Exceptions ArgumentNullException Thrown when the media type or data is null. DocumentContent(string, string, CacheControl) Initializes a new instance of the DocumentContent class. public DocumentContent(string mediaType, string data, CacheControl cacheControl) Parameters mediaType string The media type of the document. data string The data of the document. cacheControl CacheControl The cache control to be used for the content. Exceptions ArgumentNullException Thrown when the media type, data, or cache control is null. Properties Source Gets the source of the document. public DocumentSource Source { get; init; } Property Value DocumentSource"
+ "summary": "Class DocumentContent Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents content from a document that is part of a message. public class DocumentContent : Content Inheritance object Content DocumentContent Inherited Members Content.Type Content.CacheControl object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors DocumentContent(Source) Initializes a new instance of the DocumentContent class with a document source. public DocumentContent(Source source) Parameters source Source The document source. Exceptions ArgumentNullException Thrown when the source is null. DocumentContent(Source, CacheControl) Initializes a new instance of the DocumentContent class with a document source and cache control. public DocumentContent(Source source, CacheControl cacheControl) Parameters source Source The document source. cacheControl CacheControl The cache control to be used for the content. Exceptions ArgumentNullException Thrown when the source is null. DocumentContent(string, string) Initializes a new instance of the DocumentContent class. public DocumentContent(string mediaType, string data) Parameters mediaType string The media type of the document. data string The data of the document. Exceptions ArgumentNullException Thrown when the media type or data is null. DocumentContent(string, string, CacheControl) Initializes a new instance of the DocumentContent class. public DocumentContent(string mediaType, string data, CacheControl cacheControl) Parameters mediaType string The media type of the document. data string The data of the document. cacheControl CacheControl The cache control to be used for the content. Exceptions ArgumentNullException Thrown when the media type, data, or cache control is null. Properties Citations Gets whether citations are enabled for the document. public CitationOption? Citations { get; init; } Property Value CitationOption Context Gets the context of the document. public string? Context { get; init; } Property Value string Source Gets the source of the document. public Source Source { get; init; } Property Value Source Title Gets the title of the document. public string? Title { get; init; } Property Value string"
},
"api/AnthropicClient.Models.DocumentSource.html": {
"href": "api/AnthropicClient.Models.DocumentSource.html",
"title": "Class DocumentSource | AnthropicClient",
- "summary": "Class DocumentSource Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a document source. public class DocumentSource Inheritance object DocumentSource Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors DocumentSource(string, string) Initializes a new instance of the DocumentSource class. public DocumentSource(string mediaType, string data) Parameters mediaType string The media type of the document. data string The data of the document. Exceptions ArgumentException Thrown when the media type is invalid. ArgumentNullException Thrown when the media type or data is null. Properties Data Gets the data of the document. public string Data { get; init; } Property Value string MediaType Gets the media type of the document. [JsonPropertyName(\"media_type\")] public string MediaType { get; init; } Property Value string Type Gets the type of encoding of the document data. public string Type { get; init; } Property Value string"
+ "summary": "Class DocumentSource Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a document source. public class DocumentSource : Base64Source Inheritance object Source Base64Source DocumentSource Inherited Members Base64Source.MediaType Base64Source.Data Source.Type object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors DocumentSource(string, string) Initializes a new instance of the DocumentSource class. public DocumentSource(string mediaType, string data) Parameters mediaType string The media type of the document. data string The data of the document. Exceptions ArgumentException Thrown when the media type is invalid. ArgumentNullException Thrown when the media type or data is null."
},
"api/AnthropicClient.Models.EphemeralCacheControl.html": {
"href": "api/AnthropicClient.Models.EphemeralCacheControl.html",
@@ -187,12 +227,12 @@
"api/AnthropicClient.Models.ImageContent.html": {
"href": "api/AnthropicClient.Models.ImageContent.html",
"title": "Class ImageContent | AnthropicClient",
- "summary": "Class ImageContent Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents image content that is part of a message. public class ImageContent : Content Inheritance object Content ImageContent Inherited Members Content.Type Content.CacheControl object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors ImageContent(string, string) Initializes a new instance of the ImageContent class. public ImageContent(string mediaType, string data) Parameters mediaType string The media type of the image. data string The data of the image. Exceptions ArgumentNullException Thrown when the media type or data is null. ImageContent(string, string, CacheControl) Initializes a new instance of the ImageContent class. public ImageContent(string mediaType, string data, CacheControl cacheControl) Parameters mediaType string The media type of the image. data string The data of the image. cacheControl CacheControl The cache control to be used for the content. Exceptions ArgumentNullException Thrown when the media type, data, or cache control is null. Properties Source Gets the source of the image. public ImageSource Source { get; init; } Property Value ImageSource"
+ "summary": "Class ImageContent Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents image content that is part of a message. public class ImageContent : Content Inheritance object Content ImageContent Inherited Members Content.Type Content.CacheControl object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors ImageContent(string, string) Initializes a new instance of the ImageContent class. public ImageContent(string mediaType, string data) Parameters mediaType string The media type of the image. data string The data of the image. Exceptions ArgumentNullException Thrown when the media type or data is null. ImageContent(string, string, CacheControl) Initializes a new instance of the ImageContent class. public ImageContent(string mediaType, string data, CacheControl cacheControl) Parameters mediaType string The media type of the image. data string The data of the image. cacheControl CacheControl The cache control to be used for the content. Exceptions ArgumentNullException Thrown when the media type, data, or cache control is null. Properties Source Gets the source of the image. public Source Source { get; init; } Property Value Source"
},
"api/AnthropicClient.Models.ImageSource.html": {
"href": "api/AnthropicClient.Models.ImageSource.html",
"title": "Class ImageSource | AnthropicClient",
- "summary": "Class ImageSource Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents an image source. public class ImageSource Inheritance object ImageSource Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors ImageSource(string, string) Initializes a new instance of the ImageSource class. public ImageSource(string mediaType, string data) Parameters mediaType string The media type of the image. data string The data of the image. Exceptions ArgumentException Thrown when the media type is invalid. ArgumentNullException Thrown when the media type or data is null. Properties Data Gets the data of the image. public string Data { get; init; } Property Value string MediaType Gets the media type of the image. [JsonPropertyName(\"media_type\")] public string MediaType { get; init; } Property Value string Type Gets the type of encoding of the image data. public string Type { get; init; } Property Value string"
+ "summary": "Class ImageSource Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents an image source. public class ImageSource : Base64Source Inheritance object Source Base64Source ImageSource Inherited Members Base64Source.MediaType Base64Source.Data Source.Type object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors ImageSource(string, string) Initializes a new instance of the ImageSource class. public ImageSource(string mediaType, string data) Parameters mediaType string The media type of the image. data string The data of the image. Exceptions ArgumentException Thrown when the media type is invalid. ArgumentNullException Thrown when the media type or data is null."
},
"api/AnthropicClient.Models.ImageType.html": {
"href": "api/AnthropicClient.Models.ImageType.html",
@@ -329,6 +369,11 @@
"title": "Class Page | AnthropicClient",
"summary": "Class Page Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a page. public class Page Inheritance object Page Derived Page Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Properties FirstId The id of the first item in the page. [JsonPropertyName(\"first_id\")] public string? FirstId { get; init; } Property Value string HasMore Indicates whether there is more data to be retrieved. [JsonPropertyName(\"has_more\")] public bool HasMore { get; init; } Property Value bool LastId The id of the last item in the page. [JsonPropertyName(\"last_id\")] public string? LastId { get; init; } Property Value string"
},
+ "api/AnthropicClient.Models.PageLocationCitation.html": {
+ "href": "api/AnthropicClient.Models.PageLocationCitation.html",
+ "title": "Class PageLocationCitation | AnthropicClient",
+ "summary": "Class PageLocationCitation Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a citation for text within a page of a document. public class PageLocationCitation : Citation Inheritance object Citation PageLocationCitation Inherited Members Citation.Type Citation.CitedText Citation.DocumentIndex Citation.DocumentTitle object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors PageLocationCitation() Initializes a new instance of the PageLocationCitation class. public PageLocationCitation() Properties EndPageNumber Gets the end page number of the citation. [JsonPropertyName(\"end_page_number\")] public int EndPageNumber { get; init; } Property Value int StartPageNumber Gets the start page number of the citation. [JsonPropertyName(\"start_page_number\")] public int StartPageNumber { get; init; } Property Value int"
+ },
"api/AnthropicClient.Models.PagingRequest.html": {
"href": "api/AnthropicClient.Models.PagingRequest.html",
"title": "Class PagingRequest | AnthropicClient",
@@ -349,6 +394,16 @@
"title": "Class RateLimitError | AnthropicClient",
"summary": "Class RateLimitError Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a rate_limit error. public class RateLimitError : Error Inheritance object Error RateLimitError Inherited Members Error.Type Error.Message object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors RateLimitError(string) Initializes a new instance of the RateLimitError class. public RateLimitError(string message) Parameters message string The message of the error."
},
+ "api/AnthropicClient.Models.Source.html": {
+ "href": "api/AnthropicClient.Models.Source.html",
+ "title": "Class Source | AnthropicClient",
+ "summary": "Class Source Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a base class for sources. public abstract class Source Inheritance object Source Derived Base64Source CustomSource TextSource Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors Source(string) Initializes a new instance of the Source class. protected Source(string type) Parameters type string The type of the source. Properties Type Gets the type of the source. public string Type { get; init; } Property Value string"
+ },
+ "api/AnthropicClient.Models.SourceType.html": {
+ "href": "api/AnthropicClient.Models.SourceType.html",
+ "title": "Class SourceType | AnthropicClient",
+ "summary": "Class SourceType Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents the types of document sources that can be used in the Anthropic API. public static class SourceType Inheritance object SourceType Inherited Members object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Fields Base64 The base64 encoded document source type. public const string Base64 = \"base64\" Field Value string Content The custom content document source type. public const string Content = \"content\" Field Value string Text The text document source type. public const string Text = \"text\" Field Value string"
+ },
"api/AnthropicClient.Models.SpecificToolChoice.html": {
"href": "api/AnthropicClient.Models.SpecificToolChoice.html",
"title": "Class SpecificToolChoice | AnthropicClient",
@@ -372,13 +427,18 @@
"api/AnthropicClient.Models.TextContent.html": {
"href": "api/AnthropicClient.Models.TextContent.html",
"title": "Class TextContent | AnthropicClient",
- "summary": "Class TextContent Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents text content that is part of a message. public class TextContent : Content Inheritance object Content TextContent Inherited Members Content.Type Content.CacheControl object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors TextContent(string) Initializes a new instance of the TextContent class. public TextContent(string text) Parameters text string The text of the content. Exceptions ArgumentNullException Thrown when the text is null. TextContent(string, CacheControl) Initializes a new instance of the TextContent class. public TextContent(string text, CacheControl cacheControl) Parameters text string The text of the content. cacheControl CacheControl The cache control to be used for the content. Exceptions ArgumentNullException Thrown when the text or cache control is null. Properties Text Gets the text of the content. public string Text { get; init; } Property Value string"
+ "summary": "Class TextContent Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents text content that is part of a message. public class TextContent : Content Inheritance object Content TextContent Inherited Members Content.Type Content.CacheControl object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors TextContent(string) Initializes a new instance of the TextContent class. public TextContent(string text) Parameters text string The text of the content. Exceptions ArgumentNullException Thrown when the text is null. TextContent(string, CacheControl) Initializes a new instance of the TextContent class. public TextContent(string text, CacheControl cacheControl) Parameters text string The text of the content. cacheControl CacheControl The cache control to be used for the content. Exceptions ArgumentNullException Thrown when the text or cache control is null. Properties Citations Gets the citations associated with the text content. public Citation[]? Citations { get; init; } Property Value Citation[] Text Gets the text of the content. public string Text { get; init; } Property Value string"
},
"api/AnthropicClient.Models.TextDelta.html": {
"href": "api/AnthropicClient.Models.TextDelta.html",
"title": "Class TextDelta | AnthropicClient",
"summary": "Class TextDelta Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a text delta. public class TextDelta : ContentDelta Inheritance object ContentDelta TextDelta Inherited Members ContentDelta.Type object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors TextDelta(string) Initializes a new instance of the TextDelta class. public TextDelta(string text) Parameters text string The text. Properties Text Gets the text. public string Text { get; set; } Property Value string"
},
+ "api/AnthropicClient.Models.TextSource.html": {
+ "href": "api/AnthropicClient.Models.TextSource.html",
+ "title": "Class TextSource | AnthropicClient",
+ "summary": "Class TextSource Namespace AnthropicClient.Models Assembly AnthropicClient.dll Represents a text document source. public class TextSource : Source Inheritance object Source TextSource Inherited Members Source.Type object.Equals(object) object.Equals(object, object) object.GetHashCode() object.GetType() object.MemberwiseClone() object.ReferenceEquals(object, object) object.ToString() Constructors TextSource(string) Initializes a new instance of the TextSource class. public TextSource(string data) Parameters data string The data of the document. Exceptions ArgumentNullException Thrown when the data is null. Properties Data Gets the data of the source. public string Data { get; init; } Property Value string MediaType Gets the media type of the source. [JsonPropertyName(\"media_type\")] public string MediaType { get; } Property Value string"
+ },
"api/AnthropicClient.Models.TokenCountResponse.html": {
"href": "api/AnthropicClient.Models.TokenCountResponse.html",
"title": "Class TokenCountResponse | AnthropicClient",
@@ -427,7 +487,7 @@
"api/AnthropicClient.Models.html": {
"href": "api/AnthropicClient.Models.html",
"title": "Namespace AnthropicClient.Models | AnthropicClient",
- "summary": "Namespace AnthropicClient.Models Classes AnthropicError Represents an error response from the Anthropic API. AnthropicEvent Represents an event from the Anthropic API. AnthropicFunction Represents a function that can be provided as a tool. AnthropicHeaders Represents headers included in Anthropic API responses. AnthropicModel Represents an Anthropic model. AnthropicModels Provides constants for the Anthropic models. AnyToolChoice Represents the any tool choice mode. ApiError Represents an api_error response from the Anthropic API. AuthenticationError Represents an authentication_error response from the Anthropic API. AutoToolChoice Represents the auto tool choice mode. BaseMessageRequest Represents a message request. CacheControl Represents the cache control to be used for content. CacheControlType Provides constants for cache control types. CanceledMessageBatchResult Represents a message batch result that was cancelled. Content Represents part of the content of a message. ContentDelta Represents a content delta. ContentDeltaEventData Represents data for a content_block_delta event. ContentDeltaType Provides constants for content delta types. ContentStartEventData Represents data for a content_block_start event. ContentStopEventData Represents data for a content_block_stop event. ContentType Represents the content type. CountMessageTokensRequest Represents a request to count the number of tokens in a message. DocumentContent Represents content from a document that is part of a message. DocumentSource Represents a document source. EphemeralCacheControl Represents the cache control to be used for content. Error Represents an error. ErrorEventData Represents data for an error event. ErrorType Represents the error type. ErroredMessageBatchResult Represents a message batch result that contains an error response. EventData Represents data for an event. EventType Provides constants for event types. ExpiredMessageBatchResult Represents a message batch result that has expired. FunctionParameterAttribute Attribute to describe a function parameter. FunctionPropertyAttribute Attribute to describe a property of a type that is used as a function parameter. ImageContent Represents image content that is part of a message. ImageSource Represents an image source. ImageType Represents the image type. InputProperty Represents an input property. InputSchema Represents an input schema. InvalidRequestError Represents an invalid_request error. JsonDelta Represents a JSON delta. Message Represents a message. MessageBatchDeleteResponse Represents a message batch delete response. MessageBatchRequest Represents a request to create a batch of messages. MessageBatchRequestCounts Represents the counts of requests in a batch of messages. MessageBatchRequestItem Represents an item in a batch of messages. MessageBatchResponse Represents a response to a batch of messages. MessageBatchResult Represents a message batch result. MessageBatchResultItem Represents a message batch result item. MessageBatchResultType Represents the types of message batch results. MessageBatchStatus Represents the status of a message batch. MessageCompleteEventData Represents data for the message_complete event. MessageDelta Represents a message delta. MessageDeltaEventData Represents data for a message_delta event. MessageRequest Represents a message request. MessageResponse Represents a response. MessageRole Represents the message role. MessageStartEventData Represents data for a message_start event. MessageStopEventData Represents data for a message_stop event. NotFoundError Represents a not_found error. OverloadedError Represents an overloaded error. Page Represents a page. Page Represents a page with data. PagingRequest Represents a request to page through a collection of items. PermissionError Represents a permission error. PingEventData Represents data for a ping event. RateLimitError Represents a rate_limit error. SpecificToolChoice Represents the specific tool choice mode. StopReasonType Represents the stop reason type. StreamMessageRequest Represents a message request. SucceededMessageBatchResult Represents a message batch result that contains a message response. TextContent Represents text content that is part of a message. TextDelta Represents a text delta. TokenCountResponse Represents a response to a token count request. Tool Represents a tool that can be used. ToolCall Represents a tool call. ToolCallResult Represents a tool call result. ToolChoice Represents a tool choice mode. ToolChoiceType Represents the tool choice type. ToolResultContent Represents tool result content that is part of a message. ToolUseContent Represents tool use content that is part of a message. Usage Represents the usage of a response. Interfaces ITool Interface that a class can implement to be used to create a tool."
+ "summary": "Namespace AnthropicClient.Models Classes AnthropicError Represents an error response from the Anthropic API. AnthropicEvent Represents an event from the Anthropic API. AnthropicFunction Represents a function that can be provided as a tool. AnthropicHeaders Represents headers included in Anthropic API responses. AnthropicModel Represents an Anthropic model. AnthropicModels Provides constants for the Anthropic models. AnyToolChoice Represents the any tool choice mode. ApiError Represents an api_error response from the Anthropic API. AuthenticationError Represents an authentication_error response from the Anthropic API. AutoToolChoice Represents the auto tool choice mode. Base64Source Represents a base64 source. BaseMessageRequest Represents a message request. CacheControl Represents the cache control to be used for content. CacheControlType Provides constants for cache control types. CanceledMessageBatchResult Represents a message batch result that was cancelled. CharacterLocationCitation Represents a citation for specific locations within text content. Citation Represents a citation CitationDelta Represents a citation delta. CitationOption Represents whether citations are enabled for a document. CitationType The types of citations that can be returned by the Anthropic API. Content Represents part of the content of a message. ContentBlockLocationCitation Represents a citation for content blocks within custom content. ContentDelta Represents a content delta. ContentDeltaEventData Represents data for a content_block_delta event. ContentDeltaType Provides constants for content delta types. ContentStartEventData Represents data for a content_block_start event. ContentStopEventData Represents data for a content_block_stop event. ContentType Represents the content type. CountMessageTokensRequest Represents a request to count the number of tokens in a message. CustomSource Represents a custom source that contains a list of text content. DocumentContent Represents content from a document that is part of a message. DocumentSource Represents a document source. EphemeralCacheControl Represents the cache control to be used for content. Error Represents an error. ErrorEventData Represents data for an error event. ErrorType Represents the error type. ErroredMessageBatchResult Represents a message batch result that contains an error response. EventData Represents data for an event. EventType Provides constants for event types. ExpiredMessageBatchResult Represents a message batch result that has expired. FunctionParameterAttribute Attribute to describe a function parameter. FunctionPropertyAttribute Attribute to describe a property of a type that is used as a function parameter. ImageContent Represents image content that is part of a message. ImageSource Represents an image source. ImageType Represents the image type. InputProperty Represents an input property. InputSchema Represents an input schema. InvalidRequestError Represents an invalid_request error. JsonDelta Represents a JSON delta. Message Represents a message. MessageBatchDeleteResponse Represents a message batch delete response. MessageBatchRequest Represents a request to create a batch of messages. MessageBatchRequestCounts Represents the counts of requests in a batch of messages. MessageBatchRequestItem Represents an item in a batch of messages. MessageBatchResponse Represents a response to a batch of messages. MessageBatchResult Represents a message batch result. MessageBatchResultItem Represents a message batch result item. MessageBatchResultType Represents the types of message batch results. MessageBatchStatus Represents the status of a message batch. MessageCompleteEventData Represents data for the message_complete event. MessageDelta Represents a message delta. MessageDeltaEventData Represents data for a message_delta event. MessageRequest Represents a message request. MessageResponse Represents a response. MessageRole Represents the message role. MessageStartEventData Represents data for a message_start event. MessageStopEventData Represents data for a message_stop event. NotFoundError Represents a not_found error. OverloadedError Represents an overloaded error. Page Represents a page. PageLocationCitation Represents a citation for text within a page of a document. Page Represents a page with data. PagingRequest Represents a request to page through a collection of items. PermissionError Represents a permission error. PingEventData Represents data for a ping event. RateLimitError Represents a rate_limit error. Source Represents a base class for sources. SourceType Represents the types of document sources that can be used in the Anthropic API. SpecificToolChoice Represents the specific tool choice mode. StopReasonType Represents the stop reason type. StreamMessageRequest Represents a message request. SucceededMessageBatchResult Represents a message batch result that contains a message response. TextContent Represents text content that is part of a message. TextDelta Represents a text delta. TextSource Represents a text document source. TokenCountResponse Represents a response to a token count request. Tool Represents a tool that can be used. ToolCall Represents a tool call. ToolCallResult Represents a tool call result. ToolChoice Represents a tool choice mode. ToolChoiceType Represents the tool choice type. ToolResultContent Represents tool result content that is part of a message. ToolUseContent Represents tool use content that is part of a message. Usage Represents the usage of a response. Interfaces ITool Interface that a class can implement to be used to create a tool."
},
"api/AnthropicClient.html": {
"href": "api/AnthropicClient.html",
@@ -437,6 +497,6 @@
"index.html": {
"href": "index.html",
"title": "AnthropicClient | AnthropicClient",
- "summary": "AnthropicClient This library for the Anthropic API is meant to simplify development in C# for Anthropic users. Note This is an unofficial SDK for the Anthropic API. It was not built in consultation with Anthropic or any member of their organization. This SDK was developed independently using existing libraries and the Anthropic API documentation as the starting point with the intention of making development of integrations done in C# with Anthropic quicker and more convenient. Note This client library is heavily inspired by the Anthropic.SDK library. I chose to create a new library because I wanted to handle streaming and tool calling differently as well as have control over the client library as I plan to use it to build a connector for SemanticKernel. However if you are looking for a client library the Anthropic.SDK is a great place to start. \uD83D\uDCDD Issues If you encounter any issues while using this library please open an issue here. \uD83D\uDCDC License This library is licensed under the MIT License and is free to use and modify. \uD83D\uDCDD Contributing If you would like to contribute to this library please open a pull request here. \uD83D\uDEE0️ Dependencies Microsoft.Bcl.AsyncInterfaces Used to support async interfaces when streaming messages System.Text.Json Used for JSON serialization and deserialization \uD83D\uDCBE Installation Install the package from NuGet using the following command: dotnet add package AnthropicClient \uD83D\uDD11 API Key In order to use the Anthropic API you will need an API key. You can get one by signing up at Anthropic. Please keep your API key secure and do not share it with others. Be mindful of where you store your API key and do not commit it to a public repository. \uD83D\uDC68\uD83C\uDFFB\uD83D\uDCBB Start Coding AnthropicApiClient The most common way to use the SDK is to create an AnthropicApiClient instance and call its methods. Its constructor requires two parameters: apiKey - your Anthropic API key httpClient - an HttpClient instance. You can configure and customize the HttpClient instance as needed. This library however will perform the necessary configuration to work with the Anthropic API. Such as setting the base address and adding the proper headers. Note This library does not manage the lifecycle of the HttpClient instance. You should create and manage the lifecycle of the HttpClient instance in your application. It is best practice to read the API key from a secure location such as a configuration file or environment variable. For example using the appsettings.json file: { \"AnthropicApiKey\": \"YOUR_API\" } Example constructing an AnthropicApiClient instance: using AnthropicClient; using Microsoft.Extensions.Configuration; var configuration = new ConfigurationBuilder() .AddJsonFile(\"appsettings.json\") .Build(); var apiKey = configuration[\"AnthropicApiKey\"]; var client = new AnthropicApiClient(apiKey, new HttpClient()); IAnthropicApiClient The library does expose an interface IAnthropicApiClient that can be used for dependency injection and testing. The interface is implemented by the AnthropicApiClient class. Full API Documentation This library was developed to make using the Anthropic API easier within a .NET application. If you are looking for the full API documentation you can find it at Anthropic API Documentation. Usage The primary use case for working with the Anthropic API is to create a message in response to a request that includes one or more other messages. The created message can then be received either as a complete response or a stream of events. This can be used to create a conversation between the caller and Anthropic's AI models and/or to use Anthropic's AI models to perform a task. Note The following examples assume that you have already created an instance of the AnthropicApiClient class named client. You can also find these snippets in the examples directory. Count Message Tokens The AnthropicApiClient exposes a method named CountMessageTokensAsync that can be used to count the number of tokens in a message. The method requires a CountMessageTokensRequest instance as a parameter. using AnthropicClient; using AnthropicClient.Models; var response = await client.CountMessageTokensAsync(new CountMessageTokensRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ] )); if (response.IsFailure) { Console.WriteLine(\"Failed to count message tokens\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } Console.WriteLine(\"Token Count: {0}\", response.Value.InputTokens); List Models The AnthropicApiClient exposes a method named ListModelsAsync that can be used to list the available models. The method takes an optional PagingRequest instance as a parameter. using AnthropicClient; var response = await client.ListModelsAsync(); if (response.IsFailure) { Console.WriteLine(\"Failed to list models\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var model in response.Value.Data) { Console.WriteLine(\"Model Id: {0}\", model.Id); Console.WriteLine(\"Model Name: {0}\", model.DisplayName); } Using the PagingRequest instance allows you to specify the number of models to return and the page of models to return. using AnthropicClient; using AnthropicClient.Models; var response = await client.ListModelsAsync(new PagingRequest(afterId: \"claude-3-5-sonnet-20241022\", limit: 2)); if (response.IsFailure) { Console.WriteLine(\"Failed to list models\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var model in response.Value.Data) { Console.WriteLine(\"Model Id: {0}\", model.Id); Console.WriteLine(\"Model Name: {0}\", model.DisplayName); } Get Model The AnthropicApiClient exposes a method named GetModelAsync that can be used to get a model by its id. using AnthropicClient; var response = await client.GetModelAsync(\"claude-3-5-sonnet-20241022\"); if (response.IsFailure) { Console.WriteLine(\"Failed to get model\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } Console.WriteLine(\"Model Id: {0}\", response.Value.Id); Create a message The AnthropicApiClient exposes a method named CreateMessageAsync that can be used to create a message. The method requires a MessageRequest or a StreamMessageRequest instance as a parameter. The MessageRequest class is used to create a message whose response is not streamed and the StreamMessageRequest class is used to create a message whose response is streamed. The MessageRequest instance's properties can be set to configure how the message is created. Non-Streaming using AnthropicClient; using AnthropicClient.Models; var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ] )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } Streaming Anthropic uses Server-Sent Events (SSE) to stream messages. The possible events and the format of those events are documented in the Anthropic API Documentation. This library provides a way to consume them after they have been deserialized into strongly-typed C# objects that are returned in an IAsyncEnumerable collection. This allows you to consume the events as they are received and process them in the way that best fits your use case. The following example demonstrates how to consume the streamed events and build up the complete text response from the model. using AnthropicClient; using AnthropicClient.Models; var events = client.CreateMessageAsync(new StreamMessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ] )); var msgBuilder = new StringBuilder(); await foreach (var e in events) { switch (e.Data) { case var data when data is ContentDeltaEventData contentData: switch (contentData.Delta) { case var delta when delta is TextDelta textDelta: msgBuilder.Append(textDelta.Text); break; } break; } } Console.WriteLine(msgBuilder.ToString()); Message Complete Event This library also provides a custom message_complete event that is yielded when all the message's events have been received. This event is not part of Anthropic's SSE events but is provided to allow for easier consumption of the entire message response if desired and make it easier to implement built-in tool calling. using AnthropicClient; using AnthropicClient.Models; var events = client.CreateMessageAsync(new StreamMessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ] )); MessageResponse? response = null; await foreach (var e in events) { switch (e.Data) { case var data when data is MessageCompleteEventData msgData: response = msgData.Message; break; } } var textContent = response?.Content .OfType() .Aggregate(new StringBuilder(), (sb, c) => sb.Append(c.Text)) .ToString(); Console.WriteLine(textContent); Tool Use Anthropic's models support the use of tools to perform tasks. This allows the models to interact with external client-side tools that can perform actions the models cannot do natively. This gives you the ability to further extend the model's abilities with your own custom tools. This feature is covered in depth in Anthropic's API Documentation. This library aims to make using tools convenient by allowing you to create, provide, and call tools from within your application by leveraging the reflection capabilities of C#. Note All tools are user provided. The models do no not have access to any built-in server-side tools. Create a tool You can create a tool in 4 different ways and then provide that tool when creating a message. Create a tool from a class Create a tool from a static method Create a tool from an instance method Create a tool from a delegate Create a tool from a class When creating a tool from a class the class must implement the ITool interface. using AnthropicClient.Models; class GetWeatherTool : ITool { public string Name => \"Get Weather\"; public string Description => \"Get the weather for a location in the specified units\"; public MethodInfo Function => typeof(GetWeatherTool).GetMethod(nameof(GetWeather))!; public static string GetWeather(string location, string units) { return $\"The weather in {location} is 72 degrees {units}\"; } } var getWeatherTool = Tool.CreateFromClass(); Create a tool from a static method When creating a tool from a static method the method must be public and static. using AnthropicClient.Models; class GetWeatherTool { public static string GetWeather(string location) { return $\"The weather in {location} is 72 degrees Fahrenheit\"; } } var getWeatherTool = Tool.CreateFromStaticMethod( \"Get Weather\", \"Get the weather for a location in the specified units\", typeof(GetWeatherTool), nameof(GetWeatherTool.GetWeather) ); Create a tool from an instance method When creating a tool from an instance method the method must be public and non-static. using AnthropicClient.Models; class GetWeatherTool { public string GetWeather(string location) { return $\"The weather in {location} is 72 degrees Fahrenheit\"; } } var toolInstance = new GetWeatherTool(); var getWeatherTool = Tool.CreateFromInstanceMethod( \"Get Weather\", \"Get the weather for a location in the specified units\", toolInstance, nameof(toolInstance.GetWeather) ); Create a tool from a delegate When creating a tool from a delegate the delegate must be a Func, Func, or Func. If you need to create a tool from a delegate that takes more than 2 parameters you should create a complex type and pass that as the parameter. using AnthropicClient.Models; var tool = (string location, string units) => $\"The weather in {location} is 72 degrees {units}\"; var getWeatherTool = Tool.CreateFromFunction( \"Get Weather\", \"Get the weather for a location in the specified units\", tool ); Function Parameter Attribute When you create a tool from one of the methods above and send it to Anthropic in your request a JSON representation of the tool is provided in the message. This JSON representation includes the name, description, and input schema of the tool. This information is used by Anthropic's models to discern if and when it should use a tool. This library provides a FunctionParameterAttribute that can be used to provide additional information about the parameters of the tool. This information is used to provide a more detailed input schema for the tool. using AnthropicClient.Models; var tool = ( [FunctionParameter(description: \"The location of the weather being got\", name: \"Location\", required: true)] string location, string units ) => $\"The weather in {location} is 72 degrees {units}\"; var getWeatherTool = Tool.CreateFromFunction( \"Get Weather\", \"Get the weather for a location in the specified units\", tool ); Function Property Attribute This library also provides a FunctionPropertyAttribute that can be used to provide additional information about the members of complex types used as parameters in the tool. This information is used to provide a more detailed input schema for the tool. using AnthropicClient.Models; class GetWeatherInput { [FunctionProperty( description: \"The location of the weather being got\", required: true )] public string Location { get; } = string.Empty; [FunctionProperty( description: \"The units to get the weather in\", required: false, defaultValue: \"Fahrenheit\", possibleValues: [\"Fahrenheit\", \"Celsius\"] )] public string Units { get; } = \"Fahrenheit\"; } var tool = (GetWeatherInput input) => $\"The weather in {input.Location} is 72 degrees {input.Units}\"; var getWeatherTool = Tool.CreateFromFunction( \"Get Weather\", \"Get the weather for a location in the specified units\", tool ); Call a tool It is important to remember that while Anthropic's models do support tool use they don't actually have access to any built-in server-side tools. All tools are user provided. This means that while Anthropic's models can respond to a request to create a message with a request to use a tool that is all it is - a request. It is still up to the client to handle the tool request by calling the tool with the input provided by the model and then providing the result of that call back to the model. This library aims to make this process convenient by allowing you to simply provide the tools you want Anthropic's models to consider for use when creating a message, receive the response, check if the response contains a tool call, and if it does invoke the tool to get the result. Note Anthropic's API expects requests to contain messages that alternate between the user and the assistant. In addition if you receive a tool use from the model the API expects you to respond with a message that contains the result of the tool call. The tool use content will always be from the assistant while the tool result will always be from the user. using AnthropicClient; using AnthropicClient.Models; class GetWeatherTool : ITool { public string Name => \"Get Weather\"; public string Description => \"Get the weather for a location in the specified units\"; public MethodInfo Function => typeof(GetWeatherTool).GetMethod(nameof(GetWeather))!; public static string GetWeather(string location, string units) { return $\"The weather in {location} is 72 degrees {units}\"; } } List messages = [ new( MessageRole.User, [new TextContent(\"What is the weather in New York?\")] ) ]; List tools = [Tool.CreateFromClass()]; var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, messages, tools: tools )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } messages.Add(new(MessageRole.Assistant, response.Content)); foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; case ToolUseContent toolUseContent: Console.WriteLine(toolUseContent.Name); break; } } if (response.Value.ToolCall is not null) { var toolCallResult = await response.Value.ToolCall.InvokeAsync(); string toolResultContent; if (toolCallResult.IsSuccess && toolCallResult.Value is not null) { Console.WriteLine(toolCallResult.Value); toolResultContent = toolCallResult.Value; } else { Console.WriteLine(toolCallResult.Error.Message); toolResultContent = toolCallResult.Error.Message; } messages.Add( new( MessageRole.User, [ new ToolResultContent( response.Value.ToolCall.ToolUse.Id, toolResultContent ) ] ) ); } var finalResponse = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, messages, tools: tools )); if (finalResponse.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", finalResponse.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", finalResponse.Error.Error.Message); return; } foreach (var content in finalResponse.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } If an exception is thrown while invoking the tool the InvokeAsync method will return a ToolCallResult with the exception contained in the Error property. Note The InvokeAsync method does accept a generic type parameter that can be used to specify the type of the Value property of the ToolCallResult. If it is not specified it will be an object. Call a tool in streamed message Tool calling is also supported when streaming the message response. The following example demonstrates how you can handle a tool call in a streamed message response. using AnthropicClient; using AnthropicClient.Models; var tool = (string location, string units) => $\"The weather in {location} is 72 degrees {units}\"; var messages = [ new( MessageRole.User, [new TextContent(\"What is the weather in New York?\")] ) ]; var tools = [Tool.CreateFromFunction( \"Get Weather\", \"Get the weather for a location in the specified units\", tool )]; var events = client.CreateMessageAsync(new StreamMessageRequest( AnthropicModels.Claude3Haiku, messages, tools: tools )); MessageResponse? response = null; await foreach (var e in events) { switch (e.Data) { case var data when data is MessageCompleteEventData msgData: response = msgData.Message; break; } } if (response is null) { Console.WriteLine(\"Failed to get message response\"); return; } messages.Add(new(MessageRole.Assistant, response.Content)); if (response?.ToolCall is not null) { var toolCallResult = await response.ToolCall.InvokeAsync(); string toolResultContent; if (toolCallResult.IsSuccess && toolCallResult.Value is not null) { toolResultContent = toolCallResult.Value; } else { toolResultContent = toolCallResult.Error.Message; } messages.Add( new( MessageRole.User, [ new ToolResultContent( response.ToolCall.ToolUse.Id, toolResultContent ) ] ) ); } var finalResponse = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, messages, tools: tools )); if (finalResponse.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", finalResponse.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", finalResponse.Error.Error.Message); return; } foreach (var content in finalResponse.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } If you do find that you need more control over how exactly provided tools are called and how the result of those tools are returned you can avoid using the InvokeAsync method and instead use the Tool and ToolUse properties of the ToolCall instance to implement your own solution. System Prompt Anthropic's models support the use of system prompts to provide additional context to the user. This can be used to provide additional information to the user or to ask for additional information from the user. This feature is covered in depth in Anthropic's API Documentation. This library aims to make using system prompts convenient by allowing you to provide the system prompts you want Anthropic's models to consider for use when creating a message. System Message You can create a system prompt by providing a string as the system parameter in the MessageRequest or StreamMessageRequest constructor. using AnthropicClient; using AnthropicClient.Models; var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ], system: \"You are a internationally renowned poet. You excel at writing haikus. )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } System Messages You can create a more complex system prompt by providing a List as the systemMessages parameter in the MessageRequest or StreamMessageRequest constructor. using AnthropicClient; using AnthropicClient.Models; var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ], systemMessages: [ new TextContent(\"You are a internationally renowned poet. You excel at writing haikus.\"), new TextContent(\"You have been asked to write a haiku about the ocean.\") ] )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } Prompt Caching Anthropic provides a feature called Prompt Caching that allows you to cache all or part of the prompt you send to the model. This can be used to improve the performance of your application by reducing latency and token usage. This feature is covered in depth in Anthropic's API Documentation. Prompt caching can be used to cache all parts of the prompt including system messages, user messages, and tools. You should refer to the Anthropic API Documentation for specifics on limitations and requirements for using prompt caching. This library aims to make using prompt caching convenient and give you complete control over what parts of the prompt are cached. Currently there is only one type of cache control available - EphemeralCacheControl. Caching System Messages System messages can be cached by providing a List as the systemMessages parameter in the MessageRequest or StreamMessageRequest constructor and having one or more of the TextContent instances have the CacheControl property set. using AnthropicClient; using AnthropicClient.Models; var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ], systemMessages: [ new TextContent(\"You are a internationally renowned poet. You excel at writing haikus. Please use the following as examples.\"), new TextContent(exampleHaikus, new EphemeralCacheControl()) ] )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } Caching User Messages User messages can be cached by providing a List as the messages parameter in the MessageRequest or StreamMessageRequest constructor and having one or more of the Content instances have the CacheControl property set. using AnthropicClient; using AnthropicClient.Models; var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [ new TextContent(\"Please write a haiku about the ocean. Here are some examples of haikus I like.\"), new TextContent(exampleHaikus, new EphemeralCacheControl()) ] ), ] )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } Caching Tools Tools can be cached by providing a List as the tools parameter in the MessageRequest or StreamMessageRequest constructor and having one or more of the Tool instances have the CacheControl property set. This property can be set after the tool is created manually or by using one of the static methods on the Tool class. using AnthropicClient; using AnthropicClient.Models; var tool = (string location, string units) => $\"The weather in {location} is 72 degrees {units}\"; var getWeatherTool = Tool.CreateFromFunction( \"Get Weather\", \"Get the weather for a location in the specified units\", tool, new EphemeralCacheControl() ); var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"What is the weather in New York?\")] ) ], tools: [ // Lots of other tools // ... getWeatherTool ] )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; case ToolUseContent toolUseContent: Console.WriteLine(toolUseContent.Name); break; } } PDF Support Anthropic provides a feature called PDF Support that allows Claude to support PDF input and understand both text and visual content within documents. This feature is covered in depth in Anthropic's API Documentation. PDF support can be used to provide a PDF document as input to the model. This can be used to provide additional context to the model or to ask for additional information from the model. This library aims to make using PDF support convenient by allowing you to provide the PDF document you want Anthropic's models to consider for use when creating a message. PDF Document You can provide a PDF document by providing its base64 encoded content as a DocumentContent instance in the list of messages in the MessageRequest or StreamMessageRequest constructor. using AnthropicClient; using AnthropicClient.Models; var request = new MessageRequest( model: AnthropicModels.Claude35Sonnet, messages: [ new(MessageRole.User, [new TextContent(\"What is the title of this paper?\")]), new(MessageRole.User, [new DocumentContent(\"application/pdf\", base64Data)]) ] ); var response = await client.CreateMessageAsync(request); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } Message Batches Anthropic provides a feature called Message Batches that allows you to send multiple messages in a single request. This feature is covered in depth in Anthropic's API Documentation. Create a message batch You can create a message batch that will consist of one or more requests to create messages. using AnthropicClient; using AnthropicClient.Models; var request = new MessageBatchRequest([ new( Guid.NewGuid().ToString(), new( model: AnthropicModels.Claude3Haiku, messages: [new(MessageRole.User, [new TextContent(\"Hello!\")])] ) ), ]); var response = await client.CreateMessageBatchAsync(request); if (response.IsFailure) { Console.WriteLine(\"Failed to create message batch\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } Console.WriteLine(\"Message Batch Id: {0}\", response.Value.Id); Get a message batch You can retrieve a message batch by its id. using AnthropicClient; using AnthropicClient.Models; var response = await client.GetMessageBatchAsync(\"batch-id\"); if (response.IsFailure) { Console.WriteLine(\"Failed to get message batch\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } Console.WriteLine(\"Message Batch Id: {0}\", response.Value.Id); Get a message batch results You can retrieve the results of a message batch by its id. The results are returned as an IAsyncEnumerable collection so that they can be streamed and processed as they are received. using AnthropicClient; using AnthropicClient.Models; var response = await client.GetMessageBatchResultsAsync(\"batch-id\"); if (response.IsFailure) { Console.WriteLine(\"Failed to get message batch results\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } await foreach (var item in response.Value) { Console.WriteLine(\"Item Custom Id: {0}\", result.CustomId); switch (item.Result) { case SucceededMessageBatchResult successResult: foreach (var content in successResult.Message.Content) { if (content is TextContent textContent) { Console.WriteLine(\"Message Batch Result: {0}\", textContent.Text); } } break; default: Console.WriteLine(\"Message Batch Result: {0}\", item.Result.Type); break; } } List message batches You can retrieve a page of message batches. using AnthropicClient; using AnthropicClient.Models; var response = await client.ListMessageBatchesAsync(); if (response.IsFailure) { Console.WriteLine(\"Failed to list message batches\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var batch in response.Value.Data) { Console.WriteLine(\"Message Batch Id: {0}\", batch.Id); } List all message batches You can also retrieve all the pages of message batches without having to implement pagination yourself. This is done by returning an IAsyncEnumerable collection that can be streamed and processed as the pages are received. using AnthropicClient; using AnthropicClient.Models; var pageResponses = client.ListAllMessageBatchesAsync(); await foreach (var response in pageResponses) { if (response.IsFailure) { Console.WriteLine(\"Failed to list message batches\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var batch in response.Value.Data) { Console.WriteLine(\"Message Batch Id: {0}\", batch.Id); } } Cancel a message batch You can cancel a message batch by its id. using AnthropicClient; using AnthropicClient.Models; var response = await client.CancelMessageBatchAsync(\"batch-id\"); if (response.IsFailure) { Console.WriteLine(\"Failed to cancel message batch\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } Console.WriteLine(\"Message Batch Id: {0}\", response.Value.Id); Console.WriteLine(\"Message Batch Status: {0}\", response.Value.ProcessingStatus); Delete a message batch You can delete a message batch that is no longer being processed by its id. using AnthropicClient; using AnthropicClient.Models; var response = await client.DeleteMessageBatchAsync(\"batch-id\"); if (response.IsFailure) { Console.WriteLine(\"Failed to delete message batch\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } Console.WriteLine(\"Message Batch Id: {0}\", response.Value.Id);"
+ "summary": "AnthropicClient This library for the Anthropic API is meant to simplify development in C# for Anthropic users. Note This is an unofficial SDK for the Anthropic API. It was not built in consultation with Anthropic or any member of their organization. This SDK was developed independently using existing libraries and the Anthropic API documentation as the starting point with the intention of making development of integrations done in C# with Anthropic quicker and more convenient. Note This client library is heavily inspired by the Anthropic.SDK library. I chose to create a new library because I wanted to handle streaming and tool calling differently as well as have control over the client library as I plan to use it to build a connector for SemanticKernel. However if you are looking for a client library the Anthropic.SDK is a great place to start. \uD83D\uDCDD Issues If you encounter any issues while using this library please open an issue here. \uD83D\uDCDC License This library is licensed under the MIT License and is free to use and modify. \uD83D\uDCDD Contributing If you would like to contribute to this library please open a pull request here. \uD83D\uDEE0️ Dependencies Microsoft.Bcl.AsyncInterfaces Used to support async interfaces when streaming messages System.Text.Json Used for JSON serialization and deserialization \uD83D\uDCBE Installation Install the package from NuGet using the following command: dotnet add package AnthropicClient \uD83D\uDD11 API Key In order to use the Anthropic API you will need an API key. You can get one by signing up at Anthropic. Please keep your API key secure and do not share it with others. Be mindful of where you store your API key and do not commit it to a public repository. \uD83D\uDC68\uD83C\uDFFB\uD83D\uDCBB Start Coding AnthropicApiClient The most common way to use the SDK is to create an AnthropicApiClient instance and call its methods. Its constructor requires two parameters: apiKey - your Anthropic API key httpClient - an HttpClient instance. You can configure and customize the HttpClient instance as needed. This library however will perform the necessary configuration to work with the Anthropic API. Such as setting the base address and adding the proper headers. Note This library does not manage the lifecycle of the HttpClient instance. You should create and manage the lifecycle of the HttpClient instance in your application. It is best practice to read the API key from a secure location such as a configuration file or environment variable. For example using the appsettings.json file: { \"AnthropicApiKey\": \"YOUR_API\" } Example constructing an AnthropicApiClient instance: using AnthropicClient; using Microsoft.Extensions.Configuration; var configuration = new ConfigurationBuilder() .AddJsonFile(\"appsettings.json\") .Build(); var apiKey = configuration[\"AnthropicApiKey\"]; var client = new AnthropicApiClient(apiKey, new HttpClient()); IAnthropicApiClient The library does expose an interface IAnthropicApiClient that can be used for dependency injection and testing. The interface is implemented by the AnthropicApiClient class. Full API Documentation This library was developed to make using the Anthropic API easier within a .NET application. If you are looking for the full API documentation you can find it at Anthropic API Documentation. Usage The primary use case for working with the Anthropic API is to create a message in response to a request that includes one or more other messages. The created message can then be received either as a complete response or a stream of events. This can be used to create a conversation between the caller and Anthropic's AI models and/or to use Anthropic's AI models to perform a task. Note The following examples assume that you have already created an instance of the AnthropicApiClient class named client. You can also find these snippets in the examples directory. Count Message Tokens The AnthropicApiClient exposes a method named CountMessageTokensAsync that can be used to count the number of tokens in a message. The method requires a CountMessageTokensRequest instance as a parameter. using AnthropicClient; using AnthropicClient.Models; var response = await client.CountMessageTokensAsync(new CountMessageTokensRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ] )); if (response.IsFailure) { Console.WriteLine(\"Failed to count message tokens\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } Console.WriteLine(\"Token Count: {0}\", response.Value.InputTokens); List Models The AnthropicApiClient exposes a method named ListModelsAsync that can be used to list the available models. The method takes an optional PagingRequest instance as a parameter. using AnthropicClient; var response = await client.ListModelsAsync(); if (response.IsFailure) { Console.WriteLine(\"Failed to list models\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var model in response.Value.Data) { Console.WriteLine(\"Model Id: {0}\", model.Id); Console.WriteLine(\"Model Name: {0}\", model.DisplayName); } Using the PagingRequest instance allows you to specify the number of models to return and the page of models to return. using AnthropicClient; using AnthropicClient.Models; var response = await client.ListModelsAsync(new PagingRequest(afterId: \"claude-3-5-sonnet-20241022\", limit: 2)); if (response.IsFailure) { Console.WriteLine(\"Failed to list models\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var model in response.Value.Data) { Console.WriteLine(\"Model Id: {0}\", model.Id); Console.WriteLine(\"Model Name: {0}\", model.DisplayName); } Get Model The AnthropicApiClient exposes a method named GetModelAsync that can be used to get a model by its id. using AnthropicClient; var response = await client.GetModelAsync(\"claude-3-5-sonnet-20241022\"); if (response.IsFailure) { Console.WriteLine(\"Failed to get model\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } Console.WriteLine(\"Model Id: {0}\", response.Value.Id); Create a message The AnthropicApiClient exposes a method named CreateMessageAsync that can be used to create a message. The method requires a MessageRequest or a StreamMessageRequest instance as a parameter. The MessageRequest class is used to create a message whose response is not streamed and the StreamMessageRequest class is used to create a message whose response is streamed. The MessageRequest instance's properties can be set to configure how the message is created. Non-Streaming using AnthropicClient; using AnthropicClient.Models; var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ] )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } Streaming Anthropic uses Server-Sent Events (SSE) to stream messages. The possible events and the format of those events are documented in the Anthropic API Documentation. This library provides a way to consume them after they have been deserialized into strongly-typed C# objects that are returned in an IAsyncEnumerable collection. This allows you to consume the events as they are received and process them in the way that best fits your use case. The following example demonstrates how to consume the streamed events and build up the complete text response from the model. using AnthropicClient; using AnthropicClient.Models; var events = client.CreateMessageAsync(new StreamMessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ] )); var msgBuilder = new StringBuilder(); await foreach (var e in events) { switch (e.Data) { case var data when data is ContentDeltaEventData contentData: switch (contentData.Delta) { case var delta when delta is TextDelta textDelta: msgBuilder.Append(textDelta.Text); break; } break; } } Console.WriteLine(msgBuilder.ToString()); Message Complete Event This library also provides a custom message_complete event that is yielded when all the message's events have been received. This event is not part of Anthropic's SSE events but is provided to allow for easier consumption of the entire message response if desired and make it easier to implement built-in tool calling. using AnthropicClient; using AnthropicClient.Models; var events = client.CreateMessageAsync(new StreamMessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ] )); MessageResponse? response = null; await foreach (var e in events) { switch (e.Data) { case var data when data is MessageCompleteEventData msgData: response = msgData.Message; break; } } var textContent = response?.Content .OfType() .Aggregate(new StringBuilder(), (sb, c) => sb.Append(c.Text)) .ToString(); Console.WriteLine(textContent); Tool Use Anthropic's models support the use of tools to perform tasks. This allows the models to interact with external client-side tools that can perform actions the models cannot do natively. This gives you the ability to further extend the model's abilities with your own custom tools. This feature is covered in depth in Anthropic's API Documentation. This library aims to make using tools convenient by allowing you to create, provide, and call tools from within your application by leveraging the reflection capabilities of C#. Note All tools are user provided. The models do no not have access to any built-in server-side tools. Create a tool You can create a tool in 4 different ways and then provide that tool when creating a message. Create a tool from a class Create a tool from a static method Create a tool from an instance method Create a tool from a delegate Create a tool from a class When creating a tool from a class the class must implement the ITool interface. using AnthropicClient.Models; class GetWeatherTool : ITool { public string Name => \"Get Weather\"; public string Description => \"Get the weather for a location in the specified units\"; public MethodInfo Function => typeof(GetWeatherTool).GetMethod(nameof(GetWeather))!; public static string GetWeather(string location, string units) { return $\"The weather in {location} is 72 degrees {units}\"; } } var getWeatherTool = Tool.CreateFromClass(); Create a tool from a static method When creating a tool from a static method the method must be public and static. using AnthropicClient.Models; class GetWeatherTool { public static string GetWeather(string location) { return $\"The weather in {location} is 72 degrees Fahrenheit\"; } } var getWeatherTool = Tool.CreateFromStaticMethod( \"Get Weather\", \"Get the weather for a location in the specified units\", typeof(GetWeatherTool), nameof(GetWeatherTool.GetWeather) ); Create a tool from an instance method When creating a tool from an instance method the method must be public and non-static. using AnthropicClient.Models; class GetWeatherTool { public string GetWeather(string location) { return $\"The weather in {location} is 72 degrees Fahrenheit\"; } } var toolInstance = new GetWeatherTool(); var getWeatherTool = Tool.CreateFromInstanceMethod( \"Get Weather\", \"Get the weather for a location in the specified units\", toolInstance, nameof(toolInstance.GetWeather) ); Create a tool from a delegate When creating a tool from a delegate the delegate must be a Func, Func, or Func. If you need to create a tool from a delegate that takes more than 2 parameters you should create a complex type and pass that as the parameter. using AnthropicClient.Models; var tool = (string location, string units) => $\"The weather in {location} is 72 degrees {units}\"; var getWeatherTool = Tool.CreateFromFunction( \"Get Weather\", \"Get the weather for a location in the specified units\", tool ); Function Parameter Attribute When you create a tool from one of the methods above and send it to Anthropic in your request a JSON representation of the tool is provided in the message. This JSON representation includes the name, description, and input schema of the tool. This information is used by Anthropic's models to discern if and when it should use a tool. This library provides a FunctionParameterAttribute that can be used to provide additional information about the parameters of the tool. This information is used to provide a more detailed input schema for the tool. using AnthropicClient.Models; var tool = ( [FunctionParameter(description: \"The location of the weather being got\", name: \"Location\", required: true)] string location, string units ) => $\"The weather in {location} is 72 degrees {units}\"; var getWeatherTool = Tool.CreateFromFunction( \"Get Weather\", \"Get the weather for a location in the specified units\", tool ); Function Property Attribute This library also provides a FunctionPropertyAttribute that can be used to provide additional information about the members of complex types used as parameters in the tool. This information is used to provide a more detailed input schema for the tool. using AnthropicClient.Models; class GetWeatherInput { [FunctionProperty( description: \"The location of the weather being got\", required: true )] public string Location { get; } = string.Empty; [FunctionProperty( description: \"The units to get the weather in\", required: false, defaultValue: \"Fahrenheit\", possibleValues: [\"Fahrenheit\", \"Celsius\"] )] public string Units { get; } = \"Fahrenheit\"; } var tool = (GetWeatherInput input) => $\"The weather in {input.Location} is 72 degrees {input.Units}\"; var getWeatherTool = Tool.CreateFromFunction( \"Get Weather\", \"Get the weather for a location in the specified units\", tool ); Call a tool It is important to remember that while Anthropic's models do support tool use they don't actually have access to any built-in server-side tools. All tools are user provided. This means that while Anthropic's models can respond to a request to create a message with a request to use a tool that is all it is - a request. It is still up to the client to handle the tool request by calling the tool with the input provided by the model and then providing the result of that call back to the model. This library aims to make this process convenient by allowing you to simply provide the tools you want Anthropic's models to consider for use when creating a message, receive the response, check if the response contains a tool call, and if it does invoke the tool to get the result. Note Anthropic's API expects requests to contain messages that alternate between the user and the assistant. In addition if you receive a tool use from the model the API expects you to respond with a message that contains the result of the tool call. The tool use content will always be from the assistant while the tool result will always be from the user. using AnthropicClient; using AnthropicClient.Models; class GetWeatherTool : ITool { public string Name => \"Get Weather\"; public string Description => \"Get the weather for a location in the specified units\"; public MethodInfo Function => typeof(GetWeatherTool).GetMethod(nameof(GetWeather))!; public static string GetWeather(string location, string units) { return $\"The weather in {location} is 72 degrees {units}\"; } } List messages = [ new( MessageRole.User, [new TextContent(\"What is the weather in New York?\")] ) ]; List tools = [Tool.CreateFromClass()]; var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, messages, tools: tools )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } messages.Add(new(MessageRole.Assistant, response.Content)); foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; case ToolUseContent toolUseContent: Console.WriteLine(toolUseContent.Name); break; } } if (response.Value.ToolCall is not null) { var toolCallResult = await response.Value.ToolCall.InvokeAsync(); string toolResultContent; if (toolCallResult.IsSuccess && toolCallResult.Value is not null) { Console.WriteLine(toolCallResult.Value); toolResultContent = toolCallResult.Value; } else { Console.WriteLine(toolCallResult.Error.Message); toolResultContent = toolCallResult.Error.Message; } messages.Add( new( MessageRole.User, [ new ToolResultContent( response.Value.ToolCall.ToolUse.Id, toolResultContent ) ] ) ); } var finalResponse = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, messages, tools: tools )); if (finalResponse.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", finalResponse.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", finalResponse.Error.Error.Message); return; } foreach (var content in finalResponse.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } If an exception is thrown while invoking the tool the InvokeAsync method will return a ToolCallResult with the exception contained in the Error property. Note The InvokeAsync method does accept a generic type parameter that can be used to specify the type of the Value property of the ToolCallResult. If it is not specified it will be an object. Call a tool in streamed message Tool calling is also supported when streaming the message response. The following example demonstrates how you can handle a tool call in a streamed message response. using AnthropicClient; using AnthropicClient.Models; var tool = (string location, string units) => $\"The weather in {location} is 72 degrees {units}\"; var messages = [ new( MessageRole.User, [new TextContent(\"What is the weather in New York?\")] ) ]; var tools = [Tool.CreateFromFunction( \"Get Weather\", \"Get the weather for a location in the specified units\", tool )]; var events = client.CreateMessageAsync(new StreamMessageRequest( AnthropicModels.Claude3Haiku, messages, tools: tools )); MessageResponse? response = null; await foreach (var e in events) { switch (e.Data) { case var data when data is MessageCompleteEventData msgData: response = msgData.Message; break; } } if (response is null) { Console.WriteLine(\"Failed to get message response\"); return; } messages.Add(new(MessageRole.Assistant, response.Content)); if (response?.ToolCall is not null) { var toolCallResult = await response.ToolCall.InvokeAsync(); string toolResultContent; if (toolCallResult.IsSuccess && toolCallResult.Value is not null) { toolResultContent = toolCallResult.Value; } else { toolResultContent = toolCallResult.Error.Message; } messages.Add( new( MessageRole.User, [ new ToolResultContent( response.ToolCall.ToolUse.Id, toolResultContent ) ] ) ); } var finalResponse = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, messages, tools: tools )); if (finalResponse.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", finalResponse.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", finalResponse.Error.Error.Message); return; } foreach (var content in finalResponse.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } If you do find that you need more control over how exactly provided tools are called and how the result of those tools are returned you can avoid using the InvokeAsync method and instead use the Tool and ToolUse properties of the ToolCall instance to implement your own solution. System Prompt Anthropic's models support the use of system prompts to provide additional context to the user. This can be used to provide additional information to the user or to ask for additional information from the user. This feature is covered in depth in Anthropic's API Documentation. This library aims to make using system prompts convenient by allowing you to provide the system prompts you want Anthropic's models to consider for use when creating a message. System Message You can create a system prompt by providing a string as the system parameter in the MessageRequest or StreamMessageRequest constructor. using AnthropicClient; using AnthropicClient.Models; var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ], system: \"You are a internationally renowned poet. You excel at writing haikus. )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } System Messages You can create a more complex system prompt by providing a List as the systemMessages parameter in the MessageRequest or StreamMessageRequest constructor. using AnthropicClient; using AnthropicClient.Models; var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ], systemMessages: [ new TextContent(\"You are a internationally renowned poet. You excel at writing haikus.\"), new TextContent(\"You have been asked to write a haiku about the ocean.\") ] )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } Prompt Caching Anthropic provides a feature called Prompt Caching that allows you to cache all or part of the prompt you send to the model. This can be used to improve the performance of your application by reducing latency and token usage. This feature is covered in depth in Anthropic's API Documentation. Prompt caching can be used to cache all parts of the prompt including system messages, user messages, and tools. You should refer to the Anthropic API Documentation for specifics on limitations and requirements for using prompt caching. This library aims to make using prompt caching convenient and give you complete control over what parts of the prompt are cached. Currently there is only one type of cache control available - EphemeralCacheControl. Caching System Messages System messages can be cached by providing a List as the systemMessages parameter in the MessageRequest or StreamMessageRequest constructor and having one or more of the TextContent instances have the CacheControl property set. using AnthropicClient; using AnthropicClient.Models; var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"Please write a haiku about the ocean.\")] ) ], systemMessages: [ new TextContent(\"You are a internationally renowned poet. You excel at writing haikus. Please use the following as examples.\"), new TextContent(exampleHaikus, new EphemeralCacheControl()) ] )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } Caching User Messages User messages can be cached by providing a List as the messages parameter in the MessageRequest or StreamMessageRequest constructor and having one or more of the Content instances have the CacheControl property set. using AnthropicClient; using AnthropicClient.Models; var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [ new TextContent(\"Please write a haiku about the ocean. Here are some examples of haikus I like.\"), new TextContent(exampleHaikus, new EphemeralCacheControl()) ] ), ] )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } Caching Tools Tools can be cached by providing a List as the tools parameter in the MessageRequest or StreamMessageRequest constructor and having one or more of the Tool instances have the CacheControl property set. This property can be set after the tool is created manually or by using one of the static methods on the Tool class. using AnthropicClient; using AnthropicClient.Models; var tool = (string location, string units) => $\"The weather in {location} is 72 degrees {units}\"; var getWeatherTool = Tool.CreateFromFunction( \"Get Weather\", \"Get the weather for a location in the specified units\", tool, new EphemeralCacheControl() ); var response = await client.CreateMessageAsync(new MessageRequest( AnthropicModels.Claude3Haiku, [ new( MessageRole.User, [new TextContent(\"What is the weather in New York?\")] ) ], tools: [ // Lots of other tools // ... getWeatherTool ] )); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; case ToolUseContent toolUseContent: Console.WriteLine(toolUseContent.Name); break; } } PDF Support Anthropic provides a feature called PDF Support that allows Claude to support PDF input and understand both text and visual content within documents. This feature is covered in depth in Anthropic's API Documentation. PDF support can be used to provide a PDF document as input to the model. This can be used to provide additional context to the model or to ask for additional information from the model. This library aims to make using PDF support convenient by allowing you to provide the PDF document you want Anthropic's models to consider for use when creating a message. PDF Document You can provide a PDF document by providing its base64 encoded content as a DocumentContent instance in the list of messages in the MessageRequest or StreamMessageRequest constructor. using AnthropicClient; using AnthropicClient.Models; var request = new MessageRequest( model: AnthropicModels.Claude35Sonnet, messages: [ new(MessageRole.User, [new TextContent(\"What is the title of this paper?\")]), new(MessageRole.User, [new DocumentContent(\"application/pdf\", base64Data)]) ] ); var response = await client.CreateMessageAsync(request); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(textContent.Text); break; } } Citations Anthropic provides a feature called Citations that allows Claude to provide citations for information extracted from documents. This feature enables Claude to reference specific parts of the source material when answering questions, making it easier to verify information and understand the context of responses. Citations can be enabled for documents and will return references to the specific locations in the source material where information was found. This library provides comprehensive support for citations through strongly-typed models that represent different types of citation locations. Enabling Citations for Documents You can enable citations for documents by setting the Citations property on DocumentContent instances: using AnthropicClient; using AnthropicClient.Models; var request = new MessageRequest( model: AnthropicModels.Claude35Sonnet, messages: [ new(MessageRole.User, [ new DocumentContent(new TextSource(\"The grass is green. The sky is blue.\")) { Title = \"My Document\", Context = \"This is a trustworthy document.\", Citations = new() { Enabled = true } }, new TextContent(\"What color is the grass and sky?\") ]) ] ); var response = await client.CreateMessageAsync(request); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(\"Response: {0}\", textContent.Text); if (textContent.Citations is not null) { Console.WriteLine(\"Citations:\"); foreach (var citation in textContent.Citations) { Console.WriteLine(\" - Cited Text: {0}\", citation.CitedText); Console.WriteLine(\" Document: {0}\", citation.DocumentTitle); Console.WriteLine(\" Type: {0}\", citation.Type); switch (citation) { case CharacterLocationCitation charCitation: Console.WriteLine( \" Character Range: {0}-{1}\", charCitation.StartCharIndex, charCitation.EndCharIndex ); break; case PageLocationCitation pageCitation: Console.WriteLine( \" Page Range: {0}-{1}\", pageCitation.StartPageNumber, pageCitation.EndPageNumber ); break; case ContentBlockLocationCitation blockCitation: Console.WriteLine( \" Block Range: {0}-{1}\", blockCitation.StartBlockIndex, blockCitation.EndBlockIndex ); break; } } } break; } } Citations with PDF Documents Citations work particularly well with PDF documents, providing page-level references: using AnthropicClient; using AnthropicClient.Models; var pdfBytes = await File.ReadAllBytesAsync(\"document.pdf\"); var base64Data = Convert.ToBase64String(pdfBytes); var request = new MessageRequest( model: AnthropicModels.Claude35Sonnet, messages: [ new(MessageRole.User, [ new DocumentContent(\"application/pdf\", base64Data) { Title = \"Research Paper\", Citations = new() { Enabled = true } }, new TextContent(\"Summarize the key findings from this research paper.\") ]) ] ); var response = await client.CreateMessageAsync(request); if (response.IsSuccess is false) { Console.WriteLine(\"Failed to create message\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var content in response.Value.Content) { switch (content) { case TextContent textContent: Console.WriteLine(\"Summary: {0}\", textContent.Text); if (textContent.Citations is not null) { Console.WriteLine(\"\\nCitations:\"); foreach (var citation in textContent.Citations.OfType()) { Console.WriteLine( \" - \\\"{0}\\\" (Pages {1}-{2})\", citation.CitedText, citation.StartPageNumber, citation.EndPageNumber ); } } break; } } Citations in Streaming Responses Citations are also supported in streaming responses through the CitationDelta events: using AnthropicClient; using AnthropicClient.Models; var request = new StreamMessageRequest( model: AnthropicModels.Claude35Sonnet, messages: [ new(MessageRole.User, [ new DocumentContent(new TextSource(\"The grass is green. The sky is blue.\")) { Citations = new() { Enabled = true } }, new TextContent(\"What color is the grass?\") ]) ] ); var events = client.CreateMessageAsync(request); await foreach (var e in events) { switch (e.Data) { case ContentDeltaEventData contentData: switch (contentData.Delta) { case CitationDelta citationDelta: Console.WriteLine(\"Citation: {0}\", citationDelta.Citation.CitedText); Console.WriteLine(\"Type: {0}\", citationDelta.Citation.Type); break; case TextDelta textDelta: Console.Write(textDelta.Text); break; } break; } } Message Batches Anthropic provides a feature called Message Batches that allows you to send multiple messages in a single request. This feature is covered in depth in Anthropic's API Documentation. Create a message batch You can create a message batch that will consist of one or more requests to create messages. using AnthropicClient; using AnthropicClient.Models; var request = new MessageBatchRequest([ new( Guid.NewGuid().ToString(), new( model: AnthropicModels.Claude3Haiku, messages: [new(MessageRole.User, [new TextContent(\"Hello!\")])] ) ), ]); var response = await client.CreateMessageBatchAsync(request); if (response.IsFailure) { Console.WriteLine(\"Failed to create message batch\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } Console.WriteLine(\"Message Batch Id: {0}\", response.Value.Id); Get a message batch You can retrieve a message batch by its id. using AnthropicClient; using AnthropicClient.Models; var response = await client.GetMessageBatchAsync(\"batch-id\"); if (response.IsFailure) { Console.WriteLine(\"Failed to get message batch\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } Console.WriteLine(\"Message Batch Id: {0}\", response.Value.Id); Get a message batch results You can retrieve the results of a message batch by its id. The results are returned as an IAsyncEnumerable collection so that they can be streamed and processed as they are received. using AnthropicClient; using AnthropicClient.Models; var response = await client.GetMessageBatchResultsAsync(\"batch-id\"); if (response.IsFailure) { Console.WriteLine(\"Failed to get message batch results\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } await foreach (var item in response.Value) { Console.WriteLine(\"Item Custom Id: {0}\", result.CustomId); switch (item.Result) { case SucceededMessageBatchResult successResult: foreach (var content in successResult.Message.Content) { if (content is TextContent textContent) { Console.WriteLine(\"Message Batch Result: {0}\", textContent.Text); } } break; default: Console.WriteLine(\"Message Batch Result: {0}\", item.Result.Type); break; } } List message batches You can retrieve a page of message batches. using AnthropicClient; using AnthropicClient.Models; var response = await client.ListMessageBatchesAsync(); if (response.IsFailure) { Console.WriteLine(\"Failed to list message batches\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var batch in response.Value.Data) { Console.WriteLine(\"Message Batch Id: {0}\", batch.Id); } List all message batches You can also retrieve all the pages of message batches without having to implement pagination yourself. This is done by returning an IAsyncEnumerable collection that can be streamed and processed as the pages are received. using AnthropicClient; using AnthropicClient.Models; var pageResponses = client.ListAllMessageBatchesAsync(); await foreach (var response in pageResponses) { if (response.IsFailure) { Console.WriteLine(\"Failed to list message batches\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } foreach (var batch in response.Value.Data) { Console.WriteLine(\"Message Batch Id: {0}\", batch.Id); } } Cancel a message batch You can cancel a message batch by its id. using AnthropicClient; using AnthropicClient.Models; var response = await client.CancelMessageBatchAsync(\"batch-id\"); if (response.IsFailure) { Console.WriteLine(\"Failed to cancel message batch\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } Console.WriteLine(\"Message Batch Id: {0}\", response.Value.Id); Console.WriteLine(\"Message Batch Status: {0}\", response.Value.ProcessingStatus); Delete a message batch You can delete a message batch that is no longer being processed by its id. using AnthropicClient; using AnthropicClient.Models; var response = await client.DeleteMessageBatchAsync(\"batch-id\"); if (response.IsFailure) { Console.WriteLine(\"Failed to delete message batch\"); Console.WriteLine(\"Error Type: {0}\", response.Error.Error.Type); Console.WriteLine(\"Error Message: {0}\", response.Error.Error.Message); return; } Console.WriteLine(\"Message Batch Id: {0}\", response.Value.Id);"
}
}
\ No newline at end of file
diff --git a/docs/manifest.json b/docs/manifest.json
index dea9e22..f5fbbc6 100644
--- a/docs/manifest.json
+++ b/docs/manifest.json
@@ -178,6 +178,20 @@
"Title": "AnthropicClient.Models.AutoToolChoice",
"Summary": "