diff --git a/app/MindWork AI Studio/Provider/Anthropic/AnthropicMessageStreamAccumulator.cs b/app/MindWork AI Studio/Provider/Anthropic/AnthropicMessageStreamAccumulator.cs
index 075a1978..f12c157f 100644
--- a/app/MindWork AI Studio/Provider/Anthropic/AnthropicMessageStreamAccumulator.cs
+++ b/app/MindWork AI Studio/Provider/Anthropic/AnthropicMessageStreamAccumulator.cs
@@ -14,6 +14,7 @@ namespace AIStudio.Provider.Anthropic;
///
public sealed class AnthropicMessageStreamAccumulator
{
+ private const string EVENT_MESSAGE_START = "message_start";
private const string EVENT_BLOCK_START = "content_block_start";
private const string EVENT_BLOCK_DELTA = "content_block_delta";
private const string EVENT_BLOCK_STOP = "content_block_stop";
@@ -32,7 +33,7 @@ public sealed class AnthropicMessageStreamAccumulator
/// Takes the next event of the stream and returns what it has to show.
///
/// The event to read.
- /// The text of this event, empty when it carried none.
+ /// The text of this event, empty when it carried none, and the usage of the message start.
public AnthropicStreamPart Process(ServerSentEvent serverSentEvent)
{
if (serverSentEvent.Data.Length is 0)
@@ -51,6 +52,14 @@ public sealed class AnthropicMessageStreamAccumulator
switch (line.Type)
{
+ case EVENT_MESSAGE_START:
+ //
+ // What the request carried, read the same way as on the plain text path and for
+ // the same reason: the start states this request alone, cf. ResponseStreamLine.
+ //
+ var usage = line.Message?.Usage?.ToTokenUsage() ?? TokenUsage.UNKNOWN;
+ return usage.IsKnown ? new AnthropicStreamPart(string.Empty, usage) : AnthropicStreamPart.Nothing;
+
case EVENT_BLOCK_START:
this.openBlocks[line.Index] = new AnthropicContentBlockBuilder(line.ContentBlock);
return AnthropicStreamPart.Nothing;
diff --git a/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamLine.cs b/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamLine.cs
index e58ffff1..c32a0e93 100644
--- a/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamLine.cs
+++ b/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamLine.cs
@@ -9,4 +9,14 @@ namespace AIStudio.Provider.Anthropic;
/// Which content block the event belongs to; blocks are correlated by it.
/// The block as it opens, for a content block start.
/// The piece this event adds, for a content block delta or a message delta.
-public readonly record struct AnthropicStreamLine(string? Type, int Index, JsonElement ContentBlock, AnthropicStreamDelta Delta);
\ No newline at end of file
+public readonly record struct AnthropicStreamLine(string? Type, int Index, JsonElement ContentBlock, AnthropicStreamDelta Delta)
+{
+ ///
+ /// The message the stream opens with, for a message start.
+ ///
+ ///
+ /// Not a positional parameter, because nobody but the serializer ever builds this line with
+ /// one. It is what states the usage, for the reason given at ResponseStreamLine.GetUsage.
+ ///
+ public AnthropicStreamMessage? Message { get; init; }
+}
\ No newline at end of file
diff --git a/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamMessage.cs b/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamMessage.cs
new file mode 100644
index 00000000..660400f3
--- /dev/null
+++ b/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamMessage.cs
@@ -0,0 +1,18 @@
+// ReSharper disable ClassNeverInstantiated.Global
+namespace AIStudio.Provider.Anthropic;
+
+///
+/// The message a streamed Anthropic messages call opens with, as far as it is read.
+///
+///
+/// It arrives on the message start event, before any content, and states what the request
+/// carried. Its content is always empty there -- the blocks follow as events of their own -- so
+/// the usage is all there is to read.
+///
+public sealed record AnthropicStreamMessage
+{
+ ///
+ /// What the request carried, where the stream states it.
+ ///
+ public AnthropicUsage? Usage { get; init; }
+}
\ No newline at end of file
diff --git a/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamPart.cs b/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamPart.cs
index bc8f1bd1..8c6f96b2 100644
--- a/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamPart.cs
+++ b/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamPart.cs
@@ -8,15 +8,20 @@ namespace AIStudio.Provider.Anthropic;
/// and doing so would be a feature of its own rather than a side effect of streaming.
///
/// The text this line carried, empty when it carried none.
-public readonly record struct AnthropicStreamPart(string TextDelta)
+/// What the provider said the request carried, unknown on every line but the message start.
+public readonly record struct AnthropicStreamPart(string TextDelta, TokenUsage Usage = default)
{
///
/// The part of a line that says nothing to the user, such as an opening or closing block.
///
public static AnthropicStreamPart Nothing => new(string.Empty);
-
+
///
/// Whether this part has anything to show at all.
///
+ ///
+ /// The usage is not part of that: it is nothing to show, and whether it reaches the answer at
+ /// all is the tool calling loop's decision, which knows which round this is.
+ ///
public bool HasContent => this.TextDelta.Length > 0;
}
\ No newline at end of file
diff --git a/app/MindWork AI Studio/Provider/Anthropic/AnthropicToolCallingAdapter.cs b/app/MindWork AI Studio/Provider/Anthropic/AnthropicToolCallingAdapter.cs
index cee4d160..851a49f8 100644
--- a/app/MindWork AI Studio/Provider/Anthropic/AnthropicToolCallingAdapter.cs
+++ b/app/MindWork AI Studio/Provider/Anthropic/AnthropicToolCallingAdapter.cs
@@ -57,14 +57,16 @@ public sealed class AnthropicToolCallingAdapter(Model chatModel, IList
+/// What Anthropic reports a messages call carried, as it opens the stream.
+///
+///
+/// The input arrives in up to three parts, and only their sum is what the request carried: the
+/// input tokens are just those after the last cache breakpoint, the other two are what was written
+/// to and read from the cache before it. Read on 2026-09-24 at
+/// https://platform.claude.com/docs/en/build-with-claude/prompt-caching.
+///
+/// A missing cache part means that nothing was cached, not that its size is unknown: the API
+/// caches only for a request which asks for it with cache_control, which AI Studio never does on
+/// its own -- somebody could, though, through the additional API parameters. A missing input part
+/// is different, and without it the block states nothing.
+///
+/// The output tokens are left unread on purpose, for the reason given at TokenUsage: they include
+/// the model's thinking, which no later request carries.
+///
+public sealed record AnthropicUsage
+{
+ ///
+ /// What the request carried after its last cache breakpoint, which is all of it without caching.
+ ///
+ public int? InputTokens { get; init; }
+
+ ///
+ /// What the request wrote to the cache.
+ ///
+ public int? CacheCreationInputTokens { get; init; }
+
+ ///
+ /// What the request read from the cache.
+ ///
+ public int? CacheReadInputTokens { get; init; }
+
+ ///
+ /// States what this block reports, as far as it can be believed.
+ ///
+ ///
+ /// The one way from the wire to a usage, shared by the plain text path and the tool calling
+ /// path, so that what counts as believable is decided in a single place.
+ ///
+ /// The usage, or TokenUsage.UNKNOWN when the block states nothing usable.
+ public TokenUsage ToTokenUsage() => this.InputTokens is { } inputTokens
+ ? TokenUsage.OfReported(inputTokens + (this.CacheCreationInputTokens ?? 0) + (this.CacheReadInputTokens ?? 0))
+ : TokenUsage.UNKNOWN;
+}
\ No newline at end of file
diff --git a/app/MindWork AI Studio/Provider/Anthropic/ResponseStreamLine.cs b/app/MindWork AI Studio/Provider/Anthropic/ResponseStreamLine.cs
index 195f164c..a416b318 100644
--- a/app/MindWork AI Studio/Provider/Anthropic/ResponseStreamLine.cs
+++ b/app/MindWork AI Studio/Provider/Anthropic/ResponseStreamLine.cs
@@ -9,12 +9,38 @@ namespace AIStudio.Provider.Anthropic;
/// The delta of the response line.
public readonly record struct ResponseStreamLine(string Type, int Index, Delta Delta) : IResponseStreamLine
{
+ ///
+ /// The message the stream opens with, on the message start event only.
+ ///
+ ///
+ /// Not a positional parameter, because nobody but the serializer ever builds this line with
+ /// one. Only the opening event carries a message, which makes it the only line with a usage.
+ ///
+ public AnthropicStreamMessage? Message { get; init; }
+
///
public bool ContainsContent() => this != default && !string.IsNullOrWhiteSpace(this.Delta.Text);
///
public ContentStreamChunk GetContent() => new(this.Delta.Text, []);
+ ///
+ ///
+ /// Read off the message start event, the first line of the stream, and never off the message
+ /// delta at its end. That one carries a usage as well, but a cumulative one: once the model
+ /// used a server tool, it holds what the tool fed back into the same request. The example in
+ /// the streaming documentation, read on 2026-09-24 at
+ /// https://platform.claude.com/docs/en/build-with-claude/streaming, shows 2,679 input tokens at
+ /// the start of a message with a web search and 10,682 at its end. No later request carries
+ /// those search results; the start states exactly what this one carried.
+ ///
+ /// The number arriving before the answer is no problem, because it describes the request, not
+ /// the answer. A stream which breaks off afterward leaves the answer with whatever arrived up
+ /// to then, nothing at all included, and the next request carries exactly that -- which is
+ /// what the answer's text is counted as.
+ ///
+ public TokenUsage GetUsage() => this.Message?.Usage?.ToTokenUsage() ?? TokenUsage.UNKNOWN;
+
#region Implementation of IAnnotationStreamLine
//
diff --git a/app/MindWork AI Studio/Provider/BaseProvider.cs b/app/MindWork AI Studio/Provider/BaseProvider.cs
index 98a34c74..63465592 100644
--- a/app/MindWork AI Studio/Provider/BaseProvider.cs
+++ b/app/MindWork AI Studio/Provider/BaseProvider.cs
@@ -1157,17 +1157,44 @@ public abstract class BaseProvider : IProvider, ISecretId
// Check if annotations are supported:
var annotationSupported = typeof(TAnnotation) != typeof(NoResponsesAnnotationStreamLine) && typeof(TAnnotation) != typeof(NoChatCompletionAnnotationStreamLine);
+ var isCompleted = false;
await foreach (var serverSentEvent in this.ReadServerSentEventsAsync(providerName, "responses call", requestBuilder, token))
{
- // Check if the line is the end of the stream. This one is read off the raw line
- // rather than off a payload, because it has none:
+ // Check if the line announces the end of the stream. This one is read off the raw
+ // line rather than off a payload, because it has none:
if (serverSentEvent.Line.StartsWith("event: response.completed", StringComparison.InvariantCulture))
- yield break;
+ {
+ isCompleted = true;
+ continue;
+ }
// Skip lines without a payload:
if (serverSentEvent.Data.Length is 0)
continue;
+ //
+ // The payload after the announcement is the whole response, and the only line which
+ // states what the request cost. The stream ends here whether that can be read or not,
+ // which keeps the end independent of how a gateway orders the fields of the payload.
+ //
+ if (isCompleted)
+ {
+ var usage = TokenUsage.UNKNOWN;
+ try
+ {
+ usage = JsonSerializer.Deserialize(serverSentEvent.Data, JSON_SERIALIZER_OPTIONS)?.GetUsage() ?? TokenUsage.UNKNOWN;
+ }
+ catch
+ {
+ // Invalid JSON data states nothing, and the answer is complete either way.
+ }
+
+ if (usage.IsKnown)
+ yield return new(string.Empty, [], Usage: usage);
+
+ yield break;
+ }
+
//
// Find delta lines:
//
diff --git a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionStreamPart.cs b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionStreamPart.cs
index c13b72aa..7b6f1ba8 100644
--- a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionStreamPart.cs
+++ b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionStreamPart.cs
@@ -17,8 +17,8 @@ public readonly record struct ChatCompletionStreamPart(string TextDelta, IList
///
- /// The usage is not part of that: it is nothing to show, and whether it is passed on at all is
- /// the adapter's decision, which knows which round this is.
+ /// The usage is not part of that: it is nothing to show, and whether it reaches the answer at
+ /// all is the tool calling loop's decision, which knows which round this is.
///
public bool HasContent => this.TextDelta.Length > 0 || this.Sources.Count > 0;
}
\ No newline at end of file
diff --git a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionToolCallingAdapter.cs b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionToolCallingAdapter.cs
index 2d425622..cbf36542 100644
--- a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionToolCallingAdapter.cs
+++ b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionToolCallingAdapter.cs
@@ -56,27 +56,17 @@ public sealed class ChatCompletionToolCallingAdapter(
ParallelToolCalls = requestDtoBase.Tools is null || !mayAskForSequentialToolCalls ? null : false,
};
- //
- // Only the first round passes on what its request cost. Its prompt is the conversation up
- // to the question, which is exactly what the next question will be sent after. Every later
- // round carries the tool calls and their results on top, and none of that is sent again
- // once the answer stands -- a report of such a round would count a chat far larger than
- // the one the next request carries. What the answer adds, all rounds of text together, is
- // counted from its text afterwards, cf. ReportedHistory.
- //
- var passesOnUsage = this.internalMessages.Count is 0;
-
//
// The text goes out while it is being written; the tool calls are put back together
- // behind it, fragment by fragment.
+ // behind it, fragment by fragment. The usage goes out with every round: which of them
+ // describes the conversation is the loop's decision, which knows which round this is.
//
var accumulator = new ChatCompletionToolCallAccumulator(readSources);
await foreach (var serverSentEvent in streamRequestAsync(requestDto, token))
{
var part = accumulator.Process(serverSentEvent);
- var usage = passesOnUsage ? part.Usage : TokenUsage.UNKNOWN;
- if (part.HasContent || usage.IsKnown)
- yield return ToolCallingStreamEvent.TextDelta(new ContentStreamChunk(part.TextDelta, part.Sources, Usage: usage));
+ if (part.HasContent || part.Usage.IsKnown)
+ yield return ToolCallingStreamEvent.TextDelta(new ContentStreamChunk(part.TextDelta, part.Sources, Usage: part.Usage));
}
var message = accumulator.Build();
diff --git a/app/MindWork AI Studio/Provider/OpenAI/ResponsesCompletedStreamLine.cs b/app/MindWork AI Studio/Provider/OpenAI/ResponsesCompletedStreamLine.cs
index 1591d562..d60059f6 100644
--- a/app/MindWork AI Studio/Provider/OpenAI/ResponsesCompletedStreamLine.cs
+++ b/app/MindWork AI Studio/Provider/OpenAI/ResponsesCompletedStreamLine.cs
@@ -10,4 +10,15 @@ namespace AIStudio.Provider.OpenAI;
///
/// The type of the stream event.
/// The response as a non-streamed call would have returned it.
-public sealed record ResponsesCompletedStreamLine(string Type, ResponsesResponse? Response);
\ No newline at end of file
+public sealed record ResponsesCompletedStreamLine(string Type, ResponsesResponse? Response)
+{
+ ///
+ /// States what the request of this call carried, as far as it can be believed.
+ ///
+ ///
+ /// The one way from the wire to a usage, shared by the plain text path and the tool calling
+ /// path, so that what counts as believable is decided in a single place.
+ ///
+ /// The usage, or TokenUsage.UNKNOWN when the line states nothing usable.
+ public TokenUsage GetUsage() => this.Response?.GetUsage() ?? TokenUsage.UNKNOWN;
+}
\ No newline at end of file
diff --git a/app/MindWork AI Studio/Provider/OpenAI/ResponsesResponse.cs b/app/MindWork AI Studio/Provider/OpenAI/ResponsesResponse.cs
index 285bca00..91f10628 100644
--- a/app/MindWork AI Studio/Provider/OpenAI/ResponsesResponse.cs
+++ b/app/MindWork AI Studio/Provider/OpenAI/ResponsesResponse.cs
@@ -7,6 +7,16 @@ namespace AIStudio.Provider.OpenAI;
///
public sealed record ResponsesResponse
{
+ ///
+ /// The output items after which the usage still describes the request as it was sent.
+ ///
+ ///
+ /// A list of the items which are known to leave the input alone, rather than one of those which
+ /// do not: a hosted tool OpenAI adds later would otherwise inflate the number without anybody
+ /// noticing.
+ ///
+ private static readonly HashSet OUTPUT_ITEMS_LEAVING_THE_INPUT_ALONE = ["message", "reasoning", "function_call"];
+
public string Id { get; init; } = string.Empty;
public string Model { get; init; } = string.Empty;
@@ -15,6 +25,30 @@ public sealed record ResponsesResponse
public IList Output { get; init; } = [];
+ ///
+ /// What OpenAI says the response cost. Only the completed response carries it.
+ ///
+ public ResponsesUsage? Usage { get; init; }
+
+ ///
+ /// States what the request of this response carried, as far as it can be believed.
+ ///
+ ///
+ /// Only for a response which ran no hosted tool. When OpenAI runs one, such as its web search,
+ /// what the tool found is charged as input tokens of the same response, cf. the pricing read on
+ /// 2026-09-24 at https://developers.openai.com/api/docs/pricing. No later request carries what
+ /// the tool found, so the number would describe a conversation larger than the one there is --
+ /// the same reason why the tool calling loop keeps only the usage of its first round.
+ ///
+ /// A response put back together from its items, for a gateway which never sent the completed
+ /// event, has no usage. Nor is one read off a response which ended as incomplete, because it
+ /// ran out of output tokens: that is rare enough for the estimate to cover it.
+ ///
+ /// The usage, or TokenUsage.UNKNOWN when the response states nothing usable.
+ public TokenUsage GetUsage() => this.Output.All(x => OUTPUT_ITEMS_LEAVING_THE_INPUT_ALONE.Contains(ReadString(x, "type")))
+ ? this.Usage?.ToTokenUsage() ?? TokenUsage.UNKNOWN
+ : TokenUsage.UNKNOWN;
+
public IReadOnlyList GetFunctionCalls() => this.Output
.Where(x => ReadString(x, "type").Equals("function_call", StringComparison.Ordinal))
.Select(x => new ResponsesFunctionCallItem
diff --git a/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamAccumulator.cs b/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamAccumulator.cs
index 19070c82..19463e1c 100644
--- a/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamAccumulator.cs
+++ b/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamAccumulator.cs
@@ -27,7 +27,7 @@ public sealed class ResponsesStreamAccumulator
/// Takes the next event of the stream and returns what it has to show.
///
/// The event to read.
- /// The text and sources of this event, both empty when it carried neither.
+ /// The text and sources of this event, both empty when it carried neither, and the usage of the completed event.
public ResponsesStreamPart Process(ServerSentEvent serverSentEvent)
{
if (serverSentEvent.Data.Length is 0)
@@ -61,8 +61,15 @@ public sealed class ResponsesStreamAccumulator
switch (eventType)
{
case EVENT_COMPLETED:
- this.completedResponse = TryDeserialize(serverSentEvent.Data)?.Response ?? this.completedResponse;
- return ResponsesStreamPart.Nothing;
+ var completedLine = TryDeserialize(serverSentEvent.Data);
+ this.completedResponse = completedLine?.Response ?? this.completedResponse;
+
+ //
+ // What the request carried, read the same way as on the plain text path and with
+ // the same exception, a response which ran a hosted tool, cf. ResponsesResponse.
+ //
+ var usage = completedLine?.GetUsage() ?? TokenUsage.UNKNOWN;
+ return usage.IsKnown ? new ResponsesStreamPart(string.Empty, [], usage) : ResponsesStreamPart.Nothing;
case EVENT_TEXT_DELTA:
var deltaLine = TryDeserialize(serverSentEvent.Data);
diff --git a/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamPart.cs b/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamPart.cs
index fc40da97..936efc57 100644
--- a/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamPart.cs
+++ b/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamPart.cs
@@ -5,15 +5,20 @@ namespace AIStudio.Provider.OpenAI;
///
/// The text this line carried, empty when it carried none.
/// The sources this line announced, empty when it announced none.
-public readonly record struct ResponsesStreamPart(string TextDelta, IList Sources)
+/// What the provider said the request cost, unknown on every line but the completed event.
+public readonly record struct ResponsesStreamPart(string TextDelta, IList Sources, TokenUsage Usage = default)
{
///
/// The part of a line which says nothing to the user, such as a bookkeeping event.
///
public static ResponsesStreamPart Nothing => new(string.Empty, []);
-
+
///
/// Whether this part has anything to show at all.
///
+ ///
+ /// The usage is not part of that: it is nothing to show, and whether it reaches the answer at
+ /// all is the tool calling loop's decision, which knows which round this is.
+ ///
public bool HasContent => this.TextDelta.Length > 0 || this.Sources.Count > 0;
}
\ No newline at end of file
diff --git a/app/MindWork AI Studio/Provider/OpenAI/ResponsesToolCallingAdapter.cs b/app/MindWork AI Studio/Provider/OpenAI/ResponsesToolCallingAdapter.cs
index bdd16ff7..5409f775 100644
--- a/app/MindWork AI Studio/Provider/OpenAI/ResponsesToolCallingAdapter.cs
+++ b/app/MindWork AI Studio/Provider/OpenAI/ResponsesToolCallingAdapter.cs
@@ -59,14 +59,16 @@ public sealed class ResponsesToolCallingAdapter(Model chatModel, IList