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

@@ -110,11 +110,12 @@
<MudTooltip Text="@T("Copy this chat & continue in the copy.")" Placement="@TOOLBAR_TOOLTIP_PLACEMENT">
<MudIconButton Icon="@AppIcons.DUPLICATE" Disabled="@(!this.CanThreadBeCopied)" OnClick="@this.CopyCurrentChat"/>
</MudTooltip>
<MudTooltip Text="@this.CompressTooltip" Placement="@TOOLBAR_TOOLTIP_PLACEMENT">
<MudIconButton Icon="@AppIcons.COMPRESS_CHAT" Disabled="@(!this.CanThreadBeCompressed)" OnClick="@this.CompressCurrentChat"/>
</MudTooltip>
}
@* Without workspaces, compressing replaces the earlier messages, so the button stays: *@
<MudTooltip Text="@this.CompressTooltip" Placement="@TOOLBAR_TOOLTIP_PLACEMENT">
<MudIconButton Icon="@AppIcons.COMPRESS_CHAT" Disabled="@(!this.CanThreadBeCompressed)" OnClick="@this.CompressFromButtonAsync"/>
</MudTooltip>
<AttachDocuments Name="File Attachments" DocumentPaths="@this.ComposerState.FileAttachments" DocumentPathsChanged="@this.ComposerAttachmentsChanged" CatchAllDocuments="true" UseSmallForm="true" ShowMediaStatus="false" Provider="@this.Provider" OwnerChat="@this.ChatThread" EnsureOwnerChatAsync="@this.EnsureMediaImportChatAsync" KeepPreviewedText="@this.KeepPreviewedTextAsync" Disabled="@(!this.CanAttachFiles)"/>
@@ -1,5 +1,7 @@
using System.Globalization;
using AIStudio.AIOperations;
using AIStudio.AIOperations.ConversationSummary;
using AIStudio.Chat;
using AIStudio.Chat.Compression;
using AIStudio.Dialogs;
@@ -108,12 +110,13 @@ public partial class ChatComponent : MSGComponentBase
private bool hasUnsavedChanges;
/// <summary>
/// Whether the open chat is being continued in a new chat right now, see CompressCurrentChat.
/// Whether the open chat is being compressed right now, see CompressCurrentChatAsync.
/// </summary>
/// <remarks>
/// From the moment the user confirmed the summary until the new chat is open, nothing may be
/// sent: a message sent meanwhile would go into the chat being left, and its answer would be
/// written there while the user already looks at the new chat.
/// From the moment the user confirmed the summary until the new chat is open, or until the summary
/// took the place of the earlier messages, nothing may be sent: a message sent meanwhile would go
/// into the chat being left, and its answer would be written there while the user already looks
/// at the new chat, or it would be summarized away.
/// </remarks>
private bool isCompressing;
@@ -825,10 +828,11 @@ public partial class ChatComponent : MSGComponentBase
/// Whether the open chat can be compressed into a new chat.
/// </summary>
/// <remarks>
/// Compressing copies the chat, so whatever stops a copy stops it as well, and it stores both
/// chats, which needs workspaces. Beyond that, the selected provider writes the summary, so it
/// has to be one the chat allows, with a model large enough for it, and the chat needs a
/// finished answer of the AI, which the new chat keeps word for word.
/// Compressing copies the chat, so whatever stops a copy stops it as well. Without workspaces, it
/// replaces the earlier messages instead, see ContextWindowFullHandling.TargetFor. Beyond that, the
/// conversation continues with the selected provider, so it has to be one the chat allows; some
/// model has to be large enough for the summary, see IsWindowTooSmallForCompression; and the chat
/// needs a finished answer of the AI, which compressing keeps word for word.
/// </remarks>
private bool CanThreadBeCompressed => this.AllowsCompression
&& !this.IsWindowTooSmallForCompression
@@ -842,15 +846,21 @@ public partial class ChatComponent : MSGComponentBase
/// ChatCompressionService.OfferBeforeSendingAsync.
/// </remarks>
private bool AllowsCompression => this.CanThreadBeCopied
&& this.SettingsManager.ConfigurationData.Workspace.StorageBehavior is not WorkspaceStorageBehavior.DISABLE_WORKSPACES
&& !this.isCompressing
&& this.IsProviderSelected
&& this.ChatThread.IsLLMProviderAllowed(this.Provider);
/// <summary>
/// Whether the model of the selected provider is too small to compress the chat, see ChatCompressionService.MIN_CONTEXT_WINDOW.
/// Whether no model is large enough to write the summary of this chat, see ConversationSummaryBudget.MIN_CONTEXT_WINDOW.
/// </summary>
private bool IsWindowTooSmallForCompression => this.IsProviderSelected && !ChatCompressionService.CanSummarizeWith(this.Provider.GetModelProfile().Context);
/// <remarks>
/// The model picked for compressing may write it for a chat whose own model is too small, see
/// ChatCompressionService.ChooseWriter. Other reasons why no model may write it rule out the chat itself
/// already, see AllowsCompression.
/// </remarks>
private bool IsWindowTooSmallForCompression => this.IsProviderSelected
&& this.ChatThread is { } chat
&& this.CompressionService.ChooseWriter(chat, this.Provider) is { HasProvider: false, FallbackIssue: AIOperationProviderIssue.CONTEXT_WINDOW_TOO_SMALL };
/// <summary>
/// What the compress button says it does, or why it is switched off for the selected model.
@@ -858,9 +868,32 @@ public partial class ChatComponent : MSGComponentBase
/// <remarks>
/// The minimum is a limit, so it is written out in full: the short form of the token count would round it.
/// </remarks>
private string CompressTooltip => this.IsWindowTooSmallForCompression
? string.Format(T("Compressing a chat needs a model with a context window of at least {0} tokens."), ChatCompressionService.MIN_CONTEXT_WINDOW.ToString("N0", this.currentCulture))
: T("Compress this chat & switch to a new chat with its summary.");
private string CompressTooltip
{
get
{
if (this.IsWindowTooSmallForCompression)
return string.Format(T("Compressing a chat needs a model with a context window of at least {0} tokens."), ConversationSummaryBudget.MIN_CONTEXT_WINDOW.ToString("N0", this.currentCulture));
return this.AreWorkspacesDisabled
? T("Compress this chat: its summary takes the place of the earlier messages.")
: T("Compress this chat & switch to a new chat with its summary.");
}
}
/// <summary>
/// Whether the user switched off the workspaces, so that chats are never stored.
/// </summary>
private bool AreWorkspacesDisabled => this.SettingsManager.ConfigurationData.Workspace.StorageBehavior is WorkspaceStorageBehavior.DISABLE_WORKSPACES;
/// <summary>
/// Compresses the chat when the user clicks its button.
/// </summary>
/// <remarks>
/// The button continues in a new chat, as compressing after asking does, see ContextWindowFullHandling.TargetFor;
/// without workspaces, it replaces the earlier messages.
/// </remarks>
private Task CompressFromButtonAsync() => this.CompressCurrentChatAsync(ContextWindowFullHandling.TargetFor(ContextWindowFullBehavior.ASK, this.AreWorkspacesDisabled), startsAutomatically: false);
/// <summary>
/// How many blocks the example conversation of the chat template of the given chat holds, see ChatCompressionPlan.Of.
@@ -958,7 +991,9 @@ public partial class ChatComponent : MSGComponentBase
if (this.conversationTokens.TooManyImages || this.conversationTokens.FillShare >= 1d)
return "token-budget-exceeded";
return this.conversationTokens.FillShare >= WINDOW_NEARLY_FULL ? "token-budget-nearly-full" : string.Empty;
// The number warns before AI Studio asks, also when the user lets it ask early:
var nearlyFull = Math.Min(WINDOW_NEARLY_FULL, ChatCompressionOptions.Of(this.SettingsManager.ConfigurationData.ChatCompression).ShareToAsk);
return this.conversationTokens.FillShare >= nearlyFull ? "token-budget-nearly-full" : string.Empty;
}
}
@@ -2248,116 +2283,78 @@ public partial class ChatComponent : MSGComponentBase
}
/// <summary>
/// Compresses the open chat: the AI summarizes it, and the conversation continues in a new chat.
/// Compresses the open chat: the AI summarizes it, and the conversation continues in a new chat, or the summary
/// takes the place of the earlier messages.
/// </summary>
/// <remarks>
/// The open chat stays as it is, so the whole conversation remains available. It is stored first
/// when it has unsaved changes or was never stored at all, e.g., a chat an assistant started while
/// chats are stored by hand: the conversation would be gone once the new chat opens otherwise.
/// The dialog says so beforehand, and when storing fails, nothing is compressed.<br/><br/>
/// The dialog writes the summary, see ChatCompressionDialog; where the conversation goes on is up to the caller,
/// see ContextWindowFullHandling.TargetFor. The summary passes the prompt injection filter before it becomes a
/// message, since a model reads it again, and the conversation continues with the provider of this chat, also
/// when another model wrote the summary.<br/><br/>
///
/// The new chat is a copy of this one whose messages give way to the summary and the last exchange,
/// see ChatCompression.TurnIntoContinuation. It thus keeps the workspace, the profile,
/// the chat template, the tools, the data sources, and the restrictions of this chat, and it
/// continues with the provider which wrote the summary. The summary passes the prompt injection
/// filter before it becomes a message of the new chat, since a model reads it there again.<br/><br/>
///
/// The message the user is writing goes into the new chat, as with a copy. So does a last message
/// which never got an answer, when the user writes nothing, see ChatCompressionPlan. The
/// predefined message of a chat template is no message of the user and stays behind.<br/><br/>
///
/// Once the user confirmed the summary, nothing can be sent until the new chat is open, see
/// isCompressing.
/// Once the user confirmed the summary, or the summary started without asking, nothing can be sent until the
/// chat is compressed, see isCompressing.
/// </remarks>
private async Task CompressCurrentChat()
/// <param name="target">Where the conversation goes on.</param>
/// <param name="startsAutomatically">Whether the summary starts without asking, since the settings say so, see ChatCompressionDialog.StartsAutomatically.</param>
/// <returns>True when the chat was compressed.</returns>
private async Task<bool> CompressCurrentChatAsync(ChatCompressionTarget target, bool startsAutomatically)
{
if (this.ChatThread is not { } sourceChat || !this.CanThreadBeCompressed)
return;
return false;
// The new chat takes the message being written along, so the draft has to say what the user wrote:
if (this.ComposerState.HasUserDraft)
var continuesInNewChat = target is ChatCompressionTarget.NEW_CHAT;
if (continuesInNewChat && this.ComposerState.HasUserDraft)
this.MirrorComposerIntoDraft(sourceChat);
// In the same chat, the message being written stays in the field, so a last message without an answer is summarized:
var exampleConversationLength = this.ExampleConversationLengthOf(sourceChat);
var plan = ChatCompressionPlan.Of(sourceChat, exampleConversationLength, sourceChat.Draft.IsEmpty);
var plan = ChatCompressionPlan.Of(sourceChat, exampleConversationLength, continuesInNewChat && sourceChat.Draft.IsEmpty);
if (plan is null)
{
await this.MessageBus.SendWarning(new(AppIcons.COMPRESS_CHAT, TA("There is nothing to summarize yet before your last message and the last answer of the AI.")));
return;
return false;
}
var provider = this.Provider;
var sourceName = ChatCompression.NameOf(sourceChat.Name);
var storesChatFirst = this.hasUnsavedChanges || !WorkspaceBehaviour.IsChatExisting(new(sourceChat.WorkspaceId, sourceChat.ChatId));
var blockCount = sourceChat.Blocks.Count;
var storesChatFirst = continuesInNewChat && (this.hasUnsavedChanges || !WorkspaceBehaviour.IsChatExisting(new(sourceChat.WorkspaceId, sourceChat.ChatId)));
var dialogParameters = new DialogParameters<ChatCompressionDialog>
{
{ x => x.SourceChat, sourceChat },
{ x => x.Plan, plan },
{ x => x.ProviderSettings, provider },
{ x => x.ChatProvider, provider },
{ x => x.Target, target },
{ x => x.SuggestedName, ChatCompression.NameOfContinuation(sourceChat.Name) },
{ x => x.StoresChatFirst, storesChatFirst },
{ x => x.StartsAutomatically, startsAutomatically },
};
var dialogReference = await this.DialogService.ShowAsync<ChatCompressionDialog>(T("Compress Chat"), dialogParameters, DialogOptions.BLOCKING_FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled || dialogResult.Data is not ChatCompressionDialogResult result)
return;
return false;
// Nothing may continue a chat which is no longer the open one:
if (this.ChatThread?.ChatId != sourceChat.ChatId || this.IsCurrentChatStreaming || this.isCompressing)
return;
return false;
// Replacing the earlier messages needs the very messages which were summarized:
if (!continuesInNewChat && (!ReferenceEquals(this.ChatThread, sourceChat) || sourceChat.Blocks.Count != blockCount))
{
await this.MessageBus.SendWarning(new(AppIcons.COMPRESS_CHAT, TA("This chat changed while the AI wrote its summary, so AI Studio did not compress it. Please try again.")));
return false;
}
this.isCompressing = true;
this.StateHasChanged();
try
{
if (storesChatFirst || this.hasUnsavedChanges)
{
await this.SaveThread();
if (!WorkspaceBehaviour.IsChatExisting(new(sourceChat.WorkspaceId, sourceChat.ChatId)))
{
await this.MessageBus.SendError(new(AppIcons.COMPRESS_CHAT, TA("This chat could not be saved, so AI Studio did not compress it. Please try again.")));
return;
}
}
await this.FlushDraftAsync();
// A model reads the summary again in the new chat, so what the AI wrote passes the filter first:
var payload = await this.AssistantLaunchService.CreateTextPayloadAsync(result.Summary, writtenByModel: true, sourceChat.CaptureRestrictions(), sourceName);
var summaryMessage = ChatCompression.SummaryMessage(ChatCompressionTarget.NEW_CHAT, sourceName, payload.Text);
Action<ChatThread> turnIntoContinuation = copy => ChatCompression.TurnIntoContinuation(copy, exampleConversationLength, ChatCompressionTarget.NEW_CHAT, summaryMessage, payload.Restrictions, provider.Id);
ChatThread continuation;
try
{
continuation = this.Workspaces is null
? await WorkspaceBehaviour.CopyChatAsync(sourceChat, result.Name, turnIntoContinuation)
: await this.Workspaces.CopyChatAsync(sourceChat, result.Name, turnIntoContinuation);
}
catch (Exception e)
{
this.Logger.LogError(e, $"The compressed chat '{sourceChat.ChatId}' could not be continued in a new chat.");
await this.MessageBus.SendError(new(AppIcons.COMPRESS_CHAT, T("The new chat could not be created. This chat stays as it is.")));
return;
}
this.ChatThread = continuation;
this.hasUnsavedChanges = false;
// The new chat is on the disk already, and the message being written moved into it:
this.unstoredChat = null;
this.ComposerState.Clear();
this.ComposerState.RestoreFromDraft(continuation.Draft);
await this.SyncForegroundChatAsync();
this.MarkCurrentChatAsLoadedParameter();
await this.SyncWorkspaceHeaderWithChatThreadAsync();
await this.ChatThreadChanged.InvokeAsync(this.ChatThread);
// The new chat forgot which data sources an AI operation picked for the last request of the old one:
this.dataSourceSelectionComponent?.ChangeOptionWithoutSaving(continuation.DataSourceOptions, continuation.AISelectedDataSources);
this.tokenTracker?.Nudge();
return continuesInNewChat
? await this.ContinueInNewChatAsync(sourceChat, exampleConversationLength, sourceName, result, provider, storesChatFirst)
: await this.ReplaceEarlierMessagesAsync(sourceChat, exampleConversationLength, sourceName, result.Summary, provider);
}
finally
{
@@ -2366,6 +2363,129 @@ public partial class ChatComponent : MSGComponentBase
}
}
/// <summary>
/// Continues the conversation of a compressed chat in a new chat, which opens in its place.
/// </summary>
/// <remarks>
/// The compressed chat stays as it is, so the whole conversation remains available. It is stored first when it
/// has unsaved changes or was never stored at all, e.g., a chat an assistant started while chats are stored by
/// hand: the conversation would be gone once the new chat opens otherwise. The dialog says so beforehand, and when
/// storing fails, nothing is compressed.<br/><br/>
///
/// The new chat is a copy of this one whose messages give way to the summary and the last exchange, see
/// ChatCompression.TurnIntoContinuation. It thus keeps the workspace, the profile, the chat template, the tools,
/// the data sources, and the restrictions of this chat.<br/><br/>
///
/// The message the user is writing goes into the new chat, as with a copy. So does a last message which never got
/// an answer, when the user writes nothing, see ChatCompressionPlan. The predefined message of a chat template is
/// no message of the user and stays behind.
/// </remarks>
/// <param name="sourceChat">The compressed chat, which is the open one.</param>
/// <param name="exampleConversationLength">How many blocks the example conversation of the chat template holds.</param>
/// <param name="sourceName">The name of the compressed chat, as the summary calls it.</param>
/// <param name="result">What the dialog returned: the name of the new chat and the summary.</param>
/// <param name="provider">The provider of the chat, which the new chat continues with.</param>
/// <param name="storesChatFirst">Whether the compressed chat is stored first.</param>
/// <returns>True when the new chat is open.</returns>
private async Task<bool> ContinueInNewChatAsync(ChatThread sourceChat, int exampleConversationLength, string sourceName, ChatCompressionDialogResult result, AIStudio.Settings.Provider provider, bool storesChatFirst)
{
if (storesChatFirst || this.hasUnsavedChanges)
{
await this.SaveThread();
if (!WorkspaceBehaviour.IsChatExisting(new(sourceChat.WorkspaceId, sourceChat.ChatId)))
{
await this.MessageBus.SendError(new(AppIcons.COMPRESS_CHAT, TA("This chat could not be saved, so AI Studio did not compress it. Please try again.")));
return false;
}
}
await this.FlushDraftAsync();
// A model reads the summary again in the new chat, so what the AI wrote passes the filter first:
var payload = await this.AssistantLaunchService.CreateTextPayloadAsync(result.Summary, writtenByModel: true, sourceChat.CaptureRestrictions(), sourceName);
var summaryMessage = ChatCompression.SummaryMessage(ChatCompressionTarget.NEW_CHAT, sourceName, payload.Text);
Action<ChatThread> turnIntoContinuation = copy => ChatCompression.TurnIntoContinuation(copy, exampleConversationLength, ChatCompressionTarget.NEW_CHAT, summaryMessage, payload.Restrictions, provider.Id);
ChatThread continuation;
try
{
continuation = this.Workspaces is null
? await WorkspaceBehaviour.CopyChatAsync(sourceChat, result.Name, turnIntoContinuation)
: await this.Workspaces.CopyChatAsync(sourceChat, result.Name, turnIntoContinuation);
}
catch (Exception e)
{
this.Logger.LogError(e, $"The compressed chat '{sourceChat.ChatId}' could not be continued in a new chat.");
await this.MessageBus.SendError(new(AppIcons.COMPRESS_CHAT, T("The new chat could not be created. This chat stays as it is.")));
return false;
}
this.ChatThread = continuation;
this.hasUnsavedChanges = false;
// The new chat is on the disk already, and the message being written moved into it:
this.unstoredChat = null;
this.ComposerState.Clear();
this.ComposerState.RestoreFromDraft(continuation.Draft);
await this.SyncForegroundChatAsync();
this.MarkCurrentChatAsLoadedParameter();
await this.SyncWorkspaceHeaderWithChatThreadAsync();
await this.ChatThreadChanged.InvokeAsync(this.ChatThread);
// The new chat forgot which data sources an AI operation picked for the last request of the old one:
this.dataSourceSelectionComponent?.ChangeOptionWithoutSaving(continuation.DataSourceOptions, continuation.AISelectedDataSources);
this.tokenTracker?.Nudge();
return true;
}
/// <summary>
/// Lets the summary take the place of the earlier messages of the open chat.
/// </summary>
/// <remarks>
/// For a user who chose to compress in place, and for chats without workspaces, which are never stored and thus
/// have no new chat to switch to. The chat changes itself, so everything which refers to it stays valid; the last
/// message of the user and the last answer of the AI stay as they are, and the message being written stays in the
/// field, see ChatCompression.TurnIntoContinuation.<br/><br/>
///
/// A chat which is stored, automatically or by hand, is stored again right away, since the dialog said that AI
/// Studio does not keep the earlier messages. Only then are the transcripts of the summarized messages deleted:
/// the stored chat must never refer to a deleted file. A chat which was never stored keeps its unsaved changes.
/// </remarks>
/// <param name="chat">The open chat.</param>
/// <param name="exampleConversationLength">How many blocks the example conversation of the chat template holds.</param>
/// <param name="sourceName">The name of the chat, as the summary calls it.</param>
/// <param name="summary">The summary the AI wrote.</param>
/// <param name="provider">The provider of the chat, which the conversation continues with.</param>
/// <returns>True when the summary took the place of the earlier messages.</returns>
private async Task<bool> ReplaceEarlierMessagesAsync(ChatThread chat, int exampleConversationLength, string sourceName, string summary, AIStudio.Settings.Provider provider)
{
// A model reads the summary again, so what the AI wrote passes the filter first:
var payload = await this.AssistantLaunchService.CreateTextPayloadAsync(summary, writtenByModel: true, chat.CaptureRestrictions(), sourceName);
var summaryMessage = ChatCompression.SummaryMessage(ChatCompressionTarget.SAME_CHAT, sourceName, payload.Text);
var formerTranscripts = chat.ManagedTranscripts();
ChatCompression.TurnIntoContinuation(chat, exampleConversationLength, ChatCompressionTarget.SAME_CHAT, summaryMessage, payload.Restrictions, provider.Id);
var storageBehavior = this.SettingsManager.ConfigurationData.Workspace.StorageBehavior;
var isStored = storageBehavior is not WorkspaceStorageBehavior.DISABLE_WORKSPACES && WorkspaceBehaviour.IsChatExisting(new(chat.WorkspaceId, chat.ChatId));
if (storageBehavior is WorkspaceStorageBehavior.STORE_CHATS_AUTOMATICALLY || isStored)
{
await this.SaveThread();
this.hasUnsavedChanges = false;
}
else if (storageBehavior is not WorkspaceStorageBehavior.DISABLE_WORKSPACES)
this.hasUnsavedChanges = true;
chat.DeleteTranscriptsNoLongerReferenced(formerTranscripts);
await this.ChatThreadChanged.InvokeAsync(chat);
// The chat forgot which data sources an AI operation picked for its last request:
this.dataSourceSelectionComponent?.ChangeOptionWithoutSaving(chat.DataSourceOptions, chat.AISelectedDataSources);
this.tokenTracker?.Nudge();
return true;
}
/// <summary>
/// Asks the user what to do when the message about to be sent fills the context window of the
/// model, or no longer fits into it.
@@ -2379,30 +2499,55 @@ public partial class ChatComponent : MSGComponentBase
/// Compressing is offered only where this chat allows it, see AllowsCompression, and where it
/// makes enough room; otherwise, the notice says why it would not help, see
/// ChatCompressionService.OfferBeforeSendingAsync. The message being written goes along into the
/// new chat unchanged, where the user sends it, see CompressCurrentChat.
/// new chat unchanged, or stays in the field when the chat is compressed in place, and the user
/// sends it afterward, see CompressCurrentChatAsync.<br/><br/>
///
/// The settings may say to send without asking or to compress without asking, see
/// ContextWindowFullHandling.Decide. Compressing without asking counts the conversation again
/// afterward, checks once more that the chat allows its provider, since the summary may bring
/// restrictions along, and decides once more without compressing again. Then the message goes
/// out, in the new chat or in the same one.
/// </remarks>
/// <param name="mayCompressAutomatically">False when the chat was compressed for this message already.</param>
/// <returns>True when the message is to be sent.</returns>
private async Task<bool> ConfirmContextWindowAsync()
private async Task<bool> ConfirmContextWindowAsync(bool mayCompressAutomatically = true)
{
if (!this.conversationTokens.AsksBeforeSending)
var options = ChatCompressionOptions.Of(this.SettingsManager.ConfigurationData.ChatCompression);
if (!this.conversationTokens.AsksBeforeSending(options.ShareToAsk))
return true;
var offer = this.AllowsCompression
? await this.CompressionService.OfferBeforeSendingAsync(this.ChatThread!, this.ExampleConversationLengthOf(this.ChatThread!), this.Provider, this.conversationTokens)
: ChatCompressionOffer.NONE;
switch (await ContextWindowFullDialog.ShowAsync(this.DialogService, this.conversationTokens, ContextWindowFullSubject.CHAT, offer))
var target = ContextWindowFullHandling.TargetFor(options.WhenContextWindowFills, this.AreWorkspacesDisabled);
var offer = await this.OfferCompressionAsync(options);
switch (ContextWindowFullHandling.Decide(options.WhenContextWindowFills, offer, canSendAnyway: true, mayCompressAutomatically))
{
case ContextWindowFullDecision.SEND_ANYWAY:
case ContextWindowFullAction.SEND:
return true;
case ContextWindowFullDecision.COMPRESS:
case ContextWindowFullAction.COMPRESS:
//
// The user meant to send what is in the composer, so it goes along into the new chat,
// even the untouched message of a chat template, which compressing leaves behind otherwise:
//
this.ComposerState.MarkUserDraft();
await this.CompressCurrentChat();
if (!await this.CompressCurrentChatAsync(target, startsAutomatically: true))
return false;
this.conversationTokens = await this.CountConversationAsync(CancellationToken.None);
if (!this.ChatThread.IsLLMProviderAllowed(this.Provider))
return false;
return await this.ConfirmContextWindowAsync(mayCompressAutomatically: false);
}
switch (await ContextWindowFullDialog.ShowAsync(this.DialogService, this.conversationTokens, ContextWindowFullSubject.CHAT, offer, compressionTarget: target, recheckOffer: () => this.OfferCompressionAsync(ChatCompressionOptions.Of(this.SettingsManager.ConfigurationData.ChatCompression))))
{
case ContextWindowFullDecision.SEND_ANYWAY:
return true;
case ContextWindowFullDecision.COMPRESS:
// As above, what is in the composer goes along:
this.ComposerState.MarkUserDraft();
await this.CompressCurrentChatAsync(target, startsAutomatically: false);
return false;
default:
@@ -2410,6 +2555,18 @@ public partial class ChatComponent : MSGComponentBase
}
}
/// <summary>
/// Decides whether the notice before sending offers to compress this chat, or why it would not help.
/// </summary>
/// <remarks>
/// Nothing is offered where this chat does not allow compressing, see AllowsCompression.
/// </remarks>
/// <param name="options">The settings of compressing, read once for this decision.</param>
/// <returns>Whether compressing is offered, or why not.</returns>
private async Task<ChatCompressionOffer> OfferCompressionAsync(ChatCompressionOptions options) => this.AllowsCompression
? await this.CompressionService.OfferBeforeSendingAsync(this.ChatThread!, this.ExampleConversationLengthOf(this.ChatThread!), this.Provider, this.conversationTokens, options)
: ChatCompressionOffer.NONE;
private async Task LoadedChatChanged(bool notifyParent = true)
{
this.hasUnsavedChanges = false;
@@ -2646,10 +2803,35 @@ public partial class ChatComponent : MSGComponentBase
/// component reference, which is only set once the component has rendered.
///
/// Called by the tracker, never directly. Whoever thinks something changed nudges it instead,
/// and it decides when the work is worth doing.
/// and it decides when the work is worth doing. Whoever needs the count right away, such as the
/// notice before sending after compressing, counts with CountConversationAsync.
/// </remarks>
/// <param name="token">Ends the count when the component goes away.</param>
private async Task RecountTokensAsync(CancellationToken token)
{
var counted = await this.CountConversationAsync(token);
if (token.IsCancellationRequested)
return;
await this.InvokeAsync(() =>
{
if (counted == this.conversationTokens)
return;
this.conversationTokens = counted;
this.StateHasChanged();
});
}
/// <summary>
/// Counts what the next request would take out of the model's context window, see RecountTokensAsync.
/// </summary>
/// <remarks>
/// Unlike the tracker, which waits for a quiet moment, this counts right away.
/// </remarks>
/// <param name="token">Ends the count when nobody needs it anymore.</param>
/// <returns>What the conversation takes together with the message being written.</returns>
private async Task<ConversationTokens> CountConversationAsync(CancellationToken token)
{
var provider = AIStudio.Settings.Provider.NONE;
var parts = ConversationParts.NOTHING;
@@ -2682,18 +2864,7 @@ public partial class ChatComponent : MSGComponentBase
reported = thread.ReportedHistoryFor(provider.Model);
});
var counted = await this.ConversationTokenCounter.CountAsync(provider, parts, reported, token);
if (token.IsCancellationRequested)
return;
await this.InvokeAsync(() =>
{
if (counted == this.conversationTokens)
return;
this.conversationTokens = counted;
this.StateHasChanged();
});
return await this.ConversationTokenCounter.CountAsync(provider, parts, reported, token);
}
/// <summary>
@@ -0,0 +1,10 @@
@inherits MSGComponentBase
<MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1">
<MudText Typo="Typo.h6" Class="flex-grow-1">
@this.Title
</MudText>
<MudTooltip Text="@T("Settings of chat compression")" Placement="Placement.Bottom">
<MudIconButton Variant="Variant.Text" Icon="@AppIcons.SETTINGS" Disabled="@this.Disabled" OnClick="@this.OpenSettingsAsync"/>
</MudTooltip>
</MudStack>
@@ -0,0 +1,46 @@
using AIStudio.Dialogs.Settings;
using Microsoft.AspNetCore.Components;
using DialogOptions = AIStudio.Dialogs.DialogOptions;
namespace AIStudio.Components;
/// <summary>
/// The title of a dialog about compressing a chat, with a gear which opens the settings of chat compression.
/// </summary>
/// <remarks>
/// Used by the dialog of compressing and by the notice before sending, see ChatCompressionDialog and
/// ContextWindowFullDialog. Both decide anew once the settings close, since the user may have changed what they
/// show, such as the model which writes the summary.
/// </remarks>
public partial class DialogTitleWithChatCompressionSettings : MSGComponentBase
{
[Inject]
private IDialogService DialogService { get; init; } = null!;
/// <summary>
/// The title of the dialog.
/// </summary>
[Parameter]
public string Title { get; set; } = string.Empty;
/// <summary>
/// Whether the gear is switched off, e.g., while the AI writes the summary.
/// </summary>
[Parameter]
public bool Disabled { get; set; }
/// <summary>
/// Called once the settings are closed again.
/// </summary>
[Parameter]
public EventCallback SettingsClosed { get; set; }
private async Task OpenSettingsAsync()
{
var dialogReference = await this.DialogService.ShowAsync<SettingsDialogChatCompression>(null, new DialogParameters(), DialogOptions.FULLSCREEN);
await dialogReference.Result;
await this.SettingsClosed.InvokeAsync();
}
}
@@ -299,7 +299,7 @@ public partial class EmbeddedChat : MSGComponentBase
/// How much room the conversation leaves in the context window, as far as the chat shows it, see
/// EmbeddedChatTokenBudget.Shown.
/// </summary>
private EmbeddedChatTokenBudgetState Budget => EmbeddedChatTokenBudget.Shown(this.tokens, this.ShowsContextWindow);
private EmbeddedChatTokenBudgetState Budget => EmbeddedChatTokenBudget.Shown(this.tokens, this.ShowsContextWindow, ChatCompressionOptions.Of(this.SettingsManager.ConfigurationData.ChatCompression).ShareToAsk);
/// <summary>
/// Whether the chat offers to compress the conversation, see AllowsCompression.
@@ -544,17 +544,24 @@ public partial class EmbeddedChat : MSGComponentBase
/// that is all it says: the dialog names the window, which would tell apart models the user must not know.
/// Compressing is offered where the chat allows it and where it makes room for the message; otherwise, the dialog
/// says why it would not help, see ChatCompressionService.OfferBeforeSendingAsync. The message stays in the field
/// then, and the user sends it afterward.
/// then, and the user sends it afterward.<br/><br/>
///
/// The settings may say to send without asking or to compress without asking, see ContextWindowFullHandling.Decide.
/// A message which no longer fits is never sent without asking. Compressing without asking replaces the earlier
/// messages, as compressing always does here; the conversation is counted again afterward and decided on once
/// more, without compressing again, and then the message goes out.
/// </remarks>
/// <param name="message">The text of the message about to be sent.</param>
/// <param name="mayCompressAutomatically">False when the conversation was compressed for this message already.</param>
/// <returns>True when the message is to be sent.</returns>
private async Task<bool> ConfirmContextWindowAsync(string message)
private async Task<bool> ConfirmContextWindowAsync(string message, bool mayCompressAutomatically = true)
{
if (EmbeddedChatTokenBudget.Of(this.tokens) is EmbeddedChatTokenBudgetState.UNKNOWN || this.conversation?.Thread is not { } thread)
var options = ChatCompressionOptions.Of(this.SettingsManager.ConfigurationData.ChatCompression);
if (EmbeddedChatTokenBudget.Of(this.tokens, options.ShareToAsk) is EmbeddedChatTokenBudgetState.UNKNOWN || this.conversation?.Thread is not { } thread)
return true;
var tokensWithMessage = this.tokens with { DraftTokens = await this.CountMessageAsync(message) };
var notice = EmbeddedChatTokenBudget.NoticeBeforeSending(tokensWithMessage, this.ShowsContextWindow);
var notice = EmbeddedChatTokenBudget.NoticeBeforeSending(tokensWithMessage, this.ShowsContextWindow, options.ShareToAsk);
if (notice is EmbeddedChatSendNotice.NONE)
return true;
@@ -564,17 +571,28 @@ public partial class EmbeddedChat : MSGComponentBase
return false;
}
var offer = this.AllowsCompression && thread.IsLLMProviderAllowed(this.Provider)
? await this.CompressionService.OfferBeforeSendingAsync(thread, 0, this.Provider, tokensWithMessage, this.countToken)
: ChatCompressionOffer.NONE;
var offer = await this.OfferCompressionAsync(thread, tokensWithMessage, options);
var canSendAnyway = notice is EmbeddedChatSendNotice.NEARLY_FULL;
switch (ContextWindowFullHandling.Decide(options.WhenContextWindowFills, offer, canSendAnyway, mayCompressAutomatically))
{
case ContextWindowFullAction.SEND:
return true;
switch (await ContextWindowFullDialog.ShowAsync(this.DialogService, tokensWithMessage, ContextWindowFullSubject.EMBEDDED_CHAT, offer, canSendAnyway: notice is EmbeddedChatSendNotice.NEARLY_FULL))
case ContextWindowFullAction.COMPRESS:
if (!await this.CompressAsync(startsAutomatically: true))
return false;
await this.RecountAsync();
return await this.ConfirmContextWindowAsync(message, mayCompressAutomatically: false);
}
switch (await ContextWindowFullDialog.ShowAsync(this.DialogService, tokensWithMessage, ContextWindowFullSubject.EMBEDDED_CHAT, offer, canSendAnyway, ChatCompressionTarget.SAME_CHAT, recheckOffer: () => this.OfferCompressionAsync(thread, tokensWithMessage, ChatCompressionOptions.Of(this.SettingsManager.ConfigurationData.ChatCompression))))
{
case ContextWindowFullDecision.SEND_ANYWAY:
return true;
case ContextWindowFullDecision.COMPRESS:
await this.CompressAsync();
await this.CompressAsync(startsAutomatically: false);
return false;
default:
@@ -582,6 +600,21 @@ public partial class EmbeddedChat : MSGComponentBase
}
}
/// <summary>
/// Decides whether the notice before sending offers to compress the conversation, or why it would not help.
/// </summary>
/// <remarks>
/// Nothing is offered where the conversation does not allow compressing, see AllowsCompression, nor where the
/// conversation no longer allows its own provider.
/// </remarks>
/// <param name="thread">The conversation.</param>
/// <param name="tokensWithMessage">What the conversation costs together with the message about to be sent.</param>
/// <param name="options">The settings of compressing, read once for this decision.</param>
/// <returns>Whether compressing is offered, or why not.</returns>
private async Task<ChatCompressionOffer> OfferCompressionAsync(ChatThread thread, ConversationTokens tokensWithMessage, ChatCompressionOptions options) => this.AllowsCompression && thread.IsLLMProviderAllowed(this.Provider)
? await this.CompressionService.OfferBeforeSendingAsync(thread, 0, this.Provider, tokensWithMessage, options, this.countToken)
: ChatCompressionOffer.NONE;
/// <summary>
/// Counts the tokens of a message about to be sent.
/// </summary>
@@ -610,28 +643,31 @@ public partial class EmbeddedChat : MSGComponentBase
/// filter before it becomes a message, since the model reads it again. The conversation is replaced only once the
/// compressed one is stored, see EmbeddedChatService.ReplaceAsync.
/// </remarks>
private async Task CompressAsync()
/// <param name="startsAutomatically">Whether the summary starts without asking, since the settings say so, see ChatCompressionDialog.StartsAutomatically.</param>
/// <returns>True when the summary took the place of the earlier messages.</returns>
private async Task<bool> CompressAsync(bool startsAutomatically)
{
if (this.conversation is not { Thread: { } thread, IsRunning: false })
return;
return false;
// The message about to be sent waits in the field, so an unanswered last message is summarized with the rest:
var plan = ChatCompressionPlan.Of(thread, 0, draftIsEmpty: false);
if (plan is null)
return;
return false;
var dialogParameters = new DialogParameters<ChatCompressionDialog>
{
{ x => x.SourceChat, thread },
{ x => x.Plan, plan },
{ x => x.ProviderSettings, this.Provider },
{ x => x.ChatProvider, this.Provider },
{ x => x.Target, ChatCompressionTarget.SAME_CHAT },
{ x => x.StartsAutomatically, startsAutomatically },
};
var dialogReference = await this.DialogService.ShowAsync<ChatCompressionDialog>(T("Compress Conversation"), dialogParameters, DialogOptions.BLOCKING_FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled || dialogResult.Data is not ChatCompressionDialogResult result)
return;
return false;
this.isCompressing = true;
try
@@ -641,13 +677,17 @@ public partial class EmbeddedChat : MSGComponentBase
var summaryMessage = ChatCompression.SummaryMessage(ChatCompressionTarget.SAME_CHAT, sourceName, payload.Text);
var compressed = WorkspaceBehaviour.CloneChat(thread);
ChatCompression.TurnIntoContinuation(compressed, 0, ChatCompressionTarget.SAME_CHAT, summaryMessage, payload.Restrictions, this.Provider.Id);
if (!await this.ChatService.ReplaceAsync(this.ChatId, compressed))
await this.MessageBus.SendWarning(new(AppIcons.COMPRESS_CHAT, T("The conversation was not compressed, because the AI answered meanwhile.")));
if (await this.ChatService.ReplaceAsync(this.ChatId, compressed))
return true;
await this.MessageBus.SendWarning(new(AppIcons.COMPRESS_CHAT, T("The conversation was not compressed, because the AI answered meanwhile.")));
return false;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
this.Logger.LogError(exception, "Could not store the compressed embedded chat '{ChatId}'.", this.ChatId);
await this.MessageBus.SendError(new(AppIcons.COMPRESS_CHAT, TA("AI Studio could not save the compressed conversation, so it stays as it was. Please try again.")));
return false;
}
finally
{
@@ -0,0 +1,19 @@
@using AIStudio.Settings
@using AIStudio.Settings.DataModel
@inherits MSGComponentBase
<MudJustifiedText Typo="Typo.body1" Class="mb-3">
@T("When a chat grows too long for the context window of its model, AI Studio can compress it: a model summarizes the earlier messages, and the conversation continues with the summary. Every further message then costs fewer tokens.")
</MudJustifiedText>
<MudPaper Class="pa-3 mb-3 border-dashed border rounded-lg">
<ConfigurationSelect OptionDescription="@T("What should happen when a chat grows too long for the context window?")" SelectedValue="@(() => this.SettingsManager.ConfigurationData.ChatCompression.ContextWindowFullBehavior)" Data="@ConfigurationSelectDataFactory.GetContextWindowFullBehaviorData()" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.ChatCompression.ContextWindowFullBehavior = selectedValue)" OptionHelp="@TA("Assistants cannot compress their request: they ask you, unless you choose to send without asking. The BeyondFacts Lab and chats without workspaces always replace the earlier messages, since they cannot continue in a new chat.")" IsLocked="() => ManagedConfiguration.TryGet(x => x.ChatCompression, x => x.ContextWindowFullBehavior, out var meta) && meta.IsLocked"/>
<ConfigurationSlider T="int" OptionDescription="@T("Fill level of the context window from which AI Studio steps in")" Min="@DataChatCompression.MIN_CONTEXT_WINDOW_THRESHOLD_PERCENT" Max="@DataChatCompression.MAX_CONTEXT_WINDOW_THRESHOLD_PERCENT" Step="5" Unit="%" Value="@(() => this.SettingsManager.ConfigurationData.ChatCompression.ContextWindowThresholdPercent)" ValueUpdate="@(updatedValue => this.SettingsManager.ConfigurationData.ChatCompression.ContextWindowThresholdPercent = updatedValue)" OptionHelp="@TA("Before sending a message, AI Studio checks how full the context window of the model would be. From this share on, it does what you chose above. A lower share keeps more room for long answers.")" IsLocked="() => ManagedConfiguration.TryGet(x => x.ChatCompression, x => x.ContextWindowThresholdPercent, out var meta) && meta.IsLocked"/>
</MudPaper>
<MudPaper Class="pa-3 mb-3 border-dashed border rounded-lg">
<ConfigurationMinConfidenceSelection RestrictToGlobalMinimumConfidence="@true" SelectedValue="@(() => this.SettingsManager.ConfigurationData.ChatCompression.MinimumProviderConfidence)" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.ChatCompression.MinimumProviderConfidence = selectedValue)" IsLocked="() => ManagedConfiguration.TryGet(x => x.ChatCompression, x => x.MinimumProviderConfidence, out var meta) && meta.IsLocked"/>
<ConfigurationProviderSelection Component="Components.AI_TASK_CHAT_COMPRESSION" EmptySelectionText="@T("Use the model of the chat")" Data="@this.AvailableLLMProviders" SelectedValue="@(() => this.SettingsManager.ConfigurationData.ChatCompression.PreselectedProvider)" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.ChatCompression.PreselectedProvider = selectedValue)" HelpText="@(() => TA("Optionally choose a model for writing summaries, e.g., one with a large context window, which summarizes long chats in fewer steps. When it may not see a chat, e.g., because of the data sources of the chat, the model of the chat writes the summary."))" IsLocked="() => ManagedConfiguration.TryGet(x => x.ChatCompression, x => x.PreselectedProvider, out var meta) && meta.IsLocked"/>
<ConfigurationSlider T="int" OptionDescription="@T("Longest summary")" Min="@DataChatCompression.MIN_SUMMARY_TOKENS" Max="@DataChatCompression.MAX_SUMMARY_TOKENS" Step="1024" Unit="@T("tokens")" Value="@(() => this.SettingsManager.ConfigurationData.ChatCompression.MaxSummaryTokens)" ValueUpdate="@(updatedValue => this.SettingsManager.ConfigurationData.ChatCompression.MaxSummaryTokens = updatedValue)" OptionHelp="@T("A summary takes at most a quarter of the context window, and never more than this. A longer summary keeps more details, but leaves less room for the rest of the conversation.")" IsLocked="() => ManagedConfiguration.TryGet(x => x.ChatCompression, x => x.MaxSummaryTokens, out var meta) && meta.IsLocked"/>
<ConfigurationText OptionDescription="@T("Preselect what the summary should pay particular attention to")" Icon="@AppIcons.SUMMARY_FOCUS" Text="@(() => this.SettingsManager.ConfigurationData.ChatCompression.PreselectedFocus)" TextUpdate="@(updatedText => this.SettingsManager.ConfigurationData.ChatCompression.PreselectedFocus = updatedText)" OptionHelp="@TA("Compressing starts with this focus, and in the dialog, you can still change it. For example: the decisions about the budget, with all figures.")" IsLocked="() => ManagedConfiguration.TryGet(x => x.ChatCompression, x => x.PreselectedFocus, out var meta) && meta.IsLocked"/>
</MudPaper>
@@ -0,0 +1,21 @@
using AIStudio.Settings;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Components.Settings;
/// <summary>
/// The settings of compressing a chat, and of what happens when a chat fills the context window of its model.
/// </summary>
/// <remarks>
/// Shown in the panel of the settings page and in the dialog which the dialogs of compressing open, see
/// SettingsPanelAITaskChatCompression and SettingsDialogChatCompression, so that both show the same.
/// </remarks>
public partial class ChatCompressionSettings : MSGComponentBase
{
/// <summary>
/// The providers to choose from for writing the summary.
/// </summary>
[Parameter]
public IReadOnlyList<ConfigurationSelectData<string>> AvailableLLMProviders { get; set; } = [];
}
@@ -0,0 +1,5 @@
@inherits SettingsPanelBase
<ExpansionPanel HeaderIcon="@AppIcons.COMPRESS_CHAT" HeaderText="@T("AI Task: Chat Compression")">
<ChatCompressionSettings AvailableLLMProviders="@this.AvailableLLMProvidersFunc()"/>
</ExpansionPanel>
@@ -0,0 +1,3 @@
namespace AIStudio.Components.Settings;
public partial class SettingsPanelAITaskChatCompression : SettingsPanelBase;