AI-Studio/app/MindWork AI Studio/Assistants/AssistantBase.razor.cs

347 lines
11 KiB
C#
Raw Normal View History

2024-07-14 19:46:17 +00:00
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Settings;
using Microsoft.AspNetCore.Components;
2024-09-01 18:10:03 +00:00
using RustService = AIStudio.Tools.RustService;
2024-08-21 06:30:01 +00:00
namespace AIStudio.Assistants;
2024-07-14 19:46:17 +00:00
public abstract partial class AssistantBase : ComponentBase, IMessageBusReceiver, IDisposable
2024-07-14 19:46:17 +00:00
{
[Inject]
2024-09-01 18:10:03 +00:00
protected SettingsManager SettingsManager { get; init; } = null!;
2024-07-14 19:46:17 +00:00
[Inject]
protected IJSRuntime JsRuntime { get; init; } = null!;
[Inject]
protected ThreadSafeRandom RNG { get; init; } = null!;
2024-07-14 19:46:17 +00:00
[Inject]
protected ISnackbar Snackbar { get; init; } = null!;
[Inject]
2024-09-01 18:10:03 +00:00
protected RustService RustService { get; init; } = null!;
2024-08-18 10:32:18 +00:00
[Inject]
protected NavigationManager NavigationManager { get; init; } = null!;
2024-09-01 18:10:03 +00:00
[Inject]
protected ILogger<AssistantBase> Logger { get; init; } = null!;
[Inject]
private MudTheme ColorTheme { get; init; } = null!;
[Inject]
private MessageBus MessageBus { get; init; } = null!;
2024-08-21 06:30:01 +00:00
internal const string RESULT_DIV_ID = "assistantResult";
internal const string BEFORE_RESULT_DIV_ID = "beforeAssistantResult";
internal const string AFTER_RESULT_DIV_ID = "afterAssistantResult";
2024-07-14 19:46:17 +00:00
protected abstract string Title { get; }
protected abstract string Description { get; }
protected abstract string SystemPrompt { get; }
public abstract Tools.Components Component { get; }
2024-09-04 13:44:23 +00:00
protected virtual Func<string> Result2Copy => () => this.resultingContentBlock is null ? string.Empty : this.resultingContentBlock.Content switch
{
ContentText textBlock => textBlock.Text,
_ => string.Empty,
};
2024-08-18 19:48:35 +00:00
protected abstract void ResetFrom();
protected abstract bool MightPreselectValues();
2024-07-14 19:46:17 +00:00
2024-09-11 21:08:02 +00:00
protected abstract string SubmitText { get; }
protected abstract Func<Task> SubmitAction { get; }
protected virtual bool SubmitDisabled => false;
2024-07-14 19:46:17 +00:00
private protected virtual RenderFragment? Body => null;
protected virtual bool ShowResult => true;
2024-09-08 19:01:51 +00:00
protected virtual bool AllowProfiles => true;
protected virtual bool ShowProfileSelection => true;
protected virtual bool ShowDedicatedProgress => false;
2024-10-28 14:41:00 +00:00
protected virtual bool ShowSendTo => true;
protected virtual bool ShowCopyResult => true;
protected virtual bool ShowReset => true;
2024-08-18 19:48:35 +00:00
protected virtual ChatThread ConvertToChatThread => this.chatThread ?? new();
2024-08-18 10:32:18 +00:00
protected virtual IReadOnlyList<IButtonData> FooterButtons => [];
protected static readonly Dictionary<string, object?> USER_INPUT_ATTRIBUTES = new();
2024-07-16 08:28:13 +00:00
protected AIStudio.Settings.Provider providerSettings;
2024-07-14 19:46:17 +00:00
protected MudForm? form;
protected bool inputIsValid;
protected Profile currentProfile = Profile.NO_PROFILE;
2024-07-14 19:46:17 +00:00
2024-08-18 19:48:35 +00:00
protected ChatThread? chatThread;
2024-07-14 19:46:17 +00:00
private ContentBlock? resultingContentBlock;
private string[] inputIssues = [];
private bool isProcessing;
2024-07-14 19:46:17 +00:00
#region Overrides of ComponentBase
2024-09-04 13:44:23 +00:00
protected override async Task OnInitializedAsync()
{
this.MightPreselectValues();
this.providerSettings = this.SettingsManager.GetPreselectedProvider(this.Component);
2024-09-08 19:01:51 +00:00
this.currentProfile = this.SettingsManager.GetPreselectedProfile(this.Component);
this.MessageBus.RegisterComponent(this);
this.MessageBus.ApplyFilters(this, [], [ Event.COLOR_THEME_CHANGED ]);
2024-09-04 13:44:23 +00:00
await base.OnInitializedAsync();
}
protected override async Task OnParametersSetAsync()
{
// Configure the spellchecking for the user input:
this.SettingsManager.InjectSpellchecking(USER_INPUT_ATTRIBUTES);
await base.OnParametersSetAsync();
}
2024-07-14 19:46:17 +00:00
protected override async Task OnAfterRenderAsync(bool firstRender)
{
// Reset the validation when not editing and on the first render.
// We don't want to show validation errors when the user opens the dialog.
if(firstRender)
this.form?.ResetValidation();
await base.OnAfterRenderAsync(firstRender);
}
#endregion
#region Implementation of IMessageBusReceiver
public Task ProcessMessage<T>(ComponentBase? sendingComponent, Event triggeredEvent, T? data)
{
switch (triggeredEvent)
{
case Event.COLOR_THEME_CHANGED:
this.StateHasChanged();
break;
}
return Task.CompletedTask;
}
public Task<TResult?> ProcessMessageWithResult<TPayload, TResult>(ComponentBase? sendingComponent, Event triggeredEvent, TPayload? data)
{
return Task.FromResult<TResult?>(default);
}
2024-07-14 19:46:17 +00:00
#endregion
2024-09-11 21:08:02 +00:00
private string SubmitButtonStyle => this.SettingsManager.ConfigurationData.LLMProviders.ShowProviderConfidence ? this.providerSettings.UsedLLMProvider.GetConfidence(this.SettingsManager).StyleBorder(this.SettingsManager) : string.Empty;
2024-07-14 19:46:17 +00:00
2024-07-16 18:06:04 +00:00
protected string? ValidatingProvider(AIStudio.Settings.Provider provider)
{
if(provider.UsedLLMProvider == LLMProviders.NONE)
2024-07-16 18:06:04 +00:00
return "Please select a provider.";
return null;
}
2024-07-14 19:46:17 +00:00
protected void CreateChatThread()
{
this.chatThread = new()
{
2024-11-23 12:04:02 +00:00
SelectedProvider = this.providerSettings.Id,
2024-07-14 19:46:17 +00:00
WorkspaceId = Guid.Empty,
ChatId = Guid.NewGuid(),
Name = string.Empty,
Seed = this.RNG.Next(),
2024-09-08 19:01:51 +00:00
SystemPrompt = !this.AllowProfiles ? this.SystemPrompt :
$"""
{this.SystemPrompt}
{this.currentProfile.ToSystemPrompt()}
""",
2024-07-14 19:46:17 +00:00
Blocks = [],
};
}
2024-10-28 14:41:00 +00:00
protected Guid CreateChatThread(Guid workspaceId, string name)
{
var chatId = Guid.NewGuid();
this.chatThread = new()
{
2024-11-23 12:04:02 +00:00
SelectedProvider = this.providerSettings.Id,
2024-10-28 14:41:00 +00:00
WorkspaceId = workspaceId,
ChatId = chatId,
Name = name,
Seed = this.RNG.Next(),
SystemPrompt = !this.AllowProfiles ? this.SystemPrompt :
$"""
{this.SystemPrompt}
{this.currentProfile.ToSystemPrompt()}
""",
Blocks = [],
};
return chatId;
}
2024-07-14 19:46:17 +00:00
2024-10-28 14:41:00 +00:00
protected DateTimeOffset AddUserRequest(string request, bool hideContentFromUser = false)
2024-07-14 19:46:17 +00:00
{
var time = DateTimeOffset.Now;
this.chatThread!.Blocks.Add(new ContentBlock
{
Time = time,
ContentType = ContentType.TEXT,
2024-10-28 14:41:00 +00:00
HideFromUser = hideContentFromUser,
2024-07-14 19:46:17 +00:00
Role = ChatRole.USER,
Content = new ContentText
{
Text = request,
},
});
return time;
}
protected async Task<string> AddAIResponseAsync(DateTimeOffset time)
2024-07-14 19:46:17 +00:00
{
var aiText = new ContentText
{
// We have to wait for the remote
// for the content stream:
InitialRemoteWait = true,
};
this.resultingContentBlock = new ContentBlock
{
Time = time,
ContentType = ContentType.TEXT,
Role = ChatRole.AI,
Content = aiText,
};
2024-11-23 12:04:02 +00:00
if (this.chatThread is not null)
{
this.chatThread.Blocks.Add(this.resultingContentBlock);
this.chatThread.SelectedProvider = this.providerSettings.Id;
}
this.isProcessing = true;
this.StateHasChanged();
2024-07-14 19:46:17 +00:00
// Use the selected provider to get the AI response.
// By awaiting this line, we wait for the entire
// content to be streamed.
2024-09-01 18:10:03 +00:00
await aiText.CreateFromProviderAsync(this.providerSettings.CreateProvider(this.Logger), this.SettingsManager, this.providerSettings.Model, this.chatThread);
this.isProcessing = false;
this.StateHasChanged();
// Return the AI response:
return aiText.Text;
}
protected async Task CopyToClipboard()
{
2024-09-01 18:10:03 +00:00
await this.RustService.CopyText2Clipboard(this.Snackbar, this.Result2Copy());
}
private static string? GetButtonIcon(string icon)
{
if(string.IsNullOrWhiteSpace(icon))
return null;
return icon;
2024-07-14 19:46:17 +00:00
}
2024-08-18 10:32:18 +00:00
2024-10-28 14:41:00 +00:00
protected Task SendToAssistant(Tools.Components destination, SendToButton sendToButton)
2024-08-18 10:32:18 +00:00
{
if (!destination.AllowSendTo())
return Task.CompletedTask;
2024-10-28 14:41:00 +00:00
var contentToSend = sendToButton == default ? string.Empty : sendToButton.UseResultingContentBlockData switch
2024-08-18 10:32:18 +00:00
{
2024-08-18 19:48:35 +00:00
false => sendToButton.GetText(),
2024-08-18 10:32:18 +00:00
true => this.resultingContentBlock?.Content switch
{
ContentText textBlock => textBlock.Text,
_ => string.Empty,
},
};
var sendToData = destination.GetData();
2024-08-18 19:48:35 +00:00
switch (destination)
{
2024-09-04 13:44:23 +00:00
case Tools.Components.CHAT:
2024-11-23 12:04:02 +00:00
var convertedChatThread = this.ConvertToChatThread;
convertedChatThread = convertedChatThread with { SelectedProvider = this.providerSettings.Id };
MessageBus.INSTANCE.DeferMessage(this, sendToData.Event, convertedChatThread);
2024-08-18 19:48:35 +00:00
break;
default:
MessageBus.INSTANCE.DeferMessage(this, sendToData.Event, contentToSend);
2024-08-18 19:48:35 +00:00
break;
}
this.NavigationManager.NavigateTo(sendToData.Route);
2024-08-18 10:32:18 +00:00
return Task.CompletedTask;
}
2024-08-18 19:48:35 +00:00
private async Task InnerResetForm()
{
this.resultingContentBlock = null;
this.providerSettings = default;
2024-08-21 06:30:01 +00:00
await this.JsRuntime.ClearDiv(RESULT_DIV_ID);
2024-08-18 19:48:35 +00:00
await this.JsRuntime.ClearDiv(AFTER_RESULT_DIV_ID);
this.ResetFrom();
2024-09-04 13:44:23 +00:00
this.providerSettings = this.SettingsManager.GetPreselectedProvider(this.Component);
2024-08-18 19:48:35 +00:00
this.inputIsValid = false;
this.inputIssues = [];
this.form?.ResetValidation();
this.StateHasChanged();
this.form?.ResetValidation();
}
private string GetResetColor() => this.SettingsManager.IsDarkMode switch
{
true => $"background-color: #804000",
false => $"background-color: {this.ColorTheme.GetCurrentPalette(this.SettingsManager).Warning.Value}",
};
private string GetSendToColor() => this.SettingsManager.IsDarkMode switch
{
true => $"background-color: #004080",
false => $"background-color: {this.ColorTheme.GetCurrentPalette(this.SettingsManager).InfoLighten}",
};
#region Implementation of IDisposable
public void Dispose()
{
this.MessageBus.Unregister(this);
}
#endregion
2024-07-14 19:46:17 +00:00
}