mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-11-23 04:53:48 +00:00
Added context compression (#1198)
Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
This commit is contained in:
1 parent
28b88580a9
commit
8a4a26503b
54 files changed
+4582
-56
No files matched your search
@@ -110,6 +110,10 @@
|
||||
<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>
|
||||
}
|
||||
|
||||
<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,6 +1,7 @@
|
||||
using System.Globalization;
|
||||
|
||||
using AIStudio.Chat;
|
||||
using AIStudio.Chat.Compression;
|
||||
using AIStudio.Dialogs;
|
||||
using AIStudio.Provider;
|
||||
using AIStudio.Settings;
|
||||
@@ -74,6 +75,9 @@ public partial class ChatComponent : MSGComponentBase
|
||||
|
||||
[Inject]
|
||||
private ConversationTokenCounter ConversationTokenCounter { get; init; } = null!;
|
||||
|
||||
[Inject]
|
||||
private ChatCompressionService CompressionService { get; init; } = null!;
|
||||
|
||||
[Inject]
|
||||
private IJSRuntime JsRuntime { get; init; } = null!;
|
||||
@@ -102,6 +106,17 @@ public partial class ChatComponent : MSGComponentBase
|
||||
private Profile currentProfile = Profile.NO_PROFILE;
|
||||
private ChatTemplate currentChatTemplate = ChatTemplate.NO_CHAT_TEMPLATE;
|
||||
private bool hasUnsavedChanges;
|
||||
|
||||
/// <summary>
|
||||
/// Whether the open chat is being continued in a new chat right now, see CompressCurrentChat.
|
||||
/// </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.
|
||||
/// </remarks>
|
||||
private bool isCompressing;
|
||||
|
||||
private bool mustScrollToBottomAfterRender;
|
||||
private InnerScrolling scrollingArea = null!;
|
||||
private byte scrollRenderCountdown;
|
||||
@@ -806,6 +821,54 @@ public partial class ChatComponent : MSGComponentBase
|
||||
|
||||
private bool CanThreadBeCopied => this.CanThreadBeSaved && !this.IsCurrentChatStreaming && !this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
private bool CanThreadBeCompressed => this.AllowsCompression
|
||||
&& !this.IsWindowTooSmallForCompression
|
||||
&& ChatCompressionPlan.HasFinishedAnswer(this.ChatThread!);
|
||||
|
||||
/// <summary>
|
||||
/// Whether this chat may be compressed at all, whatever its length and the model; see CanThreadBeCompressed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The notice before sending asks the rest, so that it can say why compressing would not help, see
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private bool IsWindowTooSmallForCompression => this.IsProviderSelected && !ChatCompressionService.CanSummarizeWith(this.Provider.GetModelProfile().Context);
|
||||
|
||||
/// <summary>
|
||||
/// What the compress button says it does, or why it is switched off for the selected model.
|
||||
/// </summary>
|
||||
/// <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.");
|
||||
|
||||
/// <summary>
|
||||
/// How many blocks the example conversation of the chat template of the given chat holds, see ChatCompressionPlan.Of.
|
||||
/// </summary>
|
||||
/// <param name="chat">The chat.</param>
|
||||
/// <returns>The number of blocks, 0 without a chat template.</returns>
|
||||
private int ExampleConversationLengthOf(ChatThread chat) => this.SettingsManager.GetChatTemplateById(chat.SelectedChatTemplate).ExampleConversation.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Whether a chat template can be made from the open chat. While an answer is being written, the template would copy it unfinished.
|
||||
/// </summary>
|
||||
@@ -872,17 +935,6 @@ public partial class ChatComponent : MSGComponentBase
|
||||
|
||||
private string UserInputClass => $"{(this.SettingsManager.ConfigurationData.Confidence.ShowProviderConfidence ? "confidence-border" : string.Empty)} {this.TokenBudgetClass}".Trim();
|
||||
|
||||
/// <summary>
|
||||
/// How much of the model's context window the conversation already takes.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Zero whenever nobody wrote the window down. There is then nothing to be full of, and a share
|
||||
/// of an unknown total would be a number made up on the spot.
|
||||
/// </remarks>
|
||||
private double TokenBudgetFill => this.conversationTokens is { IsKnown: true, Window.IsKnown: true }
|
||||
? (double) this.conversationTokens.Tokens / this.conversationTokens.Window.DefaultTokens
|
||||
: 0d;
|
||||
|
||||
/// <summary>
|
||||
/// What the number under the input field is coloured with, if anything.
|
||||
/// </summary>
|
||||
@@ -903,10 +955,10 @@ public partial class ChatComponent : MSGComponentBase
|
||||
// Too many pictures is the same kind of news as a full window: the request will be
|
||||
// refused, and for the same reason -- more was put in than the model takes.
|
||||
//
|
||||
if (this.conversationTokens.TooManyImages || this.TokenBudgetFill >= 1d)
|
||||
if (this.conversationTokens.TooManyImages || this.conversationTokens.FillShare >= 1d)
|
||||
return "token-budget-exceeded";
|
||||
|
||||
return this.TokenBudgetFill >= WINDOW_NEARLY_FULL ? "token-budget-nearly-full" : string.Empty;
|
||||
return this.conversationTokens.FillShare >= WINDOW_NEARLY_FULL ? "token-budget-nearly-full" : string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1248,9 +1300,9 @@ public partial class ChatComponent : MSGComponentBase
|
||||
if (!this.IsProviderSelected)
|
||||
return true;
|
||||
|
||||
if(this.IsCurrentChatStreaming)
|
||||
if(this.IsCurrentChatStreaming || this.isCompressing)
|
||||
return true;
|
||||
|
||||
|
||||
if(!this.ChatThread.IsLLMProviderAllowed(this.Provider))
|
||||
return true;
|
||||
|
||||
@@ -1634,7 +1686,7 @@ public partial class ChatComponent : MSGComponentBase
|
||||
// the AI job service would turn a second answer down only after the chat got its message and
|
||||
// an empty answer, which then stays.
|
||||
//
|
||||
if (this.IsCurrentChatStreaming)
|
||||
if (this.IsCurrentChatStreaming || this.isCompressing)
|
||||
return;
|
||||
|
||||
if (this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner))
|
||||
@@ -1648,6 +1700,17 @@ public partial class ChatComponent : MSGComponentBase
|
||||
if(!this.ChatThread.IsLLMProviderAllowed(this.Provider))
|
||||
return;
|
||||
|
||||
//
|
||||
// Not when an answer is only generated again: no new message is sent then, and what the
|
||||
// user is writing stays in the composer.
|
||||
//
|
||||
if (!reuseLastUserPrompt && !await this.ConfirmContextWindowAsync())
|
||||
return;
|
||||
|
||||
// The notice may have waited for the user, while another message was sent or the chat was compressed:
|
||||
if (this.IsCurrentChatStreaming || this.isCompressing)
|
||||
return;
|
||||
|
||||
this.RefreshCurrentProfileAndChatTemplate();
|
||||
|
||||
// Blur the focus away from the input field to be able to clear it:
|
||||
@@ -2184,6 +2247,169 @@ public partial class ChatComponent : MSGComponentBase
|
||||
await this.ChatThreadChanged.InvokeAsync(this.ChatThread);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compresses the open chat: the AI summarizes it, and the conversation continues in a new chat.
|
||||
/// </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 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.
|
||||
/// </remarks>
|
||||
private async Task CompressCurrentChat()
|
||||
{
|
||||
if (this.ChatThread is not { } sourceChat || !this.CanThreadBeCompressed)
|
||||
return;
|
||||
|
||||
// The new chat takes the message being written along, so the draft has to say what the user wrote:
|
||||
if (this.ComposerState.HasUserDraft)
|
||||
this.MirrorComposerIntoDraft(sourceChat);
|
||||
|
||||
var exampleConversationLength = this.ExampleConversationLengthOf(sourceChat);
|
||||
var plan = ChatCompressionPlan.Of(sourceChat, exampleConversationLength, 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;
|
||||
}
|
||||
|
||||
var provider = this.Provider;
|
||||
var sourceName = ChatCompression.NameOf(sourceChat.Name);
|
||||
var storesChatFirst = 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.SuggestedName, ChatCompression.NameOfContinuation(sourceChat.Name) },
|
||||
{ x => x.StoresChatFirst, storesChatFirst },
|
||||
};
|
||||
|
||||
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;
|
||||
|
||||
// Nothing may continue a chat which is no longer the open one:
|
||||
if (this.ChatThread?.ChatId != sourceChat.ChatId || this.IsCurrentChatStreaming || this.isCompressing)
|
||||
return;
|
||||
|
||||
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 agent picked for the last request of the old one:
|
||||
this.dataSourceSelectionComponent?.ChangeOptionWithoutSaving(continuation.DataSourceOptions, continuation.AISelectedDataSources);
|
||||
this.tokenTracker?.Nudge();
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.isCompressing = false;
|
||||
this.StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Judged by the token count under the input field, the very number the user sees, so no request
|
||||
/// is made for it. That count does not cover images, and it knows no window where nobody wrote
|
||||
/// one down, e.g., for many self-hosted models; the notice then stays away, just as the number
|
||||
/// keeps its colour, see ConversationTokens.AsksBeforeSending.<br/><br/>
|
||||
///
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <returns>True when the message is to be sent.</returns>
|
||||
private async Task<bool> ConfirmContextWindowAsync()
|
||||
{
|
||||
if (!this.conversationTokens.AsksBeforeSending)
|
||||
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))
|
||||
{
|
||||
case ContextWindowFullDecision.SEND_ANYWAY:
|
||||
return true;
|
||||
|
||||
case ContextWindowFullDecision.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();
|
||||
return false;
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task LoadedChatChanged(bool notifyParent = true)
|
||||
{
|
||||
this.hasUnsavedChanges = false;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
@* Rider takes this using for unused, but without it, Razor does not recognize the event handler @oninput below, and MudSlider passes it to the DOM as an invalid attribute: *@
|
||||
@* ReSharper disable once RedundantUsingDirective *@
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@typeparam T
|
||||
@inherits ConfigurationBaseCore
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
using AIStudio.Chat;
|
||||
using AIStudio.Chat.Compression;
|
||||
using AIStudio.Chat.Embedded;
|
||||
using AIStudio.Dialogs;
|
||||
using AIStudio.Provider;
|
||||
using AIStudio.Settings.DataModel;
|
||||
using AIStudio.Tools.AssistantLaunch;
|
||||
using AIStudio.Tools.Rust;
|
||||
using AIStudio.Tools.Services;
|
||||
|
||||
@@ -22,7 +24,8 @@ namespace AIStudio.Components;
|
||||
/// shows it and renders whenever the service says it changed. What a request carries beside the conversation, such as
|
||||
/// the system prompt and the tools, the assistant decides through PrepareAsync. The count of tokens leaves out the
|
||||
/// context window of the model by default: it would tell models apart which the user compares without knowing them.
|
||||
/// An assistant whose requests carry long instructions shows it, see ShowsContextWindow.
|
||||
/// An assistant whose requests carry long instructions shows it, see ShowsContextWindow. Either way, the chat sends no
|
||||
/// message which no longer fits.
|
||||
/// </remarks>
|
||||
public partial class EmbeddedChat : MSGComponentBase
|
||||
{
|
||||
@@ -90,12 +93,37 @@ public partial class EmbeddedChat : MSGComponentBase
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the count of tokens shows how much of the context window of the model the conversation
|
||||
/// fills: it warns when most of it is used, and the chat sends no more when the next message and its answer would
|
||||
/// not fit anymore, see EmbeddedChatTokenBudget. Leave it out where the user must not tell the models apart.
|
||||
/// fills: it warns when most of it is used, and before sending a message which nearly fills the window, the chat
|
||||
/// asks what to do. Leave it out where the user must not tell the models apart.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Either way, the chat sends no message after which the next answer would not fit anymore, see
|
||||
/// EmbeddedChatTokenBudget.NoticeBeforeSending. Where it hides the window, it only says that the conversation is
|
||||
/// full, see FullContextHint.
|
||||
/// </remarks>
|
||||
[Parameter]
|
||||
public bool ShowsContextWindow { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether the chat offers to compress its conversation once it nearly fills the context window, in
|
||||
/// the notice before sending; only together with ShowsContextWindow, since the notice names the window. The summary
|
||||
/// then takes the place of the earlier messages, since the chat has no workspace to keep them in, see
|
||||
/// ChatCompressionTarget.SAME_CHAT.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// No button offers it otherwise: the earlier messages are gone afterward, so the chat offers it only when the
|
||||
/// conversation would not go on without it.
|
||||
/// </remarks>
|
||||
[Parameter]
|
||||
public bool AllowsCompression { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets what the chat says once its conversation fills the context window of the model, in place of its own
|
||||
/// advice, e.g., where the assistant offers another way on; null for the advice of the chat.
|
||||
/// </summary>
|
||||
[Parameter]
|
||||
public string? FullContextHint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets how the count of tokens gets the system prompt of the next request, for an assistant which puts it
|
||||
/// together anew for every request in PrepareAsync; null as its result means it cannot be known now, and the count
|
||||
@@ -184,6 +212,12 @@ public partial class EmbeddedChat : MSGComponentBase
|
||||
[Inject]
|
||||
private ConversationTokenCounter TokenCounter { get; init; } = null!;
|
||||
|
||||
[Inject]
|
||||
private AssistantLaunchService AssistantLaunchService { get; init; } = null!;
|
||||
|
||||
[Inject]
|
||||
private ChatCompressionService CompressionService { get; init; } = null!;
|
||||
|
||||
[Inject]
|
||||
private IDialogService DialogService { get; init; } = null!;
|
||||
|
||||
@@ -251,11 +285,36 @@ public partial class EmbeddedChat : MSGComponentBase
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, object?> inputAttributes = new();
|
||||
|
||||
/// <summary>
|
||||
/// Whether the summary of the conversation is taking the place of its earlier messages right now, see CompressAsync.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Nothing may be sent meanwhile: the message would go into the conversation which is being replaced.
|
||||
/// </remarks>
|
||||
private bool isCompressing;
|
||||
|
||||
private bool IsRunning => this.conversation?.IsRunning ?? false;
|
||||
|
||||
private EmbeddedChatTokenBudgetState Budget => this.ShowsContextWindow ? EmbeddedChatTokenBudget.Of(this.tokens) : EmbeddedChatTokenBudgetState.UNKNOWN;
|
||||
/// <summary>
|
||||
/// 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 bool CanSend => this.conversation is { IsAvailable: true, IsRunning: false } && this.ProviderIssue is null && this.Budget is not EmbeddedChatTokenBudgetState.FULL;
|
||||
/// <summary>
|
||||
/// Whether the chat offers to compress the conversation, see AllowsCompression.
|
||||
/// </summary>
|
||||
private bool OffersCompression => this.AllowsCompression && this.ShowsContextWindow;
|
||||
|
||||
/// <summary>
|
||||
/// Whether the user may send a message. Where the chat shows the context window, a full one does not stop it:
|
||||
/// sending asks what to do then, see ConfirmContextWindowAsync. Where it hides the window, nothing could be asked,
|
||||
/// so a full conversation takes no more messages.
|
||||
/// </summary>
|
||||
private bool CanSend => this.conversation is { IsAvailable: true, IsRunning: false }
|
||||
&& !this.isCompressing
|
||||
&& this.ProviderIssue is null
|
||||
&& (this.ShowsContextWindow || this.Budget is not EmbeddedChatTokenBudgetState.FULL);
|
||||
|
||||
private bool CanSendMessage => this.CanSend && !string.IsNullOrWhiteSpace(this.userInput);
|
||||
|
||||
@@ -372,7 +431,10 @@ public partial class EmbeddedChat : MSGComponentBase
|
||||
var culture = Tools.PluginSystem.I18N.I.Culture;
|
||||
var counted = TokenAmount.Format(this.tokens.Tokens, culture);
|
||||
if (!this.ShowsContextWindow)
|
||||
return string.Format(T("approx. {0} tokens"), counted);
|
||||
{
|
||||
var approximately = string.Format(T("approx. {0} tokens"), counted);
|
||||
return this.Budget is EmbeddedChatTokenBudgetState.FULL ? $"{approximately}. {this.FullContextText}" : approximately;
|
||||
}
|
||||
|
||||
if (!this.tokens.Window.IsKnown)
|
||||
return string.Format(T("approx. {0} tokens; the context window of this model is unknown"), counted);
|
||||
@@ -391,16 +453,37 @@ public partial class EmbeddedChat : MSGComponentBase
|
||||
/// <summary>
|
||||
/// Gets what the user can do once the conversation fills the context of the model.
|
||||
/// </summary>
|
||||
private string FullContextText => this.CanReset
|
||||
? TA("This conversation fills the context window of the model. Start it over, or choose a provider whose model reads more at once.")
|
||||
: TA("This conversation fills the context window of the model. Choose a provider whose model reads more at once.");
|
||||
private string FullContextText
|
||||
{
|
||||
get
|
||||
{
|
||||
if (this.FullContextHint is { } hint)
|
||||
return hint;
|
||||
|
||||
if (this.OffersCompression)
|
||||
return TA("This conversation fills the context window of the model. When you send your next message, AI Studio offers to compress the conversation.");
|
||||
|
||||
return this.CanReset
|
||||
? TA("This conversation fills the context window of the model. Start it over, or choose a provider whose model reads more at once.")
|
||||
: TA("This conversation fills the context window of the model. Choose a provider whose model reads more at once.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the warning once the conversation fills most of the context of the model.
|
||||
/// </summary>
|
||||
private string NearlyFullContextText => this.CanReset
|
||||
? TA("This conversation fills most of the context window of the model. Soon, you will have to start it over.")
|
||||
: T("This conversation fills most of the context window of the model.");
|
||||
private string NearlyFullContextText
|
||||
{
|
||||
get
|
||||
{
|
||||
if (this.OffersCompression)
|
||||
return T("This conversation fills most of the context window of the model. Once it is nearly full, AI Studio offers to compress it.");
|
||||
|
||||
return this.CanReset
|
||||
? TA("This conversation fills most of the context window of the model. Soon, you will have to start it over.")
|
||||
: T("This conversation fills most of the context window of the model.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the classes of the message field; like on the chat page, they colour its helper text with the tokens.
|
||||
@@ -427,6 +510,9 @@ public partial class EmbeddedChat : MSGComponentBase
|
||||
return;
|
||||
|
||||
var message = new ContentText { Text = this.userInput.Trim(), FileAttachments = [.. this.attachments] };
|
||||
if (!await this.ConfirmContextWindowAsync(message.Text) || !this.CanSend)
|
||||
return;
|
||||
|
||||
this.userInput = string.Empty;
|
||||
this.attachments = [];
|
||||
await this.ChatService.SendAsync(this.ChatId, this.RequestOf(message));
|
||||
@@ -441,9 +527,135 @@ public partial class EmbeddedChat : MSGComponentBase
|
||||
if (this.QuickMessage is not { } quickMessage || !this.CanSend)
|
||||
return;
|
||||
|
||||
if (!await this.ConfirmContextWindowAsync(quickMessage.Message) || !this.CanSend)
|
||||
return;
|
||||
|
||||
await this.ChatService.SendAsync(this.ChatId, this.RequestOf(new ContentText { Text = quickMessage.Message }));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asks the user what to do when a message would nearly fill the context window of the model, and compresses the
|
||||
/// conversation when the user wants to.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The count of the conversation leaves out the message being written, see RecountAsync, so the message is counted
|
||||
/// on its own here. A message after which the next answer would no longer fit is not sent at all, see
|
||||
/// EmbeddedChatTokenBudget.NoticeBeforeSending. Where the chat hides the context window, see ShowsContextWindow,
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="message">The text of the message about to be sent.</param>
|
||||
/// <returns>True when the message is to be sent.</returns>
|
||||
private async Task<bool> ConfirmContextWindowAsync(string message)
|
||||
{
|
||||
if (EmbeddedChatTokenBudget.Of(this.tokens) 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);
|
||||
if (notice is EmbeddedChatSendNotice.NONE)
|
||||
return true;
|
||||
|
||||
if (!this.ShowsContextWindow)
|
||||
{
|
||||
await this.MessageBus.SendWarning(new(AppIcons.CONTEXT_WINDOW, TA("Together with this conversation, your message no longer fits into the context window of the model. Shorten your message, or remove some of its files.")));
|
||||
return false;
|
||||
}
|
||||
|
||||
var offer = this.AllowsCompression && thread.IsLLMProviderAllowed(this.Provider)
|
||||
? await this.CompressionService.OfferBeforeSendingAsync(thread, 0, this.Provider, tokensWithMessage, this.countToken)
|
||||
: ChatCompressionOffer.NONE;
|
||||
|
||||
switch (await ContextWindowFullDialog.ShowAsync(this.DialogService, tokensWithMessage, ContextWindowFullSubject.EMBEDDED_CHAT, offer, canSendAnyway: notice is EmbeddedChatSendNotice.NEARLY_FULL))
|
||||
{
|
||||
case ContextWindowFullDecision.SEND_ANYWAY:
|
||||
return true;
|
||||
|
||||
case ContextWindowFullDecision.COMPRESS:
|
||||
await this.CompressAsync();
|
||||
return false;
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Counts the tokens of a message about to be sent.
|
||||
/// </summary>
|
||||
/// <param name="message">The text of the message.</param>
|
||||
/// <returns>The tokens; 0 when they could not be counted, so that the notice judges by the conversation alone.</returns>
|
||||
private async Task<int> CountMessageAsync(string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await this.TokenCounter.CountTextAsync(this.Provider, message, this.countToken);
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException)
|
||||
{
|
||||
this.Logger.LogWarning(exception, "Could not count the tokens of a message of the embedded chat '{ChatId}'.", this.ChatId);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compresses the conversation: the AI summarizes it, and the summary takes the place of the earlier messages.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The chat lives in a store of its assistant rather than in a workspace, so there is no place to keep the earlier
|
||||
/// messages: they give way to the summary, which the dialog says beforehand, see ChatCompressionTarget.SAME_CHAT.
|
||||
/// The last message of the user and the last answer stay as they are. The summary passes the prompt injection
|
||||
/// 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()
|
||||
{
|
||||
if (this.conversation is not { Thread: { } thread, IsRunning: false })
|
||||
return;
|
||||
|
||||
// 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;
|
||||
|
||||
var dialogParameters = new DialogParameters<ChatCompressionDialog>
|
||||
{
|
||||
{ x => x.SourceChat, thread },
|
||||
{ x => x.Plan, plan },
|
||||
{ x => x.ProviderSettings, this.Provider },
|
||||
{ x => x.Target, ChatCompressionTarget.SAME_CHAT },
|
||||
};
|
||||
|
||||
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;
|
||||
|
||||
this.isCompressing = true;
|
||||
try
|
||||
{
|
||||
var sourceName = ChatCompression.NameOf(thread.Name);
|
||||
var payload = await this.AssistantLaunchService.CreateTextPayloadAsync(result.Summary, writtenByModel: true, thread.CaptureRestrictions(), sourceName);
|
||||
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.")));
|
||||
}
|
||||
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.")));
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.isCompressing = false;
|
||||
this.StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lets the model open the conversation, see StartRequest.
|
||||
/// </summary>
|
||||
|
||||
@@ -704,6 +704,24 @@ public partial class Workspaces : MSGComponentBase
|
||||
return copy;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies the given chat under the given name, changes the copy before it is stored, and shows the copy in the tree.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// For a caller which already knows the name, such as compressing a chat. Like
|
||||
/// CopyChatAsync(ChatThread), it neither asks about unsaved changes nor opens the copy.
|
||||
/// </remarks>
|
||||
/// <param name="sourceChat">The chat to copy, as it stands in memory.</param>
|
||||
/// <param name="name">The name of the copy.</param>
|
||||
/// <param name="reshape">Changes the copy before it is stored, see WorkspaceBehaviour.CopyChatAsync.</param>
|
||||
/// <returns>The persisted copy.</returns>
|
||||
public async Task<ChatThread> CopyChatAsync(ChatThread sourceChat, string name, Action<ChatThread> reshape)
|
||||
{
|
||||
var copy = await WorkspaceBehaviour.CopyChatAsync(sourceChat, name, reshape);
|
||||
await this.LoadTreeItemsAsync(startPrefetch: false);
|
||||
return copy;
|
||||
}
|
||||
|
||||
private async Task<ChatThread?> LoadChatAsync(string? chatPath, bool switchToChat)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(chatPath))
|
||||
|
||||
Reference in new issue
Block a user