feat: add support for citations when streaming

This commit is contained in:
Stevan Freeborn
2025-06-14 22:24:44 -05:00
parent 74ac1ffc06
commit 98da1384c1
5 changed files with 188 additions and 7 deletions
+30 -3
View File
@@ -124,10 +124,37 @@ public class AnthropicApiClient : IAnthropicApiClient
// current content type and delta type
if (currentEvent.Type is EventType.ContentBlockDelta && currentEvent.Data is ContentDeltaEventData contentDeltaData)
{
if (content is TextContent textContent && contentDeltaData.Delta is TextDelta textDelta)
if (content is TextContent textContent)
{
var newText = textContent.Text + textDelta.Text;
content = new TextContent(newText);
if (contentDeltaData.Delta is TextDelta textDelta)
{
var newText = textContent.Text + textDelta.Text;
content = new TextContent(newText)
{
Citations = textContent.Citations,
};
}
if (contentDeltaData.Delta is CitationDelta citationDelta)
{
var citations = new List<Citation>()
{
citationDelta.Citation,
};
if (textContent.Citations is not null)
{
citations.AddRange(textContent.Citations);
}
var newContent = new TextContent(textContent.Text)
{
Citations = [.. citations],
};
content = newContent;
}
}
if (content is ToolUseContent toolUseContent && contentDeltaData.Delta is JsonDelta jsonDelta)
@@ -16,6 +16,7 @@ class ContentDeltaConverter : JsonConverter<ContentDelta>
{
ContentDeltaType.TextDelta => JsonSerializer.Deserialize<TextDelta>(root.GetRawText(), options)!,
ContentDeltaType.JsonDelta => JsonSerializer.Deserialize<JsonDelta>(root.GetRawText(), options)!,
ContentDeltaType.CitationDelta => JsonSerializer.Deserialize<CitationDelta>(root.GetRawText(), options)!,
_ => throw new JsonException($"Unknown content type: {type}")
};
}
@@ -0,0 +1,30 @@
using System.Text.Json.Serialization;
using AnthropicClient.Utils;
namespace AnthropicClient.Models;
/// <summary>
/// Represents a citation delta.
/// </summary>
public class CitationDelta : ContentDelta
{
/// <summary>
/// Gets the citation associated with this delta.
/// </summary>
public Citation Citation { get; init; } = new CharacterLocationCitation();
[JsonConstructor]
internal CitationDelta() : base(ContentDeltaType.CitationDelta)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CitationDelta"/> class.
/// </summary>
public CitationDelta(Citation citation) : base(ContentDeltaType.CitationDelta)
{
ArgumentValidator.ThrowIfNull(citation, nameof(citation));
Citation = citation;
}
}
@@ -14,4 +14,9 @@ public static class ContentDeltaType
/// The input_json_delta.
/// </summary>
public const string JsonDelta = "input_json_delta";
/// <summary>
/// The citation_delta.
/// </summary>
public const string CitationDelta = "citations_delta";
}