diff --git a/app/MindWork AI Studio/Assistants/I18N/allTexts.lua b/app/MindWork AI Studio/Assistants/I18N/allTexts.lua index d8c22f4fd..742111551 100644 --- a/app/MindWork AI Studio/Assistants/I18N/allTexts.lua +++ b/app/MindWork AI Studio/Assistants/I18N/allTexts.lua @@ -7978,12 +7978,18 @@ UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2093355991"] = "Removes -- 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. UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2544592344"] = "Failed to export this message, because the file format '{0}' is unknown." -- 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} UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2814713106"] = "Save as {0}" diff --git a/app/MindWork AI Studio/Chat/ContentBlockComponent.razor b/app/MindWork AI Studio/Chat/ContentBlockComponent.razor index 9f4c91bd3..3b5d5a38d 100644 --- a/app/MindWork AI Studio/Chat/ContentBlockComponent.razor +++ b/app/MindWork AI Studio/Chat/ContentBlockComponent.razor @@ -140,6 +140,12 @@ { if (this.Content.IsStreaming) { + @if (this.ShowsThinkingStatus) + { + + @T("The model is thinking...") + + } } @@ -225,6 +231,12 @@ if (textContent.InitialRemoteWait) { + @if (!textContent.ToolRuntimeStatus.IsRunning) + { + + @T("Processing the prompt...") + + } diff --git a/app/MindWork AI Studio/Chat/ContentBlockComponent.razor.cs b/app/MindWork AI Studio/Chat/ContentBlockComponent.razor.cs index 10a1aa641..bfa46ec67 100644 --- a/app/MindWork AI Studio/Chat/ContentBlockComponent.razor.cs +++ b/app/MindWork AI Studio/Chat/ContentBlockComponent.razor.cs @@ -217,6 +217,14 @@ public partial class ContentBlockComponent : MSGComponentBase /// private bool GetsAIGeneratedContentDisclosure => this.Role is ChatRole.AI && this.AddsAIGeneratedContentDisclosure; + /// + /// Whether this block tells the user above the progress bar that the model is thinking. + /// + /// + /// Not while a tool runs: the status of the tools tells what happens then. + /// + private bool ShowsThinkingStatus => this.Content is ContentText { IsThinking: true, ToolRuntimeStatus.IsRunning: false }; + /// /// The files this block holds, tables, code blocks, and formulas, so that the export menu can offer each of them. /// @@ -449,6 +457,7 @@ public partial class ContentBlockComponent : MSGComponentBase hash.Add(text.ToolInvocations.Count); hash.Add(text.Presentation?.Kind); hash.Add(text.Presentation?.GetDataHashCode() ?? 0); + hash.Add(text.IsThinking); hash.Add(text.ToolRuntimeStatus.IsRunning); hash.Add(text.ToolRuntimeStatus.Message); hash.Add(this.showToolTrace); diff --git a/app/MindWork AI Studio/Chat/ContentText.cs b/app/MindWork AI Studio/Chat/ContentText.cs index d4f31fb2f..64940861e 100644 --- a/app/MindWork AI Studio/Chat/ContentText.cs +++ b/app/MindWork AI Studio/Chat/ContentText.cs @@ -33,6 +33,16 @@ public sealed class ContentText : IContent /// private static readonly TimeSpan MIN_TIME = TimeSpan.FromSeconds(3); + /// + /// Whether the provider says that the model reasons, from a chunk which said so until the first text after it. + /// + private bool isReasoning; + + /// + /// Whether the text holds anything to read besides a think block, see ApplyStreamChunk. + /// + private bool hasReadableText; + #region Implementation of IContent /// @@ -43,6 +53,18 @@ public sealed class ContentText : IContent [JsonIgnore] public bool IsStreaming { get; set; } + /// + /// 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. + /// + /// + /// 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. + /// + [JsonIgnore] + public bool IsThinking => this.IsStreaming && (this.isReasoning || !this.hasReadableText); + /// /// 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. @@ -387,7 +409,18 @@ public sealed class ContentText : IContent this.InitialRemoteWait = false; 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; + + // 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) this.EndedWithoutAnswer = true; diff --git a/app/MindWork AI Studio/Chat/StringExtension.cs b/app/MindWork AI Studio/Chat/StringExtension.cs index 309c33165..59c5045be 100644 --- a/app/MindWork AI Studio/Chat/StringExtension.cs +++ b/app/MindWork AI Studio/Chat/StringExtension.cs @@ -2,22 +2,26 @@ public static class StringExtensions { + private const string THINK_OPEN_TAG = ""; + private const string THINK_CLOSE_TAG = ""; + /// The text. extension(string text) { - public string RemoveThinkTags() - { - const string OPEN_TAG = ""; - const string CLOSE_TAG = ""; - if (string.IsNullOrWhiteSpace(text) || !text.StartsWith(OPEN_TAG, StringComparison.Ordinal)) - return text; - - var endIndex = text.IndexOf(CLOSE_TAG, StringComparison.Ordinal); - if (endIndex == -1) - return string.Empty; - - return text[(endIndex + CLOSE_TAG.Length)..]; - } + /// + /// The text without the think block which a model may open its answer with. + /// + /// The text as it was without such a block, nothing while the block is still open, and otherwise what follows the block. + public string RemoveThinkTags() => AnswerStart(text) is { } start ? text[start..] : string.Empty; + + /// + /// Whether the text holds anything to read besides the think block which a model may open its answer with. + /// + /// + /// 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. + /// + public bool HasTextBeyondThinkTags => AnswerStart(text) is { } start && !text.AsSpan(start).IsWhiteSpace(); /// /// 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(), "..."); } } + + /// + /// Where the answer starts in a text which a model may open with a think block. + /// + /// The text. + /// 0 without a think block, the position right behind the block otherwise, and null while the block is still open. + 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; + } } \ No newline at end of file diff --git a/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua b/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua index ebaa34684..925c6af6c 100644 --- a/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua +++ b/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua @@ -7980,12 +7980,18 @@ UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2093355991"] = "Entfern -- Regenerate Message 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. UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2544592344"] = "Diese Nachricht konnte nicht exportiert werden, da das Dateiformat „{0}“ unbekannt ist." -- Arguments 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} UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2814713106"] = "Als {0} speichern" diff --git a/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua b/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua index 3d8c0c6fb..a39990110 100644 --- a/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua +++ b/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua @@ -7980,12 +7980,18 @@ UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2093355991"] = "Removes -- 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. UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2544592344"] = "Failed to export this message, because the file format '{0}' is unknown." -- 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} UI_TEXT_CONTENT["AISTUDIO::CHAT::CONTENTBLOCKCOMPONENT::T2814713106"] = "Save as {0}" diff --git a/app/MindWork AI Studio/Provider/Anthropic/AnthropicContentBlockBuilder.cs b/app/MindWork AI Studio/Provider/Anthropic/AnthropicContentBlockBuilder.cs index f047f5194..302cea6e0 100644 --- a/app/MindWork AI Studio/Provider/Anthropic/AnthropicContentBlockBuilder.cs +++ b/app/MindWork AI Studio/Provider/Anthropic/AnthropicContentBlockBuilder.cs @@ -23,7 +23,13 @@ public sealed class AnthropicContentBlockBuilder private const string DELTA_TEXT = "text_delta"; private const string DELTA_INPUT_JSON = "input_json_delta"; - private const string DELTA_THINKING = "thinking_delta"; + /// + /// The type of a delta which carries thinking of the model. + /// + /// + /// Both ways of streaming ask for it to tell that the model is thinking, cf. ResponseStreamLine. + /// + internal const string DELTA_THINKING = "thinking_delta"; private const string DELTA_SIGNATURE = "signature_delta"; private const string EMPTY_OBJECT = "{}"; diff --git a/app/MindWork AI Studio/Provider/Anthropic/AnthropicMessageStreamAccumulator.cs b/app/MindWork AI Studio/Provider/Anthropic/AnthropicMessageStreamAccumulator.cs index 95845673f..89961b54e 100644 --- a/app/MindWork AI Studio/Provider/Anthropic/AnthropicMessageStreamAccumulator.cs +++ b/app/MindWork AI Studio/Provider/Anthropic/AnthropicMessageStreamAccumulator.cs @@ -22,7 +22,7 @@ public sealed class AnthropicMessageStreamAccumulator private const string EVENT_MESSAGE_STOP = "message_stop"; private const string DELTA_TEXT = "text_delta"; - + private readonly Dictionary openBlocks = []; private readonly SortedDictionary finishedBlocks = []; private readonly Dictionary unparsableToolArguments = []; @@ -81,7 +81,7 @@ public sealed class AnthropicMessageStreamAccumulator 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: if (this.openBlocks.Remove(line.Index, out var finishedBlock)) diff --git a/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamPart.cs b/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamPart.cs index 8c6f96b27..d12b1b507 100644 --- a/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamPart.cs +++ b/app/MindWork AI Studio/Provider/Anthropic/AnthropicStreamPart.cs @@ -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. /// public bool HasContent => this.TextDelta.Length > 0; + + /// + /// Whether this line carried thinking of the model, see ContentStreamChunk.IsReasoning. + /// + /// + /// The thinking itself still does not show; only that it happens does. + /// + public bool IsReasoning { get; init; } } \ 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 98f6bf526..1ae1c0c75 100644 --- a/app/MindWork AI Studio/Provider/Anthropic/AnthropicToolCallingAdapter.cs +++ b/app/MindWork AI Studio/Provider/Anthropic/AnthropicToolCallingAdapter.cs @@ -66,8 +66,8 @@ public sealed class AnthropicToolCallingAdapter(Model chatModel, IList - public bool ContainsContent() => this != default && !string.IsNullOrWhiteSpace(this.Delta.Text); + public bool ContainsContent() => this != default && (!string.IsNullOrWhiteSpace(this.Delta.Text) || this.IsThinking); /// - public ContentStreamChunk GetContent() => new(this.Delta.Text, []); + public ContentStreamChunk GetContent() => new(this.Delta.Text ?? string.Empty, []) { IsReasoning = this.IsThinking }; + + /// + /// Whether this line carries thinking of the model, which says that it is reasoning. + /// + /// + /// 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. + /// + private bool IsThinking => this.Delta.Type is AnthropicContentBlockBuilder.DELTA_THINKING; /// /// diff --git a/app/MindWork AI Studio/Provider/BaseProvider.cs b/app/MindWork AI Studio/Provider/BaseProvider.cs index 9d5bcc73b..6ca010e64 100644 --- a/app/MindWork AI Studio/Provider/BaseProvider.cs +++ b/app/MindWork AI Studio/Provider/BaseProvider.cs @@ -1304,6 +1304,27 @@ public abstract class BaseProvider : IProvider, ISecretId // Yield the response: 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 }; + } } } diff --git a/app/MindWork AI Studio/Provider/ContentStreamChunk.cs b/app/MindWork AI Studio/Provider/ContentStreamChunk.cs index 6d75911b5..9a86782cd 100644 --- a/app/MindWork AI Studio/Provider/ContentStreamChunk.cs +++ b/app/MindWork AI Studio/Provider/ContentStreamChunk.cs @@ -24,6 +24,16 @@ public sealed record ContentStreamChunk(string Content, IList Sources, /// public IReadOnlyList Passages { get; init; } = []; + /// + /// Whether the model was reasoning when this chunk arrived. + /// + /// + /// 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. + /// + public bool IsReasoning { get; init; } + /// /// 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. diff --git a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionDelta.cs b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionDelta.cs index 7981f0375..59ea6391e 100644 --- a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionDelta.cs +++ b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionDelta.cs @@ -13,4 +13,12 @@ public sealed record ChatCompletionDelta [JsonIgnore] public string Content => ChatCompletionContent.GetText(this.RawContent) ?? string.Empty; + + /// + /// The reasoning text some providers stream next to the answer. + /// + /// + /// Read only to tell that the model is reasoning, see ContentStreamChunk.IsReasoning. + /// + public string? ReasoningContent { get; set; } } diff --git a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionDeltaStreamLine.cs b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionDeltaStreamLine.cs index 663381561..4f1f80041 100644 --- a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionDeltaStreamLine.cs +++ b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionDeltaStreamLine.cs @@ -44,7 +44,7 @@ public record ChatCompletionDeltaStreamLine(string Id, string Object, uint Creat public bool ContainsContent() => this.Choices.Count > 0; /// - 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) }; /// public TokenUsage GetUsage() => this.Usage?.ToTokenUsage() ?? TokenUsage.UNKNOWN; diff --git a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionStreamPart.cs b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionStreamPart.cs index 7b6f1ba83..200fd783f 100644 --- a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionStreamPart.cs +++ b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionStreamPart.cs @@ -21,4 +21,9 @@ public readonly record struct ChatCompletionStreamPart(string TextDelta, IList public bool HasContent => this.TextDelta.Length > 0 || this.Sources.Count > 0; + + /// + /// Whether this line carried reasoning of the model, see ContentStreamChunk.IsReasoning. + /// + public bool IsReasoning { get; init; } } \ No newline at end of file diff --git a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionToolCallAccumulator.cs b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionToolCallAccumulator.cs index 156dd9d2f..27e789afe 100644 --- a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionToolCallAccumulator.cs +++ b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionToolCallAccumulator.cs @@ -73,7 +73,8 @@ public sealed class ChatCompletionToolCallAccumulator(Func diff --git a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionToolCallingAdapter.cs b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionToolCallingAdapter.cs index b97ee6a3b..03fc8a897 100644 --- a/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionToolCallingAdapter.cs +++ b/app/MindWork AI Studio/Provider/OpenAI/ChatCompletionToolCallingAdapter.cs @@ -76,8 +76,8 @@ public sealed class ChatCompletionToolCallingAdapter( await foreach (var serverSentEvent in streamRequestAsync(requestDto, streamEnd, token)) { var part = accumulator.Process(serverSentEvent); - if (part.HasContent || part.Usage.IsKnown) - yield return ToolCallingStreamEvent.TextDelta(new ContentStreamChunk(part.TextDelta, part.Sources, Usage: part.Usage)); + if (part.HasContent || part.Usage.IsKnown || part.IsReasoning) + 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: diff --git a/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamAccumulator.cs b/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamAccumulator.cs index b642da69d..72c159606 100644 --- a/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamAccumulator.cs +++ b/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamAccumulator.cs @@ -19,7 +19,11 @@ public sealed class ResponsesStreamAccumulator 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_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 completedOutputItems = []; private ResponsesResponse? completedResponse; @@ -51,6 +55,18 @@ public sealed class ResponsesStreamAccumulator // if (eventType is EVENT_OUTPUT_ITEM_DONE && root.TryGetProperty("item", out var outputItem)) 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) { @@ -84,7 +100,11 @@ public sealed class ResponsesStreamAccumulator return ResponsesStreamPart.Nothing; 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: return ResponsesStreamPart.Nothing; } diff --git a/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamPart.cs b/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamPart.cs index 936efc57d..78a1727da 100644 --- a/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamPart.cs +++ b/app/MindWork AI Studio/Provider/OpenAI/ResponsesStreamPart.cs @@ -13,6 +13,11 @@ public readonly record struct ResponsesStreamPart(string TextDelta, IList public static ResponsesStreamPart Nothing => new(string.Empty, []); + /// + /// The part of a line which says that the model reasons, and nothing else. + /// + public static ResponsesStreamPart Reasoning => new(string.Empty, []) { IsReasoning = true }; + /// /// Whether this part has anything to show at all. /// @@ -21,4 +26,9 @@ public readonly record struct ResponsesStreamPart(string TextDelta, IList public bool HasContent => this.TextDelta.Length > 0 || this.Sources.Count > 0; + + /// + /// Whether this line says that the model reasons, see ContentStreamChunk.IsReasoning. + /// + public bool IsReasoning { get; init; } } \ 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 bb78d9983..996ba94f7 100644 --- a/app/MindWork AI Studio/Provider/OpenAI/ResponsesToolCallingAdapter.cs +++ b/app/MindWork AI Studio/Provider/OpenAI/ResponsesToolCallingAdapter.cs @@ -64,8 +64,8 @@ public sealed class ResponsesToolCallingAdapter(Model chatModel, IList b await foreach (var serverSentEvent in streamRequestAsync(request, streamEnd, token)) { var part = accumulator.Process(serverSentEvent); - if (part.HasContent || part.Usage.IsKnown) - yield return ToolCallingStreamEvent.TextDelta(new ContentStreamChunk(part.TextDelta, part.Sources, Usage: part.Usage)); + if (part.HasContent || part.Usage.IsKnown || part.IsReasoning) + 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: diff --git a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md index 7e9969bdb..0af707c28 100644 --- a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md +++ b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md @@ -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 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 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. - 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. diff --git a/app/Tests/Chat/ContentTextThinkingTests.cs b/app/Tests/Chat/ContentTextThinkingTests.cs new file mode 100644 index 000000000..41d73a715 --- /dev/null +++ b/app/Tests/Chat/ContentTextThinkingTests.cs @@ -0,0 +1,120 @@ +using AIStudio.Chat; +using AIStudio.Provider; + +namespace AIStudio.Tests.Chat; + +/// +/// Checks when an answer tells the user that the model is thinking. +/// +/// +/// 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. +/// +[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("Let me", [])); + var whileTheBlockIsOpen = answer.IsThinking; + + Apply(answer, new ContentStreamChunk(" consider this.", [])); + 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); +} \ No newline at end of file diff --git a/app/Tests/Chat/ThinkTagsTests.cs b/app/Tests/Chat/ThinkTagsTests.cs new file mode 100644 index 000000000..2588b922c --- /dev/null +++ b/app/Tests/Chat/ThinkTagsTests.cs @@ -0,0 +1,36 @@ +using AIStudio.Chat; + +namespace AIStudio.Tests.Chat; + +/// +/// Checks how the chat tells the answer of a model apart from the think block which the model may open it with. +/// +/// +/// 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. +/// +[TestFixture] +public sealed class ThinkTagsTests +{ + [TestCase("", ExpectedResult = false)] + [TestCase(" \n", ExpectedResult = false)] + [TestCase("The answer.", ExpectedResult = true)] + [TestCase("Let me consider", ExpectedResult = false, Description = "An open think block is all thinking.")] + [TestCase("Let me consider this.", ExpectedResult = false)] + [TestCase("Let me consider this.\n\n", ExpectedResult = false, Description = "The line breaks after the block are no answer yet.")] + [TestCase("Let me consider this.\n\nThe answer.", ExpectedResult = true)] + public bool TellsWhetherThereIsAnythingToRead(string text) => text.HasTextBeyondThinkTags; + + [TestCase("", ExpectedResult = "")] + [TestCase("The answer.", ExpectedResult = "The answer.")] + [TestCase("Let me consider", ExpectedResult = "")] + [TestCase("Let me consider this.\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."); + } +} \ No newline at end of file diff --git a/app/Tests/Provider/ReasoningSignalTests.cs b/app/Tests/Provider/ReasoningSignalTests.cs new file mode 100644 index 000000000..aa435ca19 --- /dev/null +++ b/app/Tests/Provider/ReasoningSignalTests.cs @@ -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; + +/// +/// Checks that the lines of a stream without tools say when the model reasons, so that the chat can tell the user. +/// +/// +/// 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. +/// +[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(data, ProviderJsonOptions.OPTIONS); + + private static ContentStreamChunk ReadChatCompletion(string data) => JsonSerializer.Deserialize(data, ProviderJsonOptions.OPTIONS)!.GetContent(); +} \ No newline at end of file diff --git a/app/Tests/Provider/ToolCalling/AnthropicMessageStreamAccumulatorTests.cs b/app/Tests/Provider/ToolCalling/AnthropicMessageStreamAccumulatorTests.cs index b05bd4a62..d97890a3e 100644 --- a/app/Tests/Provider/ToolCalling/AnthropicMessageStreamAccumulatorTests.cs +++ b/app/Tests/Provider/ToolCalling/AnthropicMessageStreamAccumulatorTests.cs @@ -63,6 +63,25 @@ public sealed class AnthropicMessageStreamAccumulatorTests 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] public void AThinkingBlockKeepsItsSignature() { diff --git a/app/Tests/Provider/ToolCalling/ChatCompletionToolCallAccumulatorTests.cs b/app/Tests/Provider/ToolCalling/ChatCompletionToolCallAccumulatorTests.cs index e08031fe8..af47ddfd3 100644 --- a/app/Tests/Provider/ToolCalling/ChatCompletionToolCallAccumulatorTests.cs +++ b/app/Tests/Provider/ToolCalling/ChatCompletionToolCallAccumulatorTests.cs @@ -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] public void AToolWhichTakesNothingGetsAnEmptyObject() { diff --git a/app/Tests/Provider/ToolCalling/ResponsesStreamAccumulatorTests.cs b/app/Tests/Provider/ToolCalling/ResponsesStreamAccumulatorTests.cs index ad6f76a1b..1d713b162 100644 --- a/app/Tests/Provider/ToolCalling/ResponsesStreamAccumulatorTests.cs +++ b/app/Tests/Provider/ToolCalling/ResponsesStreamAccumulatorTests.cs @@ -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] public void TheTextIsShownWhileItIsBeingWritten() {