Added settings for chat compression, with a model of its own (#1241)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-27 16:35:51 +01:00
1 parent 899139c88b
commit 1fbc1f4796
71 files changed
+3023 -797

No files matched your search

@@ -2,6 +2,9 @@
@inherits MSGComponentBase
<MudDialog DefaultFocus="DefaultFocus.FirstChild">
<TitleContent>
<DialogTitleWithChatCompressionSettings Title="@(this.MudDialog.Title ?? string.Empty)" Disabled="@this.isSummarizing" SettingsClosed="@this.ApplyChangedSettings"/>
</TitleContent>
<DialogContent>
<MudStack Spacing="3">
<MudJustifiedText Typo="Typo.body1">
@@ -19,6 +22,24 @@
@this.SummaryScope
</MudJustifiedText>
@if (this.StartsAutomatically)
{
<MudAlert Severity="Severity.Info" Dense="true">
<MudJustifiedText Typo="Typo.body2">
@TA("As chosen in the settings, AI Studio compresses a chat without asking once it grows too long. You can still cancel it here.")
</MudJustifiedText>
</MudAlert>
}
@if (!string.IsNullOrWhiteSpace(this.FallbackNotice))
{
<MudAlert Severity="Severity.Info" Dense="true">
<MudJustifiedText Typo="Typo.body2">
@this.FallbackNotice
</MudJustifiedText>
</MudAlert>
}
@if (this.Plan.PendingQuestion is not null)
{
<MudAlert Severity="Severity.Info" Dense="true">
@@ -1,6 +1,10 @@
using AIStudio.AIOperations;
using AIStudio.AIOperations.ConversationSummary;
using AIStudio.Chat;
using AIStudio.Chat.Compression;
using AIStudio.Components;
using AIStudio.Settings;
using AIStudio.Tools.PluginSystem;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
@@ -20,9 +24,15 @@ public partial class ChatCompressionDialog : MSGComponentBase
[CascadingParameter]
private IMudDialogInstance MudDialog { get; set; } = null!;
[Inject]
private ConversationSummaryOperation ConversationSummary { get; init; } = null!;
[Inject]
private ChatCompressionService ChatCompressionService { get; init; } = null!;
[Inject]
private AIOperationProviderResolver ProviderResolver { get; init; } = null!;
/// <summary>
/// The chat to compress.
/// </summary>
@@ -36,10 +46,14 @@ public partial class ChatCompressionDialog : MSGComponentBase
public ChatCompressionPlan Plan { get; set; } = null!;
/// <summary>
/// The provider which writes the summary: the one the chat would send its next message to.
/// The provider of the chat: the one it would send its next message to, and which continues with the summary.
/// </summary>
/// <remarks>
/// It writes the summary as well, unless the settings pick another model for compressing which may see the
/// chat, see ChatCompressionService.GetProviderOptions.
/// </remarks>
[Parameter]
public AIStudio.Settings.Provider ProviderSettings { get; set; } = AIStudio.Settings.Provider.NONE;
public AIStudio.Settings.Provider ChatProvider { get; set; } = AIStudio.Settings.Provider.NONE;
/// <summary>
/// Where the conversation goes on: in a new chat, which the user names here, or in the same chat.
@@ -59,6 +73,17 @@ public partial class ChatCompressionDialog : MSGComponentBase
[Parameter]
public bool StoresChatFirst { get; set; }
/// <summary>
/// Whether the summary starts right away, with the suggested name and the preselected focus, since the settings say
/// to compress without asking, see ContextWindowFullHandling.Decide.
/// </summary>
/// <remarks>
/// The dialog stays, so the user sees the progress and may cancel. When the summary fails, the dialog shows why and
/// waits for the user, as it does otherwise.
/// </remarks>
[Parameter]
public bool StartsAutomatically { get; set; }
private static readonly Dictionary<string, object?> USER_INPUT_ATTRIBUTES = new();
private readonly CancellationTokenSource cancellationTokenSource = new();
@@ -68,7 +93,9 @@ public partial class ChatCompressionDialog : MSGComponentBase
private string focus = string.Empty;
private string issue = string.Empty;
private bool isSummarizing;
private ChatCompressionProgress progress;
private ConversationSummaryProgress progress;
private ChatCompressionOptions options = ChatCompressionOptions.DEFAULT;
private AIOperationProviderChoice writer = new(AIStudio.Settings.Provider.NONE, AIOperationProviderIssue.NOT_SET, AIOperationProviderIssue.NOT_SET);
#region Overrides of ComponentBase
@@ -77,9 +104,23 @@ public partial class ChatCompressionDialog : MSGComponentBase
// Configure the spellchecking for the user input:
this.SettingsManager.InjectSpellchecking(USER_INPUT_ATTRIBUTES);
this.chatName = this.SuggestedName;
// Read once, and again only when the user changes them through the gear, see ApplyChangedSettings:
this.options = ChatCompressionOptions.Of(this.SettingsManager.ConfigurationData.ChatCompression);
this.focus = this.options.PreselectedFocus;
this.writer = this.ChatCompressionService.ChooseWriter(this.SourceChat, this.ChatProvider);
await base.OnInitializedAsync();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
// The form exists only after the first render, and CompressAsync validates it:
if (firstRender && this.StartsAutomatically)
await this.CompressAsync();
}
#endregion
private bool HasDocumentsToSummarize => this.Plan.ToSummarize.Any(block => block.Content?.FileAttachments.MayContainDocuments() is true);
@@ -87,20 +128,57 @@ public partial class ChatCompressionDialog : MSGComponentBase
private bool HasImagesToSummarize => this.Plan.ToSummarize.Any(block => block.Content?.FileAttachments.ContainsImages() is true);
private string SummaryScope => this.Plan.ToSummarize.Count is 1
? string.Format(T("'{0}' summarizes 1 message."), this.ProviderSettings.InstanceName)
: string.Format(T("'{0}' summarizes {1} messages."), this.ProviderSettings.InstanceName, this.Plan.ToSummarize.Count);
? string.Format(T("'{0}' summarizes 1 message."), this.writer.Provider.InstanceName)
: string.Format(T("'{0}' summarizes {1} messages."), this.writer.Provider.InstanceName, this.Plan.ToSummarize.Count);
/// <summary>
/// Why the model of the chat writes the summary instead of the model picked for compressing, or an empty string when it does not.
/// </summary>
/// <remarks>
/// Told from the reason the choice reports, never guessed afterward, see AIOperationProviderIssue. Without a model
/// picked for compressing, the model of the chat writes the summary as intended, and there is nothing to tell.
/// </remarks>
private string FallbackNotice => !this.writer.UsesFallback ? string.Empty : this.writer.PreferredIssue switch
{
AIOperationProviderIssue.NOT_SET => string.Empty,
AIOperationProviderIssue.MISSING => T("The model picked for compressing chats no longer exists, so the model of this chat writes the summary."),
AIOperationProviderIssue.PROHIBITED => TA("Your organization does not allow the model picked for compressing chats, so the model of this chat writes the summary."),
AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE => T("The model picked for compressing chats does not reach the minimum confidence level, so the model of this chat writes the summary."),
AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT => T("This chat holds data which the model picked for compressing chats must not see, so the model of this chat writes the summary."),
AIOperationProviderIssue.CONTEXT_WINDOW_TOO_SMALL => T("The context window of the model picked for compressing chats is too small, so the model of this chat writes the summary."),
_ => T("The model picked for compressing chats cannot write this summary, so the model of this chat writes it."),
};
private string ProgressMessage => this.progress.Step switch
{
ChatCompressionStep.SUMMARIZING when this.progress.Total > 1 => string.Format(T("The AI is summarizing part {0} of {1}..."), this.progress.Current, this.progress.Total),
ChatCompressionStep.SUMMARIZING => T("The AI is summarizing the chat..."),
ChatCompressionStep.CONDENSING => T("The summary grew too long. The AI is shortening it..."),
ConversationSummaryStep.SUMMARIZING when this.progress.Total > 1 => string.Format(T("The AI is summarizing part {0} of {1}..."), this.progress.Current, this.progress.Total),
ConversationSummaryStep.SUMMARIZING => T("The AI is summarizing the chat..."),
ConversationSummaryStep.CONDENSING => T("The summary grew too long. The AI is shortening it..."),
_ => T("AI Studio is reading the messages and their files..."),
};
private string? ValidateChatName(string? value) => string.IsNullOrWhiteSpace(value) ? TA("Please enter a chat name.") : null;
/// <summary>
/// Reads the settings again once the user closed them through the gear.
/// </summary>
/// <remarks>
/// The model which writes the summary may have changed, and so may the preselected focus. A focus the user
/// wrote stays; one which is still the preselected focus follows the settings.
/// </remarks>
private void ApplyChangedSettings()
{
var previousFocus = this.options.PreselectedFocus;
this.options = ChatCompressionOptions.Of(this.SettingsManager.ConfigurationData.ChatCompression);
if (string.IsNullOrWhiteSpace(this.focus) || this.focus == previousFocus)
this.focus = this.options.PreselectedFocus;
this.writer = this.ChatCompressionService.ChooseWriter(this.SourceChat, this.ChatProvider);
this.StateHasChanged();
}
private async Task HandleChatNameKeyDown(KeyboardEventArgs keyEvent)
{
if (keyEvent.IsPlainEnter)
@@ -118,13 +196,25 @@ public partial class ChatCompressionDialog : MSGComponentBase
this.progress = default;
await this.InvokeAsync(this.StateHasChanged);
var progressReporter = new Progress<ChatCompressionProgress>(reported =>
var progressReporter = new Progress<ConversationSummaryProgress>(reported =>
{
this.progress = reported;
this.InvokeAsync(this.StateHasChanged).Observe($"{nameof(ChatCompressionDialog)}: showing the progress of the summary");
});
var result = await this.ChatCompressionService.SummarizeAsync(this.SourceChat, this.Plan, this.ProviderSettings, this.focus, progressReporter, this.cancellationTokenSource.Token);
var request = new ConversationSummaryRequest(this.SourceChat, this.Plan, this.focus, this.options.MaxSummaryTokens, this.ChatProvider.GetModelProfile().Context, progressReporter);
// Chosen again right before running, since the settings may have changed while the dialog was open:
this.writer = this.ProviderResolver.Resolve(this.ConversationSummary, request, ConversationSummaryOperation.GetProviderSettings(this.SettingsManager), ChatCompressionService.GetProviderOptions(this.SourceChat, this.ChatProvider));
if (!this.writer.HasProvider)
{
this.issue = string.Format(TA("No model may write the summary of this chat. Please select a model with a context window of at least {0} tokens."), ConversationSummaryBudget.MIN_CONTEXT_WINDOW.ToString("N0", I18N.I.Culture));
this.isSummarizing = false;
await this.InvokeAsync(this.StateHasChanged);
return;
}
var result = await this.ConversationSummary.RunAsync(request, new AIOperationContext(this.writer.Provider), this.cancellationTokenSource.Token);
// The user canceled, and the dialog is gone already:
if (this.cancellationTokenSource.IsCancellationRequested)
@@ -1,6 +1,11 @@
@using AIStudio.Chat.Compression
@using AIStudio.Settings.DataModel
@inherits MSGComponentBase
<MudDialog>
<TitleContent>
<DialogTitleWithChatCompressionSettings Title="@(this.MudDialog.Title ?? string.Empty)" SettingsClosed="@this.ApplyChangedSettingsAsync"/>
</TitleContent>
<DialogContent>
<MudStack Spacing="3">
<MudJustifiedText Typo="Typo.body1">
@@ -39,7 +44,7 @@
</MudJustifiedText>
}
@if (this.CanCompress && this.Subject is ContextWindowFullSubject.EMBEDDED_CHAT)
@if (this.CanCompress && this.CompressionTarget is ChatCompressionTarget.SAME_CHAT)
{
<MudJustifiedText Typo="Typo.body1">
@TA("When you compress the conversation, the AI summarizes it, and the summary takes the place of the earlier messages. Your message stays in the input field, so you can send it afterward.")
@@ -63,6 +68,20 @@
@TA("You can shorten your message, remove some of its files, or select a model which takes longer texts.")
</MudJustifiedText>
}
@if (this.SettingsManager.ConfigurationData.ChatCompression.ContextWindowFullBehavior is ContextWindowFullBehavior.ASK)
{
<MudJustifiedText Typo="Typo.body2">
@if (this.Subject is ContextWindowFullSubject.ASSISTANT_REQUEST)
{
@TA("With the gear at the top, you can choose what AI Studio does in such a case from now on, e.g., send the request without asking.")
}
else
{
@TA("With the gear at the top, you can choose what AI Studio does in such a case from now on, e.g., compress automatically.")
}
</MudJustifiedText>
}
</MudStack>
</DialogContent>
<DialogActions>
@@ -1,3 +1,4 @@
using AIStudio.AIOperations.ConversationSummary;
using AIStudio.Chat;
using AIStudio.Chat.Compression;
using AIStudio.Components;
@@ -49,7 +50,7 @@ public partial class ContextWindowFullDialog : MSGComponentBase
public ContextWindowFullSubject Subject { get; set; } = ContextWindowFullSubject.CHAT;
/// <summary>
/// Whether compressing is offered, or why it would not help, see ChatCompressionService.OfferBeforeSendingAsync.
/// Whether compressing is offered when the dialog opens, or why it would not help, see ChatCompressionService.OfferBeforeSendingAsync.
/// </summary>
[Parameter]
public ChatCompressionOffer Offer { get; set; } = ChatCompressionOffer.NONE;
@@ -60,6 +61,24 @@ public partial class ContextWindowFullDialog : MSGComponentBase
[Parameter]
public bool CanSendAnyway { get; set; } = true;
/// <summary>
/// Where the conversation goes on when the user compresses, which decides the wording.
/// </summary>
[Parameter]
public ChatCompressionTarget CompressionTarget { get; set; } = ChatCompressionTarget.NEW_CHAT;
/// <summary>
/// Decides again whether compressing is offered, with the settings as they are now; null where nothing compresses.
/// </summary>
/// <remarks>
/// Called once the user closed the settings through the gear, since a model picked for compressing, a lower share,
/// or a shorter summary may change the offer.
/// </remarks>
[Parameter]
public Func<Task<ChatCompressionOffer>>? RecheckOffer { get; set; }
private ChatCompressionOffer offer = ChatCompressionOffer.NONE;
/// <summary>
/// Asks the user what to do with a message which fills the context window of the model.
/// </summary>
@@ -73,8 +92,10 @@ public partial class ContextWindowFullDialog : MSGComponentBase
/// <param name="subject">What is about to be sent.</param>
/// <param name="offer">Whether compressing is offered, or why it would not help; NONE where nothing compresses.</param>
/// <param name="canSendAnyway">Whether the user may send the message anyway, e.g., not where the chat refuses a message which no longer fits.</param>
/// <param name="compressionTarget">Where the conversation goes on when the user compresses.</param>
/// <param name="recheckOffer">Decides again whether compressing is offered, once the user changed the settings; null where nothing compresses.</param>
/// <returns>What the user decided; CANCEL when the dialog was closed.</returns>
public static async Task<ContextWindowFullDecision> ShowAsync(IDialogService dialogService, ConversationTokens tokens, ContextWindowFullSubject subject, ChatCompressionOffer offer, bool canSendAnyway = true)
public static async Task<ContextWindowFullDecision> ShowAsync(IDialogService dialogService, ConversationTokens tokens, ContextWindowFullSubject subject, ChatCompressionOffer offer, bool canSendAnyway = true, ChatCompressionTarget compressionTarget = ChatCompressionTarget.NEW_CHAT, Func<Task<ChatCompressionOffer>>? recheckOffer = null)
{
var isWindowExceeded = tokens.FillShare >= 1d;
var culture = I18N.I.Culture;
@@ -86,6 +107,8 @@ public partial class ContextWindowFullDialog : MSGComponentBase
{ x => x.Subject, subject },
{ x => x.Offer, offer },
{ x => x.CanSendAnyway, canSendAnyway },
{ x => x.CompressionTarget, compressionTarget },
{ x => x.RecheckOffer, recheckOffer },
};
var title = subject is ContextWindowFullSubject.ASSISTANT_REQUEST
@@ -99,10 +122,20 @@ public partial class ContextWindowFullDialog : MSGComponentBase
return decision;
}
#region Overrides of ComponentBase
protected override async Task OnInitializedAsync()
{
this.offer = this.Offer;
await base.OnInitializedAsync();
}
#endregion
/// <summary>
/// Whether the dialog offers to compress, see Offer.
/// </summary>
private bool CanCompress => this.Offer is ChatCompressionOffer.OFFERED;
private bool CanCompress => this.offer is ChatCompressionOffer.OFFERED;
/// <summary>
/// Why the dialog does not offer to compress, where the place compresses but it would not help; null otherwise.
@@ -111,16 +144,28 @@ public partial class ContextWindowFullDialog : MSGComponentBase
/// The user guide recommends compressing a long chat, so a notice which leaves it out says why. In the chat of an
/// assistant, the instructions of the assistant stay as well, and they are often the larger part.
/// </remarks>
private string? CompressionIssue => this.Offer switch
private string? CompressionIssue => this.offer switch
{
ChatCompressionOffer.WINDOW_TOO_SMALL => string.Format(T("Compressing is not possible with the selected model, since it needs a context window of at least {0} tokens."), ChatCompressionService.MIN_CONTEXT_WINDOW.ToString("N0", I18N.I.Culture)),
ChatCompressionOffer.WINDOW_TOO_SMALL => string.Format(TA("Compressing is not possible, since it needs a model with a context window of at least {0} tokens. With the gear at the top, you can choose such a model for compressing."), ConversationSummaryBudget.MIN_CONTEXT_WINDOW.ToString("N0", I18N.I.Culture)),
ChatCompressionOffer.MESSAGE_TOO_LONG => TA("Compressing would not help, since your message alone nearly fills the context window of the model."),
ChatCompressionOffer.NOTHING_TO_SUMMARIZE => TA("Compressing would not help yet, since there is nothing to summarize before your last message and the last answer of the AI."),
ChatCompressionOffer.KEEPS_TOO_MUCH when this.Subject is ContextWindowFullSubject.EMBEDDED_CHAT => TA("Compressing would not help, since the instructions of the assistant, your last message, and the last answer of the AI stay as they are, and together with your new message, they still nearly fill the context window of the model."),
ChatCompressionOffer.KEEPS_TOO_MUCH when this.CompressionTarget is ChatCompressionTarget.SAME_CHAT => TA("Compressing would not help, since the system prompt, your last message with its files, and the last answer of the AI stay word for word, and together with your new message, they still nearly fill the context window of the model."),
ChatCompressionOffer.KEEPS_TOO_MUCH => TA("Compressing would not help, since the new chat keeps the system prompt, your last message with its files, and the last answer of the AI word for word, and together with your new message, they still nearly fill the context window of the model."),
_ => null,
};
/// <summary>
/// Decides again whether compressing is offered, once the user closed the settings through the gear.
/// </summary>
private async Task ApplyChangedSettingsAsync()
{
if (this.RecheckOffer is not null)
this.offer = await this.RecheckOffer();
this.StateHasChanged();
}
private void Cancel() => this.MudDialog.Cancel();
private void SendAnyway() => this.MudDialog.Close(DialogResult.Ok(ContextWindowFullDecision.SEND_ANYWAY));
@@ -9,7 +9,7 @@ namespace AIStudio.Dialogs;
public enum ContextWindowFullSubject
{
/// <summary>
/// A message of the chat page, which compressing continues in a new chat.
/// A message of the chat page, whose chat compressing continues in a new chat or in place, see ChatCompressionTarget.
/// </summary>
CHAT,
@@ -0,0 +1,19 @@
@using AIStudio.Components.Settings
@inherits SettingsDialogBase
<MudDialog>
<TitleContent>
<MudText Typo="Typo.h6" Class="d-flex align-center">
<MudIcon Icon="@AppIcons.COMPRESS_CHAT" Class="mr-2" />
@T("AI Task: Chat Compression")
</MudText>
</TitleContent>
<DialogContent>
<ChatCompressionSettings AvailableLLMProviders="@this.AvailableLLMProviders"/>
</DialogContent>
<DialogActions>
<MudButton OnClick="@this.Close" Variant="Variant.Filled">
@T("Close")
</MudButton>
</DialogActions>
</MudDialog>
@@ -0,0 +1,3 @@
namespace AIStudio.Dialogs.Settings;
public partial class SettingsDialogChatCompression : SettingsDialogBase;