Added status texts for prompt processing and reasoning to the chat (#1205)

Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
This commit is contained in:
j-erlerandThorsten Sommer authored and GitHub committed 2026-11-21 09:43:31 +01:00
1 parent 6cdb0bc551
commit 28b88580a9
29 files changed
+500 -26

No files matched your search

@@ -7978,12 +7978,18 @@ UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2093355991"] = "Removes
-- Regenerate Message -- Regenerate Message
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2308444540"] = "Regenerate Message" UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2308444540"] = "Regenerate Message"
-- Processing the prompt...
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2462832453"] = "Processing the prompt..."
-- Failed to export this message, because the file format '{0}' is unknown. -- Failed to export this message, because the file format '{0}' is unknown.
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2544592344"] = "Failed to export this message, because the file format '{0}' is unknown." UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2544592344"] = "Failed to export this message, because the file format '{0}' is unknown."
-- Arguments -- Arguments
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2738624831"] = "Arguments" UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2738624831"] = "Arguments"
-- The model is thinking...
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2807374097"] = "The model is thinking..."
-- Save as {0} -- Save as {0}
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2814713106"] = "Save as {0}" UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2814713106"] = "Save as {0}"
@@ -140,6 +140,12 @@
{ {
if (this.Content.IsStreaming) if (this.Content.IsStreaming)
{ {
@if (this.ShowsThinkingStatus)
{
<MudText Typo="Typo.body2" Class="mb-2">
@T("The model is thinking...")
</MudText>
}
<MudProgressLinear Color="Color.Primary" Indeterminate="true" Class="mb-6" /> <MudProgressLinear Color="Color.Primary" Indeterminate="true" Class="mb-6" />
} }
@@ -225,6 +231,12 @@
if (textContent.InitialRemoteWait) if (textContent.InitialRemoteWait)
{ {
@if (!textContent.ToolRuntimeStatus.IsRunning)
{
<MudText Typo="Typo.body2" Class="mb-2">
@T("Processing the prompt...")
</MudText>
}
<MudSkeleton Width="30%" Height="42px;"/> <MudSkeleton Width="30%" Height="42px;"/>
<MudSkeleton Width="80%"/> <MudSkeleton Width="80%"/>
<MudSkeleton Width="100%"/> <MudSkeleton Width="100%"/>
@@ -217,6 +217,14 @@ public partial class ContentBlockComponent : MSGComponentBase
/// </summary> /// </summary>
private bool GetsAIGeneratedContentDisclosure => this.Role is ChatRole.AI && this.AddsAIGeneratedContentDisclosure; private bool GetsAIGeneratedContentDisclosure => this.Role is ChatRole.AI && this.AddsAIGeneratedContentDisclosure;
/// <summary>
/// Whether this block tells the user above the progress bar that the model is thinking.
/// </summary>
/// <remarks>
/// Not while a tool runs: the status of the tools tells what happens then.
/// </remarks>
private bool ShowsThinkingStatus => this.Content is ContentText { IsThinking: true, ToolRuntimeStatus.IsRunning: false };
/// <summary> /// <summary>
/// The files this block holds, tables, code blocks, and formulas, so that the export menu can offer each of them. /// The files this block holds, tables, code blocks, and formulas, so that the export menu can offer each of them.
/// </summary> /// </summary>
@@ -449,6 +457,7 @@ public partial class ContentBlockComponent : MSGComponentBase
hash.Add(text.ToolInvocations.Count); hash.Add(text.ToolInvocations.Count);
hash.Add(text.Presentation?.Kind); hash.Add(text.Presentation?.Kind);
hash.Add(text.Presentation?.GetDataHashCode() ?? 0); hash.Add(text.Presentation?.GetDataHashCode() ?? 0);
hash.Add(text.IsThinking);
hash.Add(text.ToolRuntimeStatus.IsRunning); hash.Add(text.ToolRuntimeStatus.IsRunning);
hash.Add(text.ToolRuntimeStatus.Message); hash.Add(text.ToolRuntimeStatus.Message);
hash.Add(this.showToolTrace); hash.Add(this.showToolTrace);
@@ -33,6 +33,16 @@ public sealed class ContentText : IContent
/// </summary> /// </summary>
private static readonly TimeSpan MIN_TIME = TimeSpan.FromSeconds(3); private static readonly TimeSpan MIN_TIME = TimeSpan.FromSeconds(3);
/// <summary>
/// Whether the provider says that the model reasons, from a chunk which said so until the first text after it.
/// </summary>
private bool isReasoning;
/// <summary>
/// Whether the text holds anything to read besides a think block, see ApplyStreamChunk.
/// </summary>
private bool hasReadableText;
#region Implementation of IContent #region Implementation of IContent
/// <inheritdoc /> /// <inheritdoc />
@@ -43,6 +53,18 @@ public sealed class ContentText : IContent
[JsonIgnore] [JsonIgnore]
public bool IsStreaming { get; set; } public bool IsStreaming { get; set; }
/// <summary>
/// Whether the model thinks right now, as far as the user can tell: its provider says that it reasons, or
/// nothing has arrived yet which the user may read, as while a model reasons inside think tags.
/// </summary>
/// <remarks>
/// Only while the answer streams, so that it holds however the stream ends: in this class, in the job service of
/// the chat, or without any stream at all. Both parts are decided once per chunk, see ApplyStreamChunk, and not
/// with every render of the answer.
/// </remarks>
[JsonIgnore]
public bool IsThinking => this.IsStreaming && (this.isReasoning || !this.hasReadableText);
/// <summary> /// <summary>
/// Tells whether the model ended its turn without an answer, so that the text holds a notice of the app rather /// Tells whether the model ended its turn without an answer, so that the text holds a notice of the app rather
/// than a word of the model, see ContentStreamChunk.EndsWithoutAnswer. /// than a word of the model, see ContentStreamChunk.EndsWithoutAnswer.
@@ -387,7 +409,18 @@ public sealed class ContentText : IContent
this.InitialRemoteWait = false; this.InitialRemoteWait = false;
this.IsStreaming = true; this.IsStreaming = true;
// Reasoning lasts until the first text after it:
if (chunk.IsReasoning)
this.isReasoning = true;
else if (!string.IsNullOrEmpty(chunk.Content))
this.isReasoning = false;
this.Text += chunk; this.Text += chunk;
// The text only grows while it streams, so once there is something to read, there always is:
if (!this.hasReadableText)
this.hasReadableText = this.Text.HasTextBeyondThinkTags;
if (chunk.EndsWithoutAnswer) if (chunk.EndsWithoutAnswer)
this.EndedWithoutAnswer = true; this.EndedWithoutAnswer = true;
+30 -12
View File
@@ -2,22 +2,26 @@
public static class StringExtensions public static class StringExtensions
{ {
private const string THINK_OPEN_TAG = "<think>";
private const string THINK_CLOSE_TAG = "</think>";
/// <param name="text">The text.</param> /// <param name="text">The text.</param>
extension(string text) extension(string text)
{ {
public string RemoveThinkTags() /// <summary>
{ /// The text without the think block which a model may open its answer with.
const string OPEN_TAG = "<think>"; /// </summary>
const string CLOSE_TAG = "</think>"; /// <returns>The text as it was without such a block, nothing while the block is still open, and otherwise what follows the block.</returns>
if (string.IsNullOrWhiteSpace(text) || !text.StartsWith(OPEN_TAG, StringComparison.Ordinal)) public string RemoveThinkTags() => AnswerStart(text) is { } start ? text[start..] : string.Empty;
return text;
var endIndex = text.IndexOf(CLOSE_TAG, StringComparison.Ordinal); /// <summary>
if (endIndex == -1) /// Whether the text holds anything to read besides the think block which a model may open its answer with.
return string.Empty; /// </summary>
/// <remarks>
return text[(endIndex + CLOSE_TAG.Length)..]; /// Tells what RemoveThinkTags would leave without copying it: the chat asks with every chunk of an answer,
} /// and a model which thinks out loud writes long texts.
/// </remarks>
public bool HasTextBeyondThinkTags => AnswerStart(text) is { } start && !text.AsSpan(start).IsWhiteSpace();
/// <summary> /// <summary>
/// Shortens a text to the given number of characters, and marks the cut with three dots. /// Shortens a text to the given number of characters, and marks the cut with three dots.
@@ -38,4 +42,18 @@ public static class StringExtensions
return string.Concat(text.AsSpan(0, end).TrimEnd(), "..."); return string.Concat(text.AsSpan(0, end).TrimEnd(), "...");
} }
} }
/// <summary>
/// Where the answer starts in a text which a model may open with a think block.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>0 without a think block, the position right behind the block otherwise, and null while the block is still open.</returns>
private static int? AnswerStart(string text)
{
if (string.IsNullOrWhiteSpace(text) || !text.StartsWith(THINK_OPEN_TAG, StringComparison.Ordinal))
return 0;
var endIndex = text.IndexOf(THINK_CLOSE_TAG, StringComparison.Ordinal);
return endIndex == -1 ? null : endIndex + THINK_CLOSE_TAG.Length;
}
} }
@@ -7980,12 +7980,18 @@ UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2093355991"] = "Entfern
-- Regenerate Message -- Regenerate Message
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2308444540"] = "Nachricht neu generieren" UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2308444540"] = "Nachricht neu generieren"
-- Processing the prompt...
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2462832453"] = "Prompt wird verarbeitet …"
-- Failed to export this message, because the file format '{0}' is unknown. -- Failed to export this message, because the file format '{0}' is unknown.
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2544592344"] = "Diese Nachricht konnte nicht exportiert werden, da das Dateiformat „{0}“ unbekannt ist." UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2544592344"] = "Diese Nachricht konnte nicht exportiert werden, da das Dateiformat „{0}“ unbekannt ist."
-- Arguments -- Arguments
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2738624831"] = "Argumente" UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2738624831"] = "Argumente"
-- The model is thinking...
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2807374097"] = "Das Modell denkt nach …"
-- Save as {0} -- Save as {0}
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2814713106"] = "Als {0} speichern" UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2814713106"] = "Als {0} speichern"
@@ -7980,12 +7980,18 @@ UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2093355991"] = "Removes
-- Regenerate Message -- Regenerate Message
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2308444540"] = "Regenerate Message" UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2308444540"] = "Regenerate Message"
-- Processing the prompt...
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2462832453"] = "Processing the prompt..."
-- Failed to export this message, because the file format '{0}' is unknown. -- Failed to export this message, because the file format '{0}' is unknown.
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2544592344"] = "Failed to export this message, because the file format '{0}' is unknown." UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2544592344"] = "Failed to export this message, because the file format '{0}' is unknown."
-- Arguments -- Arguments
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2738624831"] = "Arguments" UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2738624831"] = "Arguments"
-- The model is thinking...
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2807374097"] = "The model is thinking..."
-- Save as {0} -- Save as {0}
UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2814713106"] = "Save as {0}" UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2814713106"] = "Save as {0}"
@@ -23,7 +23,13 @@ public sealed class AnthropicContentBlockBuilder
private const string DELTA_TEXT = "text_delta"; private const string DELTA_TEXT = "text_delta";
private const string DELTA_INPUT_JSON = "input_json_delta"; private const string DELTA_INPUT_JSON = "input_json_delta";
private const string DELTA_THINKING = "thinking_delta"; /// <summary>
/// The type of a delta which carries thinking of the model.
/// </summary>
/// <remarks>
/// Both ways of streaming ask for it to tell that the model is thinking, cf. ResponseStreamLine.
/// </remarks>
internal const string DELTA_THINKING = "thinking_delta";
private const string DELTA_SIGNATURE = "signature_delta"; private const string DELTA_SIGNATURE = "signature_delta";
private const string EMPTY_OBJECT = "{}"; private const string EMPTY_OBJECT = "{}";
@@ -81,7 +81,7 @@ public sealed class AnthropicMessageStreamAccumulator
this.openBlocks[line.Index] = openBlock; this.openBlocks[line.Index] = openBlock;
} }
return new AnthropicStreamPart(openBlock.Append(line.Delta)); return new AnthropicStreamPart(openBlock.Append(line.Delta)) { IsReasoning = line.Delta.Type is AnthropicContentBlockBuilder.DELTA_THINKING };
case EVENT_BLOCK_STOP: case EVENT_BLOCK_STOP:
if (this.openBlocks.Remove(line.Index, out var finishedBlock)) if (this.openBlocks.Remove(line.Index, out var finishedBlock))
@@ -24,4 +24,12 @@ public readonly record struct AnthropicStreamPart(string TextDelta, TokenUsage U
/// all is the tool calling loop's decision, which knows which round this is. /// all is the tool calling loop's decision, which knows which round this is.
/// </remarks> /// </remarks>
public bool HasContent => this.TextDelta.Length > 0; public bool HasContent => this.TextDelta.Length > 0;
/// <summary>
/// Whether this line carried thinking of the model, see ContentStreamChunk.IsReasoning.
/// </summary>
/// <remarks>
/// The thinking itself still does not show; only that it happens does.
/// </remarks>
public bool IsReasoning { get; init; }
} }
@@ -66,8 +66,8 @@ public sealed class AnthropicToolCallingAdapter(Model chatModel, IList<IMessageB
await foreach (var serverSentEvent in streamRequestAsync(request, streamEnd, token)) await foreach (var serverSentEvent in streamRequestAsync(request, streamEnd, token))
{ {
var part = accumulator.Process(serverSentEvent); var part = accumulator.Process(serverSentEvent);
if (part.HasContent || part.Usage.IsKnown) if (part.HasContent || part.Usage.IsKnown || part.IsReasoning)
yield return ToolCallingStreamEvent.TextDelta(new ContentStreamChunk(part.TextDelta, [], Usage: part.Usage)); yield return ToolCallingStreamEvent.TextDelta(new ContentStreamChunk(part.TextDelta, [], Usage: part.Usage) { IsReasoning = part.IsReasoning });
} }
// A stream which was cut off ends the round without an outcome, cf. IToolCallingProviderAdapter.ExecuteRoundAsync: // A stream which was cut off ends the round without an outcome, cf. IToolCallingProviderAdapter.ExecuteRoundAsync:
@@ -19,10 +19,19 @@ public readonly record struct ResponseStreamLine(string Type, int Index, Delta D
public AnthropicStreamMessage? Message { get; init; } public AnthropicStreamMessage? Message { get; init; }
/// <inheritdoc /> /// <inheritdoc />
public bool ContainsContent() => this != default && !string.IsNullOrWhiteSpace(this.Delta.Text); public bool ContainsContent() => this != default && (!string.IsNullOrWhiteSpace(this.Delta.Text) || this.IsThinking);
/// <inheritdoc /> /// <inheritdoc />
public ContentStreamChunk GetContent() => new(this.Delta.Text, []); public ContentStreamChunk GetContent() => new(this.Delta.Text ?? string.Empty, []) { IsReasoning = this.IsThinking };
/// <summary>
/// Whether this line carries thinking of the model, which says that it is reasoning.
/// </summary>
/// <remarks>
/// Asks the type of the delta, as the stream with tools does, cf. AnthropicMessageStreamAccumulator. The thinking
/// itself is never read here, so the delta needs no field for it.
/// </remarks>
private bool IsThinking => this.Delta.Type is AnthropicContentBlockBuilder.DELTA_THINKING;
/// <inheritdoc /> /// <inheritdoc />
/// <remarks> /// <remarks>
@@ -1304,6 +1304,27 @@ public abstract class BaseProvider : IProvider, ISecretId
// Yield the response: // Yield the response:
yield return new(string.Empty, providerResponse.GetSources()); yield return new(string.Empty, providerResponse.GetSources());
} }
//
// Find the lines which say that the model reasons: the opening of a reasoning item,
// which is all the API tells about reasoning it keeps to itself, and the reasoning
// which does arrive as text. None of it is shown; the chunk only says that it happens.
//
else if (serverSentEvent.Data.StartsWith(
"""
{"type":"response.reasoning
""", StringComparison.InvariantCulture) ||
(serverSentEvent.Data.StartsWith(
"""
{"type":"response.output_item.added"
""", StringComparison.InvariantCulture) &&
serverSentEvent.Data.Contains(
"""
"type":"reasoning"
""", StringComparison.InvariantCulture)))
{
yield return new(string.Empty, []) { IsReasoning = true };
}
} }
} }
@@ -24,6 +24,16 @@ public sealed record ContentStreamChunk(string Content, IList<ISource> Sources,
/// </remarks> /// </remarks>
public IReadOnlyList<SourcePassage> Passages { get; init; } = []; public IReadOnlyList<SourcePassage> Passages { get; init; } = [];
/// <summary>
/// Whether the model was reasoning when this chunk arrived.
/// </summary>
/// <remarks>
/// The reasoning itself never travels with the chunk; nothing shows it. The chunk only says
/// that it happens, so that the user reads why no text arrives yet. A provider which hides
/// its reasoning inside think tags sets nothing here: that text arrives as content.
/// </remarks>
public bool IsReasoning { get; init; }
/// <summary> /// <summary>
/// Tells whether the model ended its turn without an answer, so that the content of the chunk is a notice of the /// Tells whether the model ended its turn without an answer, so that the content of the chunk is a notice of the
/// app rather than a word of the model. /// app rather than a word of the model.
@@ -13,4 +13,12 @@ public sealed record ChatCompletionDelta
[JsonIgnore] [JsonIgnore]
public string Content => ChatCompletionContent.GetText(this.RawContent) ?? string.Empty; public string Content => ChatCompletionContent.GetText(this.RawContent) ?? string.Empty;
/// <summary>
/// The reasoning text some providers stream next to the answer.
/// </summary>
/// <remarks>
/// Read only to tell that the model is reasoning, see ContentStreamChunk.IsReasoning.
/// </remarks>
public string? ReasoningContent { get; set; }
} }
@@ -44,7 +44,7 @@ public record ChatCompletionDeltaStreamLine(string Id, string Object, uint Creat
public bool ContainsContent() => this.Choices.Count > 0; public bool ContainsContent() => this.Choices.Count > 0;
/// <inheritdoc /> /// <inheritdoc />
public ContentStreamChunk GetContent() => new(this.Choices[0].Delta.Content, []); public ContentStreamChunk GetContent() => new(this.Choices[0].Delta.Content, []) { IsReasoning = !string.IsNullOrEmpty(this.Choices[0].Delta.ReasoningContent) };
/// <inheritdoc /> /// <inheritdoc />
public TokenUsage GetUsage() => this.Usage?.ToTokenUsage() ?? TokenUsage.UNKNOWN; public TokenUsage GetUsage() => this.Usage?.ToTokenUsage() ?? TokenUsage.UNKNOWN;
@@ -21,4 +21,9 @@ public readonly record struct ChatCompletionStreamPart(string TextDelta, IList<I
/// all is the tool calling loop's decision, which knows which round this is. /// all is the tool calling loop's decision, which knows which round this is.
/// </remarks> /// </remarks>
public bool HasContent => this.TextDelta.Length > 0 || this.Sources.Count > 0; public bool HasContent => this.TextDelta.Length > 0 || this.Sources.Count > 0;
/// <summary>
/// Whether this line carried reasoning of the model, see ContentStreamChunk.IsReasoning.
/// </summary>
public bool IsReasoning { get; init; }
} }
@@ -73,7 +73,8 @@ public sealed class ChatCompletionToolCallAccumulator(Func<ServerSentEvent, ILis
this.hasReadAnything = true; this.hasReadAnything = true;
if (!string.IsNullOrEmpty(delta.ReasoningContent)) var isReasoning = !string.IsNullOrEmpty(delta.ReasoningContent);
if (isReasoning)
this.reasoning.Append(delta.ReasoningContent); this.reasoning.Append(delta.ReasoningContent);
foreach (var toolCallDelta in delta.ToolCalls ?? []) foreach (var toolCallDelta in delta.ToolCalls ?? [])
@@ -86,10 +87,12 @@ public sealed class ChatCompletionToolCallAccumulator(Func<ServerSentEvent, ILis
var textDelta = delta.Content; var textDelta = delta.Content;
if (textDelta.Length is 0) if (textDelta.Length is 0)
return WithSources(string.Empty, sources, usage); return isReasoning
? new ChatCompletionStreamPart(string.Empty, sources, usage) { IsReasoning = true }
: WithSources(string.Empty, sources, usage);
this.text.Append(textDelta); this.text.Append(textDelta);
return new ChatCompletionStreamPart(textDelta, sources, usage); return new ChatCompletionStreamPart(textDelta, sources, usage) { IsReasoning = isReasoning };
} }
/// <summary> /// <summary>
@@ -76,8 +76,8 @@ public sealed class ChatCompletionToolCallingAdapter<TRequest>(
await foreach (var serverSentEvent in streamRequestAsync(requestDto, streamEnd, token)) await foreach (var serverSentEvent in streamRequestAsync(requestDto, streamEnd, token))
{ {
var part = accumulator.Process(serverSentEvent); var part = accumulator.Process(serverSentEvent);
if (part.HasContent || part.Usage.IsKnown) if (part.HasContent || part.Usage.IsKnown || part.IsReasoning)
yield return ToolCallingStreamEvent.TextDelta(new ContentStreamChunk(part.TextDelta, part.Sources, Usage: part.Usage)); yield return ToolCallingStreamEvent.TextDelta(new ContentStreamChunk(part.TextDelta, part.Sources, Usage: part.Usage) { IsReasoning = part.IsReasoning });
} }
// A stream which was cut off ends the round without an outcome, cf. IToolCallingProviderAdapter.ExecuteRoundAsync: // A stream which was cut off ends the round without an outcome, cf. IToolCallingProviderAdapter.ExecuteRoundAsync:
@@ -19,6 +19,10 @@ public sealed class ResponsesStreamAccumulator
private const string EVENT_TEXT_DELTA = "response.output_text.delta"; private const string EVENT_TEXT_DELTA = "response.output_text.delta";
private const string EVENT_ANNOTATION_ADDED = "response.output_text.annotation.added"; private const string EVENT_ANNOTATION_ADDED = "response.output_text.annotation.added";
private const string EVENT_OUTPUT_ITEM_DONE = "response.output_item.done"; private const string EVENT_OUTPUT_ITEM_DONE = "response.output_item.done";
private const string EVENT_OUTPUT_ITEM_ADDED = "response.output_item.added";
private const string EVENT_REASONING_SUMMARY_DELTA = "response.reasoning_summary_text.delta";
private const string EVENT_REASONING_DELTA = "response.reasoning_text.delta";
private const string ITEM_TYPE_REASONING = "reasoning";
private readonly List<JsonElement> completedOutputItems = []; private readonly List<JsonElement> completedOutputItems = [];
private ResponsesResponse? completedResponse; private ResponsesResponse? completedResponse;
@@ -51,6 +55,18 @@ public sealed class ResponsesStreamAccumulator
// //
if (eventType is EVENT_OUTPUT_ITEM_DONE && root.TryGetProperty("item", out var outputItem)) if (eventType is EVENT_OUTPUT_ITEM_DONE && root.TryGetProperty("item", out var outputItem))
this.completedOutputItems.Add(outputItem.Clone()); this.completedOutputItems.Add(outputItem.Clone());
//
// The API mostly keeps its reasoning to itself: all it says is that a reasoning item
// opened, and then nothing until the item is done. That opening is the signal.
//
if (eventType is EVENT_OUTPUT_ITEM_ADDED &&
root.TryGetProperty("item", out var addedItem) &&
addedItem.ValueKind is JsonValueKind.Object &&
addedItem.TryGetProperty("type", out var addedItemType) &&
addedItemType.ValueKind is JsonValueKind.String &&
addedItemType.GetString() is ITEM_TYPE_REASONING)
return ResponsesStreamPart.Reasoning;
} }
catch (JsonException) catch (JsonException)
{ {
@@ -85,6 +101,10 @@ public sealed class ResponsesStreamAccumulator
return new ResponsesStreamPart(string.Empty, annotationLine.GetSources()); return new ResponsesStreamPart(string.Empty, annotationLine.GetSources());
// Reasoning which does arrive as text, as a summary or from an open model:
case EVENT_REASONING_SUMMARY_DELTA or EVENT_REASONING_DELTA:
return ResponsesStreamPart.Reasoning;
default: default:
return ResponsesStreamPart.Nothing; return ResponsesStreamPart.Nothing;
} }
@@ -13,6 +13,11 @@ public readonly record struct ResponsesStreamPart(string TextDelta, IList<ISourc
/// </summary> /// </summary>
public static ResponsesStreamPart Nothing => new(string.Empty, []); public static ResponsesStreamPart Nothing => new(string.Empty, []);
/// <summary>
/// The part of a line which says that the model reasons, and nothing else.
/// </summary>
public static ResponsesStreamPart Reasoning => new(string.Empty, []) { IsReasoning = true };
/// <summary> /// <summary>
/// Whether this part has anything to show at all. /// Whether this part has anything to show at all.
/// </summary> /// </summary>
@@ -21,4 +26,9 @@ public readonly record struct ResponsesStreamPart(string TextDelta, IList<ISourc
/// all is the tool calling loop's decision, which knows which round this is. /// all is the tool calling loop's decision, which knows which round this is.
/// </remarks> /// </remarks>
public bool HasContent => this.TextDelta.Length > 0 || this.Sources.Count > 0; public bool HasContent => this.TextDelta.Length > 0 || this.Sources.Count > 0;
/// <summary>
/// Whether this line says that the model reasons, see ContentStreamChunk.IsReasoning.
/// </summary>
public bool IsReasoning { get; init; }
} }
@@ -64,8 +64,8 @@ public sealed class ResponsesToolCallingAdapter(Model chatModel, IList<object> b
await foreach (var serverSentEvent in streamRequestAsync(request, streamEnd, token)) await foreach (var serverSentEvent in streamRequestAsync(request, streamEnd, token))
{ {
var part = accumulator.Process(serverSentEvent); var part = accumulator.Process(serverSentEvent);
if (part.HasContent || part.Usage.IsKnown) if (part.HasContent || part.Usage.IsKnown || part.IsReasoning)
yield return ToolCallingStreamEvent.TextDelta(new ContentStreamChunk(part.TextDelta, part.Sources, Usage: part.Usage)); yield return ToolCallingStreamEvent.TextDelta(new ContentStreamChunk(part.TextDelta, part.Sources, Usage: part.Usage) { IsReasoning = part.IsReasoning });
} }
// A stream which was cut off ends the round without an outcome, cf. IToolCallingProviderAdapter.ExecuteRoundAsync: // A stream which was cut off ends the round without an outcome, cf. IToolCallingProviderAdapter.ExecuteRoundAsync:
@@ -15,6 +15,7 @@
- Improved the assistants page: you can collapse a category with a click on its heading, and AI Studio remembers it. - Improved the assistants page: you can collapse a category with a click on its heading, and AI Studio remembers it.
- Improved the assistants page: you can hide a category you do not need with the eye next to its heading. The gear next to the heading of the page shows it again. - Improved the assistants page: you can hide a category you do not need with the eye next to its heading. The gear next to the heading of the page shows it again.
- Improved the "Send to ..." menu: it no longer offers the assistants of categories you hid on the assistants page. With the gear on the assistants page, you decide what happens to the assistants of hidden and collapsed categories. - Improved the "Send to ..." menu: it no longer offers the assistants of categories you hid on the assistants page. With the gear on the assistants page, you decide what happens to the assistants of hidden and collapsed categories.
- Improved the chat while you wait for an answer: AI Studio now tells you when it is processing your prompt and when the model is thinking, instead of showing an animation alone.
- Changed the icons of AI Studio to Lucide, an open-source icon set. All icons now share one style, and each feature shows the same icon wherever you meet it. - Changed the icons of AI Studio to Lucide, an open-source icon set. All icons now share one style, and each feature shows the same icon wherever you meet it.
- Fixed assistant plugins, which all appeared under "Installed Assistants" on the assistants page. Each one now appears under its own category, such as "Business", next to the built-in assistants of that category. - Fixed assistant plugins, which all appeared under "Installed Assistants" on the assistants page. Each one now appears under its own category, such as "Business", next to the built-in assistants of that category.
- Fixed the Assistant Builder, which ignored the category you chose for your assistant. You can now also name a category of your own. - Fixed the Assistant Builder, which ignored the category you chose for your assistant. You can now also name a category of your own.
+120
View File
@@ -0,0 +1,120 @@
using AIStudio.Chat;
using AIStudio.Provider;
namespace AIStudio.Tests.Chat;
/// <summary>
/// Checks when an answer tells the user that the model is thinking.
/// </summary>
/// <remarks>
/// Some providers say that their model reasons, others send nothing to read for a while, and some models write
/// their thoughts into think tags. All of them have to end in the same status, and the status has to go however
/// the stream ends.
/// </remarks>
[TestFixture]
public sealed class ContentTextThinkingTests
{
private const string MODEL_ID = "test-model";
[Test]
public void NothingThinksBeforeTheFirstChunk()
{
var answer = new ContentText { InitialRemoteWait = true };
Assert.That(answer.IsThinking, Is.False, "Until the first chunk, the chat says that it processes the prompt.");
}
[Test]
public void ReasoningLastsUntilTheFirstText()
{
var answer = new ContentText { InitialRemoteWait = true };
Apply(answer, Reasoning());
var whileReasoning = answer.IsThinking;
Apply(answer, new ContentStreamChunk(string.Empty, []));
var afterAChunkWithoutText = answer.IsThinking;
Apply(answer, new ContentStreamChunk("The answer.", []));
var afterTheText = answer.IsThinking;
using (Assert.EnterMultipleScope())
{
Assert.That(whileReasoning, Is.True);
Assert.That(afterAChunkWithoutText, Is.True, "A chunk without text, such as one with the usage, does not end the reasoning.");
Assert.That(afterTheText, Is.False);
}
}
[Test]
public void AChunkWithoutTextLetsTheModelThink()
{
var answer = new ContentText { InitialRemoteWait = true };
Apply(answer, new ContentStreamChunk(string.Empty, []));
Assert.That(answer.IsThinking, Is.True, "A provider which does not say that its model reasons still sends nothing to read yet.");
}
[Test]
public void ThinkTagsLetTheModelThinkUntilTheAnswer()
{
var answer = new ContentText { InitialRemoteWait = true };
Apply(answer, new ContentStreamChunk("<think>Let me", []));
var whileTheBlockIsOpen = answer.IsThinking;
Apply(answer, new ContentStreamChunk(" consider this.</think>", []));
var afterTheBlock = answer.IsThinking;
Apply(answer, new ContentStreamChunk("\n\n", []));
var afterTheLineBreaks = answer.IsThinking;
Apply(answer, new ContentStreamChunk("The answer.", []));
var afterTheAnswer = answer.IsThinking;
using (Assert.EnterMultipleScope())
{
Assert.That(whileTheBlockIsOpen, Is.True);
Assert.That(afterTheBlock, Is.True, "A closed think block is no answer yet.");
Assert.That(afterTheLineBreaks, Is.True, "Neither are the line breaks after it.");
Assert.That(afterTheAnswer, Is.False);
}
}
[Test]
public void ReasoningLaterInTheAnswerShowsAgain()
{
var answer = new ContentText { InitialRemoteWait = true };
Apply(answer, new ContentStreamChunk("Let me look that up.", []));
var whileWriting = answer.IsThinking;
Apply(answer, Reasoning());
var whileReasoningAgain = answer.IsThinking;
Apply(answer, new ContentStreamChunk(" Here it is.", []));
var afterMoreText = answer.IsThinking;
using (Assert.EnterMultipleScope())
{
Assert.That(whileWriting, Is.False);
Assert.That(whileReasoningAgain, Is.True, "After a tool, the model may reason again before it goes on writing.");
Assert.That(afterMoreText, Is.False);
}
}
[Test]
public void TheEndOfTheStreamEndsTheThinking()
{
var answer = new ContentText { InitialRemoteWait = true };
Apply(answer, Reasoning());
// The job service of the chat ends a stream this way, without a word about reasoning:
answer.IsStreaming = false;
Assert.That(answer.IsThinking, Is.False);
}
private static ContentStreamChunk Reasoning() => new(string.Empty, []) { IsReasoning = true };
private static void Apply(ContentText answer, ContentStreamChunk chunk) => answer.ApplyStreamChunk(chunk, MODEL_ID, blockCount: 2);
}
+36
View File
@@ -0,0 +1,36 @@
using AIStudio.Chat;
namespace AIStudio.Tests.Chat;
/// <summary>
/// Checks how the chat tells the answer of a model apart from the think block which the model may open it with.
/// </summary>
/// <remarks>
/// The chat asks with every chunk of an answer whether there is anything to read yet, to tell the user that the
/// model is thinking until then. It must come to the same result as the text which the chat shows.
/// </remarks>
[TestFixture]
public sealed class ThinkTagsTests
{
[TestCase("", ExpectedResult = false)]
[TestCase(" \n", ExpectedResult = false)]
[TestCase("The answer.", ExpectedResult = true)]
[TestCase("<think>Let me consider", ExpectedResult = false, Description = "An open think block is all thinking.")]
[TestCase("<think>Let me consider this.</think>", ExpectedResult = false)]
[TestCase("<think>Let me consider this.</think>\n\n", ExpectedResult = false, Description = "The line breaks after the block are no answer yet.")]
[TestCase("<think>Let me consider this.</think>\n\nThe answer.", ExpectedResult = true)]
public bool TellsWhetherThereIsAnythingToRead(string text) => text.HasTextBeyondThinkTags;
[TestCase("", ExpectedResult = "")]
[TestCase("The answer.", ExpectedResult = "The answer.")]
[TestCase("<think>Let me consider", ExpectedResult = "")]
[TestCase("<think>Let me consider this.</think>\n\nThe answer.", ExpectedResult = "\n\nThe answer.")]
public string KeepsOnlyWhatFollowsTheThinkBlock(string text) => text.RemoveThinkTags();
[Test]
public void AnAnswerWithoutThinkBlockIsNotCopied()
{
const string ANSWER = "The answer.";
Assert.That(ANSWER.RemoveThinkTags(), Is.SameAs(ANSWER), "The chat removes the think tags with every render of a streamed answer.");
}
}
@@ -0,0 +1,68 @@
using System.Text.Json;
using AIStudio.Provider;
using AIStudio.Provider.OpenAI;
using AnthropicResponseStreamLine = AIStudio.Provider.Anthropic.ResponseStreamLine;
namespace AIStudio.Tests.Provider;
/// <summary>
/// Checks that the lines of a stream without tools say when the model reasons, so that the chat can tell the user.
/// </summary>
/// <remarks>
/// The stream with tools reads the same lines through its accumulators, which have tests of their own. Both have to
/// agree: whether a chat may use tools must not change what the user reads while the model thinks.
/// </remarks>
[TestFixture]
public sealed class ReasoningSignalTests
{
[Test]
public void AThinkingDeltaOfAnthropicSaysThatTheModelReasons()
{
var line = ReadAnthropic("""{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"Let me consider this."}}""");
var chunk = line.GetContent();
using (Assert.EnterMultipleScope())
{
Assert.That(line.ContainsContent(), Is.True, "The line has to reach the chat, although it carries no text.");
Assert.That(chunk.IsReasoning, Is.True);
Assert.That(chunk.Content, Is.Empty, "The thinking itself does not show.");
}
}
[Test]
public void ATextDeltaOfAnthropicIsNoReasoning()
{
var chunk = ReadAnthropic("""{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"The answer."}}""").GetContent();
using (Assert.EnterMultipleScope())
{
Assert.That(chunk.IsReasoning, Is.False);
Assert.That(chunk.Content, Is.EqualTo("The answer."));
}
}
[Test]
public void ReasoningContentOfAChatCompletionSaysThatTheModelReasons()
{
var chunk = ReadChatCompletion("""{"id":"chatcmpl-1","object":"chat.completion.chunk","created":1,"model":"deepseek-reasoner","choices":[{"index":0,"delta":{"reasoning_content":"Thinking about it."}}]}""");
using (Assert.EnterMultipleScope())
{
Assert.That(chunk.IsReasoning, Is.True);
Assert.That(chunk.Content, Is.Empty, "The reasoning itself does not show.");
}
}
[Test]
public void ContentOfAChatCompletionIsNoReasoning()
{
var chunk = ReadChatCompletion("""{"id":"chatcmpl-1","object":"chat.completion.chunk","created":1,"model":"deepseek-reasoner","choices":[{"index":0,"delta":{"content":"The answer."}}]}""");
Assert.That(chunk.IsReasoning, Is.False);
}
private static AnthropicResponseStreamLine ReadAnthropic(string data) => JsonSerializer.Deserialize<AnthropicResponseStreamLine>(data, ProviderJsonOptions.OPTIONS);
private static ContentStreamChunk ReadChatCompletion(string data) => JsonSerializer.Deserialize<ChatCompletionDeltaStreamLine>(data, ProviderJsonOptions.OPTIONS)!.GetContent();
}
@@ -63,6 +63,25 @@ public sealed class AnthropicMessageStreamAccumulatorTests
Assert.That(shown, Is.False, "What the model thinks stays between it and the next round."); Assert.That(shown, Is.False, "What the model thinks stays between it and the next round.");
} }
[Test]
public void ThinkingSaysThatTheModelReasons()
{
var accumulator = new AnthropicMessageStreamAccumulator();
var parts = Lines(
"""{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}""",
"""{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"Let me consider this."}}""",
"""{"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}""",
"""{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"The answer."}}""")
.Select(accumulator.Process)
.ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(parts[1].IsReasoning, Is.True, "A thinking delta tells the user why no text arrives yet.");
Assert.That(parts[3].IsReasoning, Is.False, "Text is the answer, not reasoning.");
}
}
[Test] [Test]
public void AThinkingBlockKeepsItsSignature() public void AThinkingBlockKeepsItsSignature()
{ {
@@ -131,6 +131,24 @@ public sealed class ChatCompletionToolCallAccumulatorTests
} }
} }
[Test]
public void ReasoningSaysThatTheModelReasons()
{
var accumulator = new ChatCompletionToolCallAccumulator();
var parts = Lines(
"""{"choices":[{"index":0,"delta":{"reasoning_content":"Thinking about it."}}]}""",
"""{"choices":[{"index":0,"delta":{"content":"The answer."}}]}""")
.Select(accumulator.Process)
.ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(parts[0].IsReasoning, Is.True, "A reasoning delta tells the user why no text arrives yet.");
Assert.That(parts[0].HasContent, Is.False, "The reasoning itself still does not show.");
Assert.That(parts[1].IsReasoning, Is.False, "Text is the answer, not reasoning.");
}
}
[Test] [Test]
public void AToolWhichTakesNothingGetsAnEmptyObject() public void AToolWhichTakesNothingGetsAnEmptyObject()
{ {
@@ -46,6 +46,28 @@ public sealed class ResponsesStreamAccumulatorTests
} }
} }
[Test]
public void AnOpeningReasoningItemSaysThatTheModelReasons()
{
var accumulator = new ResponsesStreamAccumulator();
var parts = Lines(
"""{"type":"response.output_item.added","output_index":0,"item":{"id":"rs_1","type":"reasoning","summary":[]}}""",
"""{"type":"response.reasoning_summary_text.delta","item_id":"rs_1","delta":"Weighing the options."}""",
"""{"type":"response.output_item.added","output_index":1,"item":{"id":"msg_1","type":"message","content":[]}}""",
"""{"type":"response.output_text.delta","delta":"The answer."}""")
.Select(accumulator.Process)
.ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(parts[0].IsReasoning, Is.True, "The opening of a reasoning item is all the API says about reasoning it keeps to itself.");
Assert.That(parts[1].IsReasoning, Is.True, "A summary of the reasoning says the same.");
Assert.That(parts[1].HasContent, Is.False, "The reasoning itself does not show.");
Assert.That(parts[2].IsReasoning, Is.False, "A message which opens is not reasoning.");
Assert.That(parts[3].IsReasoning, Is.False, "Text is the answer, not reasoning.");
}
}
[Test] [Test]
public void TheTextIsShownWhileItIsBeingWritten() public void TheTextIsShownWhileItIsBeingWritten()
{ {