Compare commits

...
10 Commits
106 changed files with 5676 additions and 455 deletions

No files matched your search

+6 -4
View File
@@ -15,7 +15,7 @@ Things we are currently working on:
- [x] ~~App: Management of data sources (local & external data via [ERI](https://github.com/MindWorkAI/ERI)) (PR [#259](https://github.com/MindWorkAI/AI-Studio/pull/259), [#273](https://github.com/MindWorkAI/AI-Studio/pull/273))~~
- [x] ~~Runtime: Extract data from txt / md / pdf / docx / xlsx files (PR [#374](https://github.com/MindWorkAI/AI-Studio/pull/374))~~
- [ ] (*Optional*) Runtime: Implement internal embedding provider through [fastembed-rs](https://github.com/Anush008/fastembed-rs)
- [ ] App: Implement dialog for checking & handling [pandoc](https://pandoc.org/) installation ([PR #393](https://github.com/MindWorkAI/AI-Studio/pull/393))
- [x] ~~App: Implement dialog for checking & handling [pandoc](https://pandoc.org/) installation ([PR #393](https://github.com/MindWorkAI/AI-Studio/pull/393), [PR #487](https://github.com/MindWorkAI/AI-Studio/pull/487))~~
- [ ] App: Implement external embedding providers
- [ ] App: Implement the process to vectorize one local file using embeddings
- [ ] Runtime: Integration of the vector database [LanceDB](https://github.com/lancedb/lancedb)
@@ -31,10 +31,10 @@ Things we are currently working on:
- [x] ~~Plan & implement the base plugin system ([PR #322](https://github.com/MindWorkAI/AI-Studio/pull/322))~~
- [x] ~~Start the plugin system ([PR #372](https://github.com/MindWorkAI/AI-Studio/pull/372))~~
- [x] ~~Added hot-reload support for plugins ([PR #377](https://github.com/MindWorkAI/AI-Studio/pull/377), [PR #391](https://github.com/MindWorkAI/AI-Studio/pull/391))~~
- [ ] Add support for other languages (I18N) to AI Studio (~~[PR #381](https://github.com/MindWorkAI/AI-Studio/pull/381), [PR #400](https://github.com/MindWorkAI/AI-Studio/pull/400), [PR #404](https://github.com/MindWorkAI/AI-Studio/pull/404), [PR #429](https://github.com/MindWorkAI/AI-Studio/pull/429), [PR #446](https://github.com/MindWorkAI/AI-Studio/pull/446), [PR #451](https://github.com/MindWorkAI/AI-Studio/pull/451), [PR #455](https://github.com/MindWorkAI/AI-Studio/pull/455), [PR #458](https://github.com/MindWorkAI/AI-Studio/pull/458), [PR #462](https://github.com/MindWorkAI/AI-Studio/pull/462), [PR #469](https://github.com/MindWorkAI/AI-Studio/pull/469))~~
- [x] ~~Add support for other languages (I18N) to AI Studio ([PR #381](https://github.com/MindWorkAI/AI-Studio/pull/381), [PR #400](https://github.com/MindWorkAI/AI-Studio/pull/400), [PR #404](https://github.com/MindWorkAI/AI-Studio/pull/404), [PR #429](https://github.com/MindWorkAI/AI-Studio/pull/429), [PR #446](https://github.com/MindWorkAI/AI-Studio/pull/446), [PR #451](https://github.com/MindWorkAI/AI-Studio/pull/451), [PR #455](https://github.com/MindWorkAI/AI-Studio/pull/455), [PR #458](https://github.com/MindWorkAI/AI-Studio/pull/458), [PR #462](https://github.com/MindWorkAI/AI-Studio/pull/462), [PR #469](https://github.com/MindWorkAI/AI-Studio/pull/469), [PR #486](https://github.com/MindWorkAI/AI-Studio/pull/486))~~
- [x] ~~Add an I18N assistant to translate all AI Studio texts to a certain language & culture ([PR #422](https://github.com/MindWorkAI/AI-Studio/pull/422))~~
- [ ] Provide MindWork AI Studio in German (~~[PR #430](https://github.com/MindWorkAI/AI-Studio/pull/430), [PR #446](https://github.com/MindWorkAI/AI-Studio/pull/446), [PR #451](https://github.com/MindWorkAI/AI-Studio/pull/451), [PR #455](https://github.com/MindWorkAI/AI-Studio/pull/455), [PR #458](https://github.com/MindWorkAI/AI-Studio/pull/458), [PR #462](https://github.com/MindWorkAI/AI-Studio/pull/462), [PR #469](https://github.com/MindWorkAI/AI-Studio/pull/469)~~)
- [ ] Add configuration plugins, which allow pre-defining some LLM providers in organizations
- [x] ~~Provide MindWork AI Studio in German ([PR #430](https://github.com/MindWorkAI/AI-Studio/pull/430), [PR #446](https://github.com/MindWorkAI/AI-Studio/pull/446), [PR #451](https://github.com/MindWorkAI/AI-Studio/pull/451), [PR #455](https://github.com/MindWorkAI/AI-Studio/pull/455), [PR #458](https://github.com/MindWorkAI/AI-Studio/pull/458), [PR #462](https://github.com/MindWorkAI/AI-Studio/pull/462), [PR #469](https://github.com/MindWorkAI/AI-Studio/pull/469), [PR #486](https://github.com/MindWorkAI/AI-Studio/pull/486)~~)
- [ ] Add configuration plugins, which allow pre-defining some LLM providers in organizations (~~[PR #491](https://github.com/MindWorkAI/AI-Studio/pull/491)~~)
- [ ] Add an app store for plugins, showcasing community-contributed plugins from public GitHub and GitLab repositories. This will enable AI Studio users to discover, install, and update plugins directly within the platform.
- [ ] Add assistant plugins
@@ -47,6 +47,8 @@ Other News:
Features we have recently released:
- v0.9.46: Released our plugin system, a German language plugin, early support for enterprise environments, and configuration plugins. Additionally, we added the Pandoc integration for future data processing and file generation.
- v0.9.45: Added chat templates to AI Studio, allowing you to create and use a library of system prompts for your chats.
- v0.9.44: Added PDF import to the text summarizer, translation, and legal check assistants, allowing you to import PDF files and use them as input for the assistants.
- v0.9.40: Added support for the `o4` models from OpenAI. Also, we added Alibaba Cloud & Hugging Face as LLM providers.
- v0.9.39: Added the plugin system as a preview feature.
+1 -1
View File
@@ -48,7 +48,7 @@ public static class Pdfium
//
Console.Write(" deploying ...");
var library = GetLibraryPath(rid);
if (string.IsNullOrEmpty(library.Path))
if (string.IsNullOrWhiteSpace(library.Path))
{
Console.WriteLine($" failed to find the library path for {rid.ToUserFriendlyName()}");
return;
@@ -2,22 +2,24 @@ namespace AIStudio.Assistants.Agenda;
public static class NumberParticipantsExtensions
{
private static string TB(string fallbackEN) => Tools.PluginSystem.I18N.I.T(fallbackEN, typeof(NumberParticipantsExtensions).Namespace, nameof(NumberParticipantsExtensions));
public static string Name(this NumberParticipants numberParticipants) => numberParticipants switch
{
NumberParticipants.NOT_SPECIFIED => "Please select how many participants are expected",
NumberParticipants.NOT_SPECIFIED => TB("Please select how many participants are expected"),
NumberParticipants.PEER_TO_PEER => "2 (peer to peer)",
NumberParticipants.PEER_TO_PEER => TB("2 (peer to peer)"),
NumberParticipants.SMALL_GROUP => "3 - 5 (small group)",
NumberParticipants.LARGE_GROUP => "6 - 12 (large group)",
NumberParticipants.MULTIPLE_SMALL_GROUPS => "13 - 20 (multiple small groups)",
NumberParticipants.MULTIPLE_LARGE_GROUPS => "21 - 30 (multiple large groups)",
NumberParticipants.SMALL_GROUP => TB("3 - 5 (small group)"),
NumberParticipants.LARGE_GROUP => TB("6 - 12 (large group)"),
NumberParticipants.MULTIPLE_SMALL_GROUPS => TB("13 - 20 (multiple small groups)"),
NumberParticipants.MULTIPLE_LARGE_GROUPS => TB("21 - 30 (multiple large groups)"),
NumberParticipants.SYMPOSIUM => "31 - 100 (symposium)",
NumberParticipants.CONFERENCE => "101 - 200 (conference)",
NumberParticipants.CONGRESS => "201 - 1,000 (congress)",
NumberParticipants.SYMPOSIUM => TB("31 - 100 (symposium)"),
NumberParticipants.CONFERENCE => TB("101 - 200 (conference)"),
NumberParticipants.CONGRESS => TB("201 - 1,000 (congress)"),
NumberParticipants.LARGE_EVENT => "1,000+ (large event)",
NumberParticipants.LARGE_EVENT => TB("1,000+ (large event)"),
_ => "Unknown"
};
@@ -6,22 +6,22 @@
{
var codingContext = this.codingContexts[contextIndex];
var index = contextIndex;
<ExpansionPanel HeaderText="@codingContext.Id" HeaderIcon="@Icons.Material.Filled.Code" ShowEndButton="@true" EndButtonColor="Color.Error" EndButtonIcon="@Icons.Material.Filled.Delete" EndButtonTooltip="Delete context" EndButtonClickAsync="@(() => this.DeleteContext(index))">
<ExpansionPanel HeaderText="@codingContext.Id" HeaderIcon="@Icons.Material.Filled.Code" ShowEndButton="@true" EndButtonColor="Color.Error" EndButtonIcon="@Icons.Material.Filled.Delete" EndButtonTooltip="@T("Delete context")" EndButtonClickAsync="@(() => this.DeleteContext(index))">
<CodingContextItem @bind-CodingContext="@codingContext"/>
</ExpansionPanel>
}
</MudExpansionPanels>
<MudButton Variant="Variant.Filled" OnClick="() => this.AddCodingContext()" Class="mb-3">
Add context
@T("Add context")
</MudButton>
<MudStack Row="@false" Class="mb-3">
<MudTextSwitch Label="Do you want to provide compiler messages?" @bind-Value="@this.provideCompilerMessages" LabelOn="Yes, provide compiler messages" LabelOff="No, there are no compiler messages" />
<MudTextSwitch Label="@T("Do you want to provide compiler messages?")" @bind-Value="@this.provideCompilerMessages" LabelOn="@T("Yes, provide compiler messages")" LabelOff="@T("No, there are no compiler messages")" />
@if (this.provideCompilerMessages)
{
<MudTextField T="string" @bind-Text="@this.compilerMessages" Validation="@this.ValidatingCompilerMessages" AdornmentIcon="@Icons.Material.Filled.Error" Adornment="Adornment.Start" Label="Compiler messages" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudTextField T="string" @bind-Text="@this.compilerMessages" Validation="@this.ValidatingCompilerMessages" AdornmentIcon="@Icons.Material.Filled.Error" Adornment="Adornment.Start" Label="@T("Compiler messages")" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
}
</MudStack>
<MudTextField T="string" @bind-Text="@this.questions" Validation="@this.ValidateQuestions" AdornmentIcon="@Icons.Material.Filled.QuestionMark" Adornment="Adornment.Start" Label="Your question(s)" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudTextField T="string" @bind-Text="@this.questions" Validation="@this.ValidateQuestions" AdornmentIcon="@Icons.Material.Filled.QuestionMark" Adornment="Adornment.Start" Label="@T("Your question(s)")" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<ProviderSelection @bind-ProviderSettings="@this.providerSettings" ValidateProvider="@this.ValidatingProvider"/>
@@ -8,14 +8,9 @@ public partial class AssistantCoding : AssistantBaseCore<SettingsDialogCoding>
{
public override Tools.Components Component => Tools.Components.CODING_ASSISTANT;
protected override string Title => "Coding Assistant";
protected override string Title => T("Coding Assistant");
protected override string Description =>
"""
This coding assistant supports you in writing code. Provide some coding context by copying and pasting
your code into the input fields. You might assign an ID to your code snippet to easily reference it later.
When you have compiler messages, you can paste them into the input fields to get help with debugging as well.
""";
protected override string Description => T("This coding assistant supports you in writing code. Provide some coding context by copying and pasting your code into the input fields. You might assign an ID to your code snippet to easily reference it later. When you have compiler messages, you can paste them into the input fields to get help with debugging as well.");
protected override string SystemPrompt =>
"""
@@ -30,7 +25,7 @@ public partial class AssistantCoding : AssistantBaseCore<SettingsDialogCoding>
protected override IReadOnlyList<IButtonData> FooterButtons => [];
protected override string SubmitText => "Get Support";
protected override string SubmitText => T("Get Support");
protected override Func<Task> SubmitAction => this.GetSupport;
@@ -80,7 +75,7 @@ public partial class AssistantCoding : AssistantBaseCore<SettingsDialogCoding>
return null;
if(string.IsNullOrWhiteSpace(checkCompilerMessages))
return "Please provide the compiler messages.";
return T("Please provide the compiler messages.");
return null;
}
@@ -88,7 +83,7 @@ public partial class AssistantCoding : AssistantBaseCore<SettingsDialogCoding>
private string? ValidateQuestions(string checkQuestions)
{
if(string.IsNullOrWhiteSpace(checkQuestions))
return "Please provide your questions.";
return T("Please provide your questions.");
return null;
}
@@ -97,7 +92,7 @@ public partial class AssistantCoding : AssistantBaseCore<SettingsDialogCoding>
{
this.codingContexts.Add(new()
{
Id = $"Context {this.codingContexts.Count + 1}",
Id = string.Format(T("Context {0}"), this.codingContexts.Count + 1),
Language = this.SettingsManager.ConfigurationData.Coding.PreselectOptions ? this.SettingsManager.ConfigurationData.Coding.PreselectedProgrammingLanguage : default,
OtherLanguage = this.SettingsManager.ConfigurationData.Coding.PreselectOptions ? this.SettingsManager.ConfigurationData.Coding.PreselectedOtherProgrammingLanguage : string.Empty,
});
@@ -1,14 +1,18 @@
<MudTextField T="string" @bind-Text="@this.CodingContext.Id" AdornmentIcon="@Icons.Material.Filled.Numbers" Adornment="Adornment.Start" Label="(Optional) Identifier" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
@inherits MSGComponentBase
<MudTextField T="string" @bind-Text="@this.CodingContext.Id" AdornmentIcon="@Icons.Material.Filled.Numbers" Adornment="Adornment.Start" Label="@T("(Optional) Identifier")" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudStack Row="@true" Class="mb-3">
<MudSelect T="CommonCodingLanguages" @bind-Value="@this.CodingContext.Language" AdornmentIcon="@Icons.Material.Filled.Code" Adornment="Adornment.Start" Label="Language" Variant="Variant.Outlined" Margin="Margin.Dense">
<MudSelect T="CommonCodingLanguages" @bind-Value="@this.CodingContext.Language" AdornmentIcon="@Icons.Material.Filled.Code" Adornment="Adornment.Start" Label="@T("Language")" Variant="Variant.Outlined" Margin="Margin.Dense">
@foreach (var language in Enum.GetValues<CommonCodingLanguages>())
{
<MudSelectItem Value="@language">@language.Name()</MudSelectItem>
<MudSelectItem Value="@language">
@language.Name()
</MudSelectItem>
}
</MudSelect>
@if (this.CodingContext.Language is CommonCodingLanguages.OTHER)
{
<MudTextField T="string" @bind-Text="@this.CodingContext.OtherLanguage" Validation="@this.ValidatingOtherLanguage" Label="Other language" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudTextField T="string" @bind-Text="@this.CodingContext.OtherLanguage" Validation="@this.ValidatingOtherLanguage" Label="@T("Other language")" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
}
</MudStack>
<MudTextField T="string" @bind-Text="@this.CodingContext.Code" Validation="@this.ValidatingCode" AdornmentIcon="@Icons.Material.Filled.DocumentScanner" Adornment="Adornment.Start" Label="Your code" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES" />
<MudTextField T="string" @bind-Text="@this.CodingContext.Code" Validation="@this.ValidatingCode" AdornmentIcon="@Icons.Material.Filled.DocumentScanner" Adornment="Adornment.Start" Label="@T("Your code")" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES" />
@@ -1,19 +1,16 @@
using AIStudio.Settings;
using AIStudio.Components;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Assistants.Coding;
public partial class CodingContextItem : ComponentBase
public partial class CodingContextItem : MSGComponentBase
{
[Parameter]
public CodingContext CodingContext { get; set; } = new();
[Parameter]
public EventCallback<CodingContext> CodingContextChanged { get; set; }
[Inject]
protected SettingsManager SettingsManager { get; set; } = null!;
private static readonly Dictionary<string, object?> USER_INPUT_ATTRIBUTES = new();
@@ -32,7 +29,7 @@ public partial class CodingContextItem : ComponentBase
private string? ValidatingCode(string code)
{
if(string.IsNullOrWhiteSpace(code))
return $"{this.CodingContext.Id}: Please provide your input.";
return string.Format(T("{0}: Please provide your input."), this.CodingContext.Id);
return null;
}
@@ -43,7 +40,7 @@ public partial class CodingContextItem : ComponentBase
return null;
if(string.IsNullOrWhiteSpace(language))
return "Please specify the language.";
return T("Please specify the language.");
return null;
}
@@ -2,9 +2,11 @@
public static class CommonCodingLanguageExtensions
{
private static string TB(string fallbackEN) => Tools.PluginSystem.I18N.I.T(fallbackEN, typeof(CommonCodingLanguageExtensions).Namespace, nameof(CommonCodingLanguageExtensions));
public static string Name(this CommonCodingLanguages language) => language switch
{
CommonCodingLanguages.NONE => "None",
CommonCodingLanguages.NONE => TB("None"),
CommonCodingLanguages.BASH => "Bash",
CommonCodingLanguages.BLAZOR => ".NET Blazor",
@@ -37,7 +39,7 @@ public static class CommonCodingLanguageExtensions
CommonCodingLanguages.TYPESCRIPT => "TypeScript",
CommonCodingLanguages.XML => "XML",
CommonCodingLanguages.OTHER => "Other",
_ => "Unknown"
CommonCodingLanguages.OTHER => TB("Other"),
_ => TB("Unknown")
};
}
@@ -2,12 +2,14 @@ namespace AIStudio.Assistants.ERI;
public static class AllowedLLMProvidersExtensions
{
private static string TB(string fallbackEN) => Tools.PluginSystem.I18N.I.T(fallbackEN, typeof(AllowedLLMProvidersExtensions).Namespace, nameof(AllowedLLMProvidersExtensions));
public static string Description(this AllowedLLMProviders provider) => provider switch
{
AllowedLLMProviders.NONE => "Please select what kind of LLM provider are allowed for this data source",
AllowedLLMProviders.ANY => "Any LLM provider is allowed: users might choose a cloud-based or a self-hosted provider",
AllowedLLMProviders.SELF_HOSTED => "Self-hosted LLM providers are allowed: users cannot choose any cloud-based provider",
AllowedLLMProviders.NONE => TB("Please select what kind of LLM provider are allowed for this data source"),
AllowedLLMProviders.ANY => TB("Any LLM provider is allowed: users might choose a cloud-based or a self-hosted provider"),
AllowedLLMProviders.SELF_HOSTED => TB("Self-hosted LLM providers are allowed: users cannot choose any cloud-based provider"),
_ => "Unknown option was selected"
_ => TB("Unknown option was selected")
};
}
@@ -4,36 +4,38 @@
@inherits AssistantBaseCore<AIStudio.Dialogs.Settings.SettingsDialogERIServer>
<MudJustifiedText Typo="Typo.body1" Class="mb-3">
You can imagine it like this: Hypothetically, when Wikipedia implemented the ERI, it would vectorize
all pages using an embedding method. All of Wikipedia’s data would remain with Wikipedia, including the
vector database (decentralized approach). Then, any AI Studio user could add Wikipedia as a data source to
significantly reduce the hallucination of the LLM in knowledge questions.
@T("You can imagine it like this: Hypothetically, when Wikipedia implemented the ERI, it would vectorize all pages using an embedding method. All of Wikipedia’s data would remain with Wikipedia, including the vector database (decentralized approach). Then, any AI Studio user could add Wikipedia as a data source to significantly reduce the hallucination of the LLM in knowledge questions.")
</MudJustifiedText>
<MudText Typo="Typo.body1">
<b>Related links:</b>
<b>
@T("Related links:")
</b>
</MudText>
<MudList T="string" Class="mb-6">
<MudListItem T="string" Icon="@Icons.Material.Filled.Link" Target="_blank" Href="https://github.com/MindWorkAI/ERI">ERI repository with example implementation in .NET and C#</MudListItem>
<MudListItem T="string" Icon="@Icons.Material.Filled.Link" Target="_blank" Href="https://mindworkai.org/swagger-ui.html">Interactive documentation aka Swagger UI</MudListItem>
<MudListItem T="string" Icon="@Icons.Material.Filled.Link" Target="_blank" Href="https://github.com/MindWorkAI/ERI">
@T("ERI repository with example implementation in .NET and C#")
</MudListItem>
<MudListItem T="string" Icon="@Icons.Material.Filled.Link" Target="_blank" Href="https://mindworkai.org/swagger-ui.html">
@T("Interactive documentation aka Swagger UI")
</MudListItem>
</MudList>
<PreviewPrototype/>
<div class="mb-6"></div>
<MudText Typo="Typo.h4" Class="mb-3">
ERI server presets
@T("ERI server presets")
</MudText>
<MudJustifiedText Typo="Typo.body1" Class="mb-3">
Here you have the option to save different configurations for various ERI servers and switch between them. This is useful if
you are responsible for multiple ERI servers.
@T("Here you have the option to save different configurations for various ERI servers and switch between them. This is useful if you are responsible for multiple ERI servers.")
</MudJustifiedText>
@if(this.SettingsManager.ConfigurationData.ERI.ERIServers.Count is 0)
{
<MudText Typo="Typo.body1" Class="mb-3">
You have not yet added any ERI server presets.
@T("You have not yet added any ERI server presets.")
</MudText>
}
else
@@ -50,112 +52,116 @@ else
<MudStack Row="@true" Class="mt-1">
<MudButton Disabled="@this.AreServerPresetsBlocked" OnClick="@this.AddERIServer" Variant="Variant.Filled" Color="Color.Primary">
Add ERI server preset
@T("Add ERI server preset")
</MudButton>
<MudButton OnClick="@this.RemoveERIServer" Disabled="@(this.AreServerPresetsBlocked || this.IsNoneERIServerSelected)" Variant="Variant.Filled" Color="Color.Error">
Delete this server preset
@T("Delete this server preset")
</MudButton>
</MudStack>
@if(this.AreServerPresetsBlocked)
{
<MudJustifiedText Typo="Typo.body1" Class="mb-3 mt-3">
Hint: to allow this assistant to manage multiple presets, you must enable the preselection of values in the settings.
@T("Hint: to allow this assistant to manage multiple presets, you must enable the preselection of values in the settings.")
</MudJustifiedText>
}
<MudText Typo="Typo.h4" Class="mb-3 mt-6">
Auto save
@T("Auto save")
</MudText>
<MudJustifiedText Typo="Typo.body1" Class="mb-3">
The ERI specification will change over time. You probably want to keep your ERI server up to date. This means you might want to
regenerate the code for your ERI server. To avoid having to make all inputs each time, all your inputs and decisions can be
automatically saved. Would you like this?
@T("The ERI specification will change over time. You probably want to keep your ERI server up to date. This means you might want to regenerate the code for your ERI server. To avoid having to make all inputs each time, all your inputs and decisions can be automatically saved. Would you like this?")
</MudJustifiedText>
@if(this.AreServerPresetsBlocked)
{
<MudJustifiedText Typo="Typo.body1" Class="mb-3">
Hint: to allow this assistant to automatically save your changes, you must enable the preselection of values in the settings.
@T("Hint: to allow this assistant to automatically save your changes, you must enable the preselection of values in the settings.")
</MudJustifiedText>
}
<MudTextSwitch Label="Should we automatically save any input made?" Disabled="@this.AreServerPresetsBlocked" @bind-Value="@this.autoSave" LabelOn="Yes, please save my inputs" LabelOff="No, I will enter everything again or configure it manually in the settings" />
<MudTextSwitch Label="@T("Should we automatically save any input made?")" Disabled="@this.AreServerPresetsBlocked" @bind-Value="@this.autoSave" LabelOn="@T("Yes, please save my inputs")" LabelOff="@T("No, I will enter everything again or configure it manually in the settings")" />
<hr style="width: 100%; border-width: 0.25ch;" class="mt-6"/>
<MudText Typo="Typo.h4" Class="mt-6 mb-1">
Common ERI server settings
@T("Common ERI server settings")
</MudText>
<MudTextField T="string" Disabled="@this.IsNoneERIServerSelected" @bind-Text="@this.serverName" Validation="@this.ValidateServerName" Immediate="@true" Label="ERI server name" HelperText="Please give your ERI server a name that provides information about the data source and/or its intended purpose. The name will be displayed to users in AI Studio." Counter="60" MaxLength="60" Variant="Variant.Outlined" Margin="Margin.Normal" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3" OnKeyUp="() => this.ServerNameWasChanged()"/>
<MudTextField T="string" Disabled="@this.IsNoneERIServerSelected" @bind-Text="@this.serverDescription" Validation="@this.ValidateServerDescription" Immediate="@true" Label="ERI server description" HelperText="Please provide a brief description of your ERI server. Describe or explain what your ERI server does and what data it uses for this purpose. This description will be shown to users in AI Studio." Counter="512" MaxLength="512" Variant="Variant.Outlined" Margin="Margin.Normal" Lines="3" AutoGrow="@true" MaxLines="6" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudTextField T="string" Disabled="@this.IsNoneERIServerSelected" @bind-Text="@this.serverName" Validation="@this.ValidateServerName" Immediate="@true" Label="@T("ERI server name")" HelperText="@T("Please give your ERI server a name that provides information about the data source and/or its intended purpose. The name will be displayed to users in AI Studio.")" Counter="60" MaxLength="60" Variant="Variant.Outlined" Margin="Margin.Normal" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3" OnKeyUp="() => this.ServerNameWasChanged()"/>
<MudTextField T="string" Disabled="@this.IsNoneERIServerSelected" @bind-Text="@this.serverDescription" Validation="@this.ValidateServerDescription" Immediate="@true" Label="@T("ERI server description")" HelperText="@T("Please provide a brief description of your ERI server. Describe or explain what your ERI server does and what data it uses for this purpose. This description will be shown to users in AI Studio.")" Counter="512" MaxLength="512" Variant="Variant.Outlined" Margin="Margin.Normal" Lines="3" AutoGrow="@true" MaxLines="6" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudStack Row="@true" Class="mb-3">
<MudSelect Disabled="@this.IsNoneERIServerSelected" T="ProgrammingLanguages" @bind-Value="@this.selectedProgrammingLanguage" AdornmentIcon="@Icons.Material.Filled.Code" Adornment="Adornment.Start" Label="Programming language" Variant="Variant.Outlined" Margin="Margin.Dense" Validation="@this.ValidateProgrammingLanguage">
<MudSelect Disabled="@this.IsNoneERIServerSelected" T="ProgrammingLanguages" @bind-Value="@this.selectedProgrammingLanguage" AdornmentIcon="@Icons.Material.Filled.Code" Adornment="Adornment.Start" Label="@T("Programming language")" Variant="Variant.Outlined" Margin="Margin.Dense" Validation="@this.ValidateProgrammingLanguage">
@foreach (var language in Enum.GetValues<ProgrammingLanguages>())
{
<MudSelectItem Value="@language">@language.Name()</MudSelectItem>
<MudSelectItem Value="@language">
@language.Name()
</MudSelectItem>
}
</MudSelect>
@if (this.selectedProgrammingLanguage is ProgrammingLanguages.OTHER)
{
<MudTextField Disabled="@this.IsNoneERIServerSelected" T="string" @bind-Text="@this.otherProgrammingLanguage" Validation="@this.ValidateOtherLanguage" Label="Other language" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudTextField Disabled="@this.IsNoneERIServerSelected" T="string" @bind-Text="@this.otherProgrammingLanguage" Validation="@this.ValidateOtherLanguage" Label="@T("Other language")" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
}
</MudStack>
<MudStack Row="@true" AlignItems="AlignItems.Center" Class="mb-3">
<MudSelect Disabled="@this.IsNoneERIServerSelected" T="ERIVersion" @bind-Value="@this.selectedERIVersion" Label="ERI specification version" Variant="Variant.Outlined" Margin="Margin.Dense" Validation="@this.ValidateERIVersion">
<MudSelect Disabled="@this.IsNoneERIServerSelected" T="ERIVersion" @bind-Value="@this.selectedERIVersion" Label="@T("ERI specification version")" Variant="Variant.Outlined" Margin="Margin.Dense" Validation="@this.ValidateERIVersion">
@foreach (var version in Enum.GetValues<ERIVersion>())
{
<MudSelectItem Value="@version">@version</MudSelectItem>
<MudSelectItem Value="@version">
@version
</MudSelectItem>
}
</MudSelect>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!this.selectedERIVersion.WasSpecificationSelected() || this.IsNoneERIServerSelected)" Href="@this.selectedERIVersion.SpecificationURL()" Target="_blank">
<MudIcon Icon="@Icons.Material.Filled.Link" Class="mr-2"/> Download specification
<MudIcon Icon="@Icons.Material.Filled.Link" Class="mr-2"/> @T("Download specification")
</MudButton>
</MudStack>
<MudText Typo="Typo.h4" Class="mt-9 mb-3">
Data source settings
@T("Data source settings")
</MudText>
<MudStack Row="@false" Spacing="1" Class="mb-3">
<MudSelect Disabled="@this.IsNoneERIServerSelected" T="DataSources" @bind-Value="@this.selectedDataSource" AdornmentIcon="@Icons.Material.Filled.Dataset" Adornment="Adornment.Start" Label="Data source" Variant="Variant.Outlined" Margin="Margin.Dense" Validation="@this.ValidateDataSource" SelectedValuesChanged="@this.DataSourceWasChanged">
<MudSelect Disabled="@this.IsNoneERIServerSelected" T="DataSources" @bind-Value="@this.selectedDataSource" AdornmentIcon="@Icons.Material.Filled.Dataset" Adornment="Adornment.Start" Label="@T("Data source")" Variant="Variant.Outlined" Margin="Margin.Dense" Validation="@this.ValidateDataSource" SelectedValuesChanged="@this.DataSourceWasChanged">
@foreach (var dataSource in Enum.GetValues<DataSources>())
{
<MudSelectItem Value="@dataSource">@dataSource.Name()</MudSelectItem>
<MudSelectItem Value="@dataSource">
@dataSource.Name()
</MudSelectItem>
}
</MudSelect>
@if (this.selectedDataSource is DataSources.CUSTOM)
{
<MudTextField Disabled="@this.IsNoneERIServerSelected" T="string" @bind-Text="@this.otherDataSource" Validation="@this.ValidateOtherDataSource" Label="Describe your data source" Variant="Variant.Outlined" Margin="Margin.Normal" Lines="3" AutoGrow="@true" MaxLines="6" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudTextField Disabled="@this.IsNoneERIServerSelected" T="string" @bind-Text="@this.otherDataSource" Validation="@this.ValidateOtherDataSource" Label="@T("Describe your data source")" Variant="Variant.Outlined" Margin="Margin.Normal" Lines="3" AutoGrow="@true" MaxLines="6" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
}
</MudStack>
@if(this.selectedDataSource > DataSources.FILE_SYSTEM)
{
<MudTextField Disabled="@this.IsNoneERIServerSelected" T="string" @bind-Text="@this.dataSourceProductName" Label="Data source: product name" Validation="@this.ValidateDataSourceProductName" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudTextField Disabled="@this.IsNoneERIServerSelected" T="string" @bind-Text="@this.dataSourceProductName" Label="@T("Data source: product name")" Validation="@this.ValidateDataSourceProductName" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
}
@if (this.NeedHostnamePort())
{
<div class="mb-3">
<MudStack Row="@true">
<MudTextField Disabled="@this.IsNoneERIServerSelected" T="string" @bind-Text="@this.dataSourceHostname" Label="Data source: hostname" Validation="@this.ValidateHostname" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudNumericField Disabled="@this.IsNoneERIServerSelected" Label="Data source: port" Immediate="@true" Min="1" Max="65535" Validation="@this.ValidatePort" @bind-Value="@this.dataSourcePort" Variant="Variant.Outlined" Margin="Margin.Dense" OnKeyUp="() => this.DataSourcePortWasTyped()"/>
<MudTextField Disabled="@this.IsNoneERIServerSelected" T="string" @bind-Text="@this.dataSourceHostname" Label="@T("Data source: hostname")" Validation="@this.ValidateHostname" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudNumericField Disabled="@this.IsNoneERIServerSelected" Label="@T("Data source: port")" Immediate="@true" Min="1" Max="65535" Validation="@this.ValidatePort" @bind-Value="@this.dataSourcePort" Variant="Variant.Outlined" Margin="Margin.Dense" OnKeyUp="() => this.DataSourcePortWasTyped()"/>
</MudStack>
@if (this.dataSourcePort < 1024)
{
<MudText Typo="Typo.body2">
<b>Warning:</b> Ports below 1024 are reserved for system services. Your ERI server need to run with elevated permissions (root user).
<b>@T("Warning:")</b> @T("Ports below 1024 are reserved for system services. Your ERI server need to run with elevated permissions (root user).")
</MudText>
}
</div>
}
<MudText Typo="Typo.h4" Class="mt-9 mb-3">
Authentication settings
@T("Authentication settings")
</MudText>
<MudStack Row="@false" Spacing="1" Class="mb-1">
@@ -168,12 +174,14 @@ else
SelectedValues="@this.selectedAuthenticationMethods"
Validation="@this.ValidateAuthenticationMethods"
SelectedValuesChanged="@this.AuthenticationMethodWasChanged"
Label="Authentication method(s)"
Label="@T("Authentication method(s)")"
Variant="Variant.Outlined"
Margin="Margin.Dense">
@foreach (var authMethod in Enum.GetValues<Auth>())
{
<MudSelectItemExtended Value="@authMethod">@authMethod.Name()</MudSelectItemExtended>
<MudSelectItemExtended Value="@authMethod">
@authMethod.Name()
</MudSelectItemExtended>
}
</MudSelectExtended>
<MudTextField Disabled="@this.IsNoneERIServerSelected" T="string" @bind-Text="@this.authDescription" Label="@this.AuthDescriptionTitle()" Validation="@this.ValidateAuthDescription" Variant="Variant.Outlined" Margin="Margin.Normal" Lines="3" AutoGrow="@true" MaxLines="6" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
@@ -181,40 +189,39 @@ else
@if (this.selectedAuthenticationMethods.Contains(Auth.KERBEROS))
{
<MudSelect Disabled="@this.IsNoneERIServerSelected" T="OperatingSystem" @bind-Value="@this.selectedOperatingSystem" Label="Operating system on which your ERI will run" Variant="Variant.Outlined" Margin="Margin.Dense" Validation="@this.ValidateOperatingSystem" Class="mb-1">
<MudSelect Disabled="@this.IsNoneERIServerSelected" T="OperatingSystem" @bind-Value="@this.selectedOperatingSystem" Label="@T("Operating system on which your ERI will run")" Variant="Variant.Outlined" Margin="Margin.Dense" Validation="@this.ValidateOperatingSystem" Class="mb-1">
@foreach (var os in Enum.GetValues<OperatingSystem>())
{
<MudSelectItem Value="@os">@os.Name()</MudSelectItem>
<MudSelectItem Value="@os">
@os.Name()
</MudSelectItem>
}
</MudSelect>
}
<MudText Typo="Typo.h4" Class="mt-11 mb-3">
Data protection settings
@T("Data protection settings")
</MudText>
<MudSelect Disabled="@this.IsNoneERIServerSelected" T="AllowedLLMProviders" @bind-Value="@this.allowedLLMProviders" Label="Allowed LLM providers for this data source" Variant="Variant.Outlined" Margin="Margin.Dense" Validation="@this.ValidateAllowedLLMProviders" Class="mb-1">
<MudSelect Disabled="@this.IsNoneERIServerSelected" T="AllowedLLMProviders" @bind-Value="@this.allowedLLMProviders" Label="@T("Allowed LLM providers for this data source")" Variant="Variant.Outlined" Margin="Margin.Dense" Validation="@this.ValidateAllowedLLMProviders" Class="mb-1">
@foreach (var option in Enum.GetValues<AllowedLLMProviders>())
{
<MudSelectItem Value="@option">@option.Description()</MudSelectItem>
<MudSelectItem Value="@option">
@option.Description()
</MudSelectItem>
}
</MudSelect>
<MudText Typo="Typo.h4" Class="mt-11 mb-3">
Embedding settings
@T("Embedding settings")
</MudText>
<MudJustifiedText Typo="Typo.body1" Class="mb-2">
You will likely use one or more embedding methods to encode the meaning of your data into a typically high-dimensional vector
space. In this case, you will use a vector database to store and search these vectors (called embeddings). However, you don't
have to use embedding methods. When your retrieval method works without any embedding, you can ignore this section. An example: You
store files on a file server, and your retrieval method works exclusively with file names in the file system, so you don't
need embeddings.
@T("You will likely use one or more embedding methods to encode the meaning of your data into a typically high-dimensional vector space. In this case, you will use a vector database to store and search these vectors (called embeddings). However, you don't have to use embedding methods. When your retrieval method works without any embedding, you can ignore this section. An example: You store files on a file server, and your retrieval method works exclusively with file names in the file system, so you don't need embeddings.")
</MudJustifiedText>
<MudJustifiedText Typo="Typo.body1" Class="mb-3">
You can specify more than one embedding method. This can be useful when you want to use different embeddings for different queries
or data types. For example, one embedding for texts, another for images, and a third for videos, etc.
@T("You can specify more than one embedding method. This can be useful when you want to use different embeddings for different queries or data types. For example, one embedding for texts, another for images, and a third for videos, etc.")
</MudJustifiedText>
@if (!this.IsNoneERIServerSelected)
@@ -226,9 +233,9 @@ else
<col style="width: 34em;"/>
</ColGroup>
<HeaderContent>
<MudTh>Name</MudTh>
<MudTh>Type</MudTh>
<MudTh>Actions</MudTh>
<MudTh>@T("Name")</MudTh>
<MudTh>@T("Type")</MudTh>
<MudTh>@T("Actions")</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>@context.EmbeddingName</MudTd>
@@ -236,10 +243,10 @@ else
<MudTd>
<MudStack Row="true" Class="mb-2 mt-2" Wrap="Wrap.Wrap">
<MudButton Variant="Variant.Filled" Color="Color.Info" StartIcon="@Icons.Material.Filled.Edit" OnClick="() => this.EditEmbedding(context)">
Edit
@T("Edit")
</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Error" StartIcon="@Icons.Material.Filled.Delete" OnClick="() => this.DeleteEmbedding(context)">
Delete
@T("Delete")
</MudButton>
</MudStack>
</MudTd>
@@ -248,23 +255,22 @@ else
@if (this.embeddings.Count == 0)
{
<MudText Typo="Typo.h6" Class="mt-3">No embedding methods configured yet.</MudText>
<MudText Typo="Typo.h6" Class="mt-3">
@T("No embedding methods configured yet.")
</MudText>
}
}
<MudButton Disabled="@this.IsNoneERIServerSelected" Variant="Variant.Filled" Color="@Color.Primary" StartIcon="@Icons.Material.Filled.AddRoad" Class="mt-3 mb-6" OnClick="@this.AddEmbedding">
Add Embedding Method
@T("Add Embedding Method")
</MudButton>
<MudText Typo="Typo.h4" Class="mt-6 mb-1">
Data retrieval settings
@T("Data retrieval settings")
</MudText>
<MudJustifiedText Typo="Typo.body1" Class="mb-2">
For your ERI server, you need to retrieve data that matches a chat or prompt in some way. We call this the retrieval process.
You must describe at least one such process. You may offer several retrieval processes from which users can choose. This allows
you to test with beta users which process works better. Or you might generally want to give users the choice so they can select
the process that best suits their circumstances.
@T("For your ERI server, you need to retrieve data that matches a chat or prompt in some way. We call this the retrieval process. You must describe at least one such process. You may offer several retrieval processes from which users can choose. This allows you to test with beta users which process works better. Or you might generally want to give users the choice so they can select the process that best suits their circumstances.")
</MudJustifiedText>
@if (!this.IsNoneERIServerSelected)
@@ -275,18 +281,18 @@ else
<col style="width: 34em;"/>
</ColGroup>
<HeaderContent>
<MudTh>Name</MudTh>
<MudTh>Actions</MudTh>
<MudTh>@T("Name")</MudTh>
<MudTh>@T("Actions")</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>@context.Name</MudTd>
<MudTd>
<MudStack Row="true" Class="mb-2 mt-2" Wrap="Wrap.Wrap">
<MudButton Variant="Variant.Filled" Color="Color.Info" StartIcon="@Icons.Material.Filled.Edit" OnClick="() => this.EditRetrievalProcess(context)">
Edit
@T("Edit")
</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Error" StartIcon="@Icons.Material.Filled.Delete" OnClick="() => this.DeleteRetrievalProcess(context)">
Delete
@T("Delete")
</MudButton>
</MudStack>
</MudTd>
@@ -295,59 +301,47 @@ else
@if (this.retrievalProcesses.Count == 0)
{
<MudText Typo="Typo.h6" Class="mt-3">No retrieval process configured yet.</MudText>
<MudText Typo="Typo.h6" Class="mt-3">
@T("No retrieval process configured yet.")
</MudText>
}
}
<MudButton Disabled="@this.IsNoneERIServerSelected" Variant="Variant.Filled" Color="@Color.Primary" StartIcon="@Icons.Material.Filled.AddRoad" Class="mt-3 mb-6" OnClick="@this.AddRetrievalProcess">
Add Retrieval Process
@T("Add Retrieval Process")
</MudButton>
<MudJustifiedText Typo="Typo.body1" Class="mb-1">
You can integrate additional libraries. Perhaps you want to evaluate the prompts in advance using a machine learning method or analyze them with a text
mining approach? Or maybe you want to preprocess images in the prompts? For such advanced scenarios, you can specify which libraries you want to use here.
It's best to describe which library you want to integrate for which purpose. This way, the LLM that writes the ERI server for you can try to use these
libraries effectively. This should result in less rework being necessary. If you don't know the necessary libraries, you can instead attempt to describe
the intended use. The LLM can then attempt to choose suitable libraries. However, hallucinations can occur, and fictional libraries might be selected.
@T("You can integrate additional libraries. Perhaps you want to evaluate the prompts in advance using a machine learning method or analyze them with a text mining approach? Or maybe you want to preprocess images in the prompts? For such advanced scenarios, you can specify which libraries you want to use here. It's best to describe which library you want to integrate for which purpose. This way, the LLM that writes the ERI server for you can try to use these libraries effectively. This should result in less rework being necessary. If you don't know the necessary libraries, you can instead attempt to describe the intended use. The LLM can then attempt to choose suitable libraries. However, hallucinations can occur, and fictional libraries might be selected.")
</MudJustifiedText>
<MudTextField Disabled="@this.IsNoneERIServerSelected" T="string" @bind-Text="@this.additionalLibraries" Label="(Optional) Additional libraries" HelperText="Do you want to include additional libraries? Then name them and briefly describe what you want to achieve with them." Variant="Variant.Outlined" Margin="Margin.Normal" Lines="3" AutoGrow="@true" MaxLines="12" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudTextField Disabled="@this.IsNoneERIServerSelected" T="string" @bind-Text="@this.additionalLibraries" Label="@T("(Optional) Additional libraries")" HelperText="@T("Do you want to include additional libraries? Then name them and briefly describe what you want to achieve with them.")" Variant="Variant.Outlined" Margin="Margin.Normal" Lines="3" AutoGrow="@true" MaxLines="12" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudText Typo="Typo.h4" Class="mt-9 mb-1">
Provider selection for generation
@T("Provider selection for generation")
</MudText>
<MudJustifiedText Typo="Typo.body1" Class="mb-2">
The task of writing the ERI server for you is very complex. Therefore, a very powerful LLM is needed to successfully accomplish this task.
Small local models will probably not be sufficient. Instead, try using a large cloud-based or a large self-hosted model.
@T("The task of writing the ERI server for you is very complex. Therefore, a very powerful LLM is needed to successfully accomplish this task. Small local models will probably not be sufficient. Instead, try using a large cloud-based or a large self-hosted model.")
</MudJustifiedText>
<MudJustifiedText Typo="Typo.body1" Class="mb-2">
<b>Important:</b> The LLM may need to generate many files. This reaches the request limit of most providers. Typically, only a certain number
of requests can be made per minute, and only a maximum number of tokens can be generated per minute. AI Studio automatically considers this.
<b>However, generating all the files takes a certain amount of time.</b> Local or self-hosted models may work without these limitations
and can generate responses faster. AI Studio dynamically adapts its behavior and always tries to achieve the fastest possible data processing.
<b>@T("Important:")</b> @T("The LLM may need to generate many files. This reaches the request limit of most providers. Typically, only a certain number of requests can be made per minute, and only a maximum number of tokens can be generated per minute. AI Studio automatically considers this.") <b>@T("However, generating all the files takes a certain amount of time.")</b> @T("Local or self-hosted models may work without these limitations and can generate responses faster. AI Studio dynamically adapts its behavior and always tries to achieve the fastest possible data processing.")
</MudJustifiedText>
<ProviderSelection @bind-ProviderSettings="@this.providerSettings" ValidateProvider="@this.ValidatingProvider"/>
<MudText Typo="Typo.h4" Class="mt-9 mb-1">
Write code to file system
@T("Write code to file system")
</MudText>
<MudJustifiedText Typo="Typo.body1" Class="mb-2">
AI Studio can save the generated code to the file system. You can select a base folder for this. AI Studio ensures that no files are created
outside of this base folder. Furthermore, we recommend that you create a Git repository in this folder. This way, you can see what changes the
AI has made in which files.
@T("AI Studio can save the generated code to the file system. You can select a base folder for this. AI Studio ensures that no files are created outside of this base folder. Furthermore, we recommend that you create a Git repository in this folder. This way, you can see what changes the AI has made in which files.")
</MudJustifiedText>
<MudJustifiedText Typo="Typo.body1" Class="mb-2">
When you rebuild / re-generate the ERI server code, AI Studio proceeds as follows: All files generated last time will be deleted. All
other files you have created remain. Then, the AI generates the new files. <b>But beware:</b> It may happen that the AI generates a
file this time that you manually created last time. In this case, your manually created file will then be overwritten. Therefore,
you should always create a Git repository and commit or revert all changes before using this assistant. With a diff visualization,
you can immediately see where the AI has made changes. It is best to use an IDE suitable for your selected language for this purpose.
@T("When you rebuild / re-generate the ERI server code, AI Studio proceeds as follows: All files generated last time will be deleted. All other files you have created remain. Then, the AI generates the new files.") <b>@T("But beware:")</b> @T("It may happen that the AI generates a file this time that you manually created last time. In this case, your manually created file will then be overwritten. Therefore, you should always create a Git repository and commit or revert all changes before using this assistant. With a diff visualization, you can immediately see where the AI has made changes. It is best to use an IDE suitable for your selected language for this purpose.")
</MudJustifiedText>
<MudTextSwitch Label="Should we write the generated code to the file system?" Disabled="@this.IsNoneERIServerSelected" @bind-Value="@this.writeToFilesystem" LabelOn="Yes, please write or update all generated code to the file system" LabelOff="No, just show me the code" />
<SelectDirectory Label="Base directory where to write the code" @bind-Directory="@this.baseDirectory" Disabled="@(this.IsNoneERIServerSelected || !this.writeToFilesystem)" DirectoryDialogTitle="Select the target directory for the ERI server" Validation="@this.ValidateDirectory" />
<MudTextSwitch Label="@T("Should we write the generated code to the file system?")" Disabled="@this.IsNoneERIServerSelected" @bind-Value="@this.writeToFilesystem" LabelOn="@T("Yes, please write or update all generated code to the file system")" LabelOff="@T("No, just show me the code")" />
<SelectDirectory Label="@T("Base directory where to write the code")" @bind-Directory="@this.baseDirectory" Disabled="@(this.IsNoneERIServerSelected || !this.writeToFilesystem)" DirectoryDialogTitle="@T("Select the target directory for the ERI server")" Validation="@this.ValidateDirectory" />
@@ -22,16 +22,9 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
public override Tools.Components Component => Tools.Components.ERI_ASSISTANT;
protected override string Title => "ERI Server";
protected override string Title => T("ERI Server");
protected override string Description =>
"""
The ERI is the External Retrieval Interface for AI Studio and other tools. The ERI acts as a contract
between decentralized data sources and, e.g., AI Studio. The ERI is implemented by the data sources,
allowing them to be integrated into AI Studio later. This means that the data sources assume the server
role and AI Studio (or any other LLM tool) assumes the client role of the API. This approach serves to
realize a Retrieval-Augmented Generation (RAG) process with external data.
""";
protected override string Description => T("The ERI is the External Retrieval Interface for AI Studio and other tools. The ERI acts as a contract between decentralized data sources and, e.g., AI Studio. The ERI is implemented by the data sources, allowing them to be integrated into AI Studio later. This means that the data sources assume the server role and AI Studio (or any other LLM tool) assumes the client role of the API. This approach serves to realize a Retrieval-Augmented Generation (RAG) process with external data.");
protected override string SystemPrompt
{
@@ -44,7 +37,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
// Introduction
// ---------------------------------
//
var programmingLanguage = this.selectedProgrammingLanguage is ProgrammingLanguages.OTHER ? this.otherProgrammingLanguage : this.selectedProgrammingLanguage.Name();
var programmingLanguage = this.selectedProgrammingLanguage is ProgrammingLanguages.OTHER ? this.otherProgrammingLanguage : this.selectedProgrammingLanguage.ToPrompt();
sb.Append($"""
# Introduction
You are an experienced {programmingLanguage} developer. Your task is to implement an API server in
@@ -159,7 +152,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
{
sb.Append($"""
The server will run on {this.selectedOperatingSystem.Name()} operating systems. Keep
The server will run on {this.selectedOperatingSystem.ToPrompt()} operating systems. Keep
this in mind when implementing the SSO with Kerberos.
""");
}
@@ -304,7 +297,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
protected override bool ShowSendTo => false;
protected override string SubmitText => "Create the ERI server";
protected override string SubmitText => T("Create the ERI server");
protected override Func<Task> SubmitAction => this.GenerateServer;
@@ -469,7 +462,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
{
this.SettingsManager.ConfigurationData.ERI.ERIServers.Add(new ()
{
ServerName = $"ERI Server {DateTimeOffset.UtcNow}",
ServerName = string.Format(T("ERI Server {0}"), DateTimeOffset.UtcNow),
});
await this.SettingsManager.StoreSettings();
@@ -482,10 +475,10 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
var dialogParameters = new DialogParameters
{
{ "Message", $"Are you sure you want to delete the ERI server preset '{this.selectedERIServer.ServerName}'?" },
{ "Message", string.Format(T("Are you sure you want to delete the ERI server preset '{0}'?"), this.selectedERIServer.ServerName) },
};
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>("Delete ERI server preset", dialogParameters, DialogOptions.FULLSCREEN);
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>(T("Delete ERI server preset"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
return;
@@ -518,13 +511,13 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
private string? ValidateServerName(string name)
{
if(string.IsNullOrWhiteSpace(name))
return "Please provide a name for your ERI server. This name will be used to identify the server in AI Studio.";
return T("Please provide a name for your ERI server. This name will be used to identify the server in AI Studio.");
if(name.Length is > 60 or < 6)
return "The name of your ERI server must be between 6 and 60 characters long.";
return T("The name of your ERI server must be between 6 and 60 characters long.");
if(this.SettingsManager.ConfigurationData.ERI.ERIServers.Where(n => n != this.selectedERIServer).Any(n => n.ServerName == name))
return "An ERI server preset with this name already exists. Please choose a different name.";
return T("An ERI server preset with this name already exists. Please choose a different name.");
return null;
}
@@ -532,10 +525,10 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
private string? ValidateServerDescription(string description)
{
if(string.IsNullOrWhiteSpace(description))
return "Please provide a description for your ERI server. What data will the server retrieve? This description will be used to inform users about the purpose of your ERI server.";
return T("Please provide a description for your ERI server. What data will the server retrieve? This description will be used to inform users about the purpose of your ERI server.");
if(description.Length is < 32 or > 512)
return "The description of your ERI server must be between 32 and 512 characters long.";
return T("The description of your ERI server must be between 32 and 512 characters long.");
return null;
}
@@ -543,7 +536,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
private string? ValidateERIVersion(ERIVersion version)
{
if (version == ERIVersion.NONE)
return "Please select an ERI specification version for the ERI server.";
return T("Please select an ERI specification version for the ERI server.");
return null;
}
@@ -554,7 +547,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
return null;
if (language == ProgrammingLanguages.NONE)
return "Please select a programming language for the ERI server.";
return T("Please select a programming language for the ERI server.");
return null;
}
@@ -565,7 +558,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
return null;
if(string.IsNullOrWhiteSpace(language))
return "Please specify the custom programming language for the ERI server.";
return T("Please specify the custom programming language for the ERI server.");
return null;
}
@@ -576,7 +569,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
return null;
if (dataSource == DataSources.NONE)
return "Please select a data source for the ERI server.";
return T("Please select a data source for the ERI server.");
return null;
}
@@ -587,7 +580,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
return null;
if(string.IsNullOrWhiteSpace(productName))
return "Please specify the product name of the data source, e.g., 'MongoDB', 'Redis', 'PostgreSQL', 'Neo4j', or 'MinIO', etc.";
return T("Please specify the product name of the data source, e.g., 'MongoDB', 'Redis', 'PostgreSQL', 'Neo4j', or 'MinIO', etc.");
return null;
}
@@ -598,7 +591,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
return null;
if(string.IsNullOrWhiteSpace(dataSource))
return "Please describe the data source of your ERI server.";
return T("Please describe the data source of your ERI server.");
return null;
}
@@ -613,10 +606,10 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
return null;
if(string.IsNullOrWhiteSpace(hostname))
return "Please provide the hostname of the data source. Use 'localhost' if the data source is on the same machine as the ERI server.";
return T("Please provide the hostname of the data source. Use 'localhost' if the data source is on the same machine as the ERI server.");
if(hostname.Length > 255)
return "The hostname of the data source must not exceed 255 characters.";
return T("The hostname of the data source must not exceed 255 characters.");
return null;
}
@@ -631,10 +624,10 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
return null;
if(port is null)
return "Please provide the port of the data source.";
return T("Please provide the port of the data source.");
if(port is < 1 or > 65535)
return "The port of the data source must be between 1 and 65535.";
return T("The port of the data source must be between 1 and 65535.");
return null;
}
@@ -679,7 +672,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
{
var authenticationMethods = (this.selectedAuthenticationMethods as HashSet<Auth>)!;
if(authenticationMethods.Count == 0)
return "Please select at least one authentication method for the ERI server.";
return T("Please select at least one authentication method for the ERI server.");
return null;
}
@@ -709,7 +702,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
return null;
if(os is OperatingSystem.NONE)
return "Please select the operating system on which the ERI server will run. This is necessary when using SSO with Kerberos.";
return T("Please select the operating system on which the ERI server will run. This is necessary when using SSO with Kerberos.");
return null;
}
@@ -717,16 +710,12 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
private string? ValidateAllowedLLMProviders(AllowedLLMProviders provider)
{
if(provider == AllowedLLMProviders.NONE)
return "Please select which types of LLMs users are allowed to use with the data from this ERI server.";
return T("Please select which types of LLMs users are allowed to use with the data from this ERI server.");
return null;
}
private string AuthDescriptionTitle()
{
const string TITLE = "Describe how you planned the authentication process";
return this.IsAuthDescriptionOptional() ? $"(Optional) {TITLE}" : TITLE;
}
private string AuthDescriptionTitle() => this.IsAuthDescriptionOptional() ? T("(Optional) Describe how you planned the authentication process") : T("Describe how you planned the authentication process");
private bool IsAuthDescriptionOptional()
{
@@ -746,10 +735,10 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
{
var authenticationMethods = (this.selectedAuthenticationMethods as HashSet<Auth>)!;
if(authenticationMethods.Any(n => n == Auth.NONE) && authenticationMethods.Count > 1 && string.IsNullOrWhiteSpace(this.authDescription))
return "Please describe how the selected authentication methods should be used. Especially, explain for what data the NONE method (public access) is used.";
return T("Please describe how the selected authentication methods should be used. Especially, explain for what data the NONE method (public access) is used.");
if(authenticationMethods.Count > 1 && string.IsNullOrWhiteSpace(this.authDescription))
return "Please describe how the selected authentication methods should be used.";
return T("Please describe how the selected authentication methods should be used.");
return null;
}
@@ -760,7 +749,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
return null;
if(string.IsNullOrWhiteSpace(path))
return "Please provide a base directory for the ERI server to write files to.";
return T("Please provide a base directory for the ERI server to write files to.");
return null;
}
@@ -768,12 +757,12 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
private string GetMultiSelectionAuthText(List<Auth> selectedValues)
{
if(selectedValues.Count == 0)
return "Please select at least one authentication method";
return T("Please select at least one authentication method");
if(selectedValues.Count == 1)
return $"You have selected 1 authentication method";
return T("You have selected 1 authentication method");
return $"You have selected {selectedValues.Count} authentication methods";
return string.Format(T("You have selected {0} authentication methods"), selectedValues.Count);
}
private bool NeedHostnamePort()
@@ -797,7 +786,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
{ x => x.UsedEmbeddingMethodNames, this.embeddings.Select(n => n.EmbeddingName).ToList() },
};
var dialogReference = await this.DialogService.ShowAsync<EmbeddingMethodDialog>("Add Embedding Method", dialogParameters, DialogOptions.FULLSCREEN);
var dialogReference = await this.DialogService.ShowAsync<EmbeddingMethodDialog>(T("Add Embedding Method"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
return;
@@ -821,7 +810,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
{ x => x.IsEditing, true },
};
var dialogReference = await this.DialogService.ShowAsync<EmbeddingMethodDialog>("Edit Embedding Method", dialogParameters, DialogOptions.FULLSCREEN);
var dialogReference = await this.DialogService.ShowAsync<EmbeddingMethodDialog>(T("Edit Embedding Method"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
return;
@@ -835,15 +824,15 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
private async Task DeleteEmbedding(EmbeddingInfo embeddingInfo)
{
var message = this.retrievalProcesses.Any(n => n.Embeddings?.Contains(embeddingInfo) is true)
? $"The embedding '{embeddingInfo.EmbeddingName}' is used in one or more retrieval processes. Are you sure you want to delete it?"
: $"Are you sure you want to delete the embedding '{embeddingInfo.EmbeddingName}'?";
? string.Format(T("The embedding '{0}' is used in one or more retrieval processes. Are you sure you want to delete it?"), embeddingInfo.EmbeddingName)
: string.Format(T("Are you sure you want to delete the embedding '{0}'?"), embeddingInfo.EmbeddingName);
var dialogParameters = new DialogParameters
{
{ "Message", message },
};
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>("Delete Embedding", dialogParameters, DialogOptions.FULLSCREEN);
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>(T("Delete Embedding"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
return;
@@ -863,7 +852,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
{ x => x.UsedRetrievalProcessNames, this.retrievalProcesses.Select(n => n.Name).ToList() },
};
var dialogReference = await this.DialogService.ShowAsync<RetrievalProcessDialog>("Add Retrieval Process", dialogParameters, DialogOptions.FULLSCREEN);
var dialogReference = await this.DialogService.ShowAsync<RetrievalProcessDialog>(T("Add Retrieval Process"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
return;
@@ -888,7 +877,7 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
{ x => x.UsedRetrievalProcessNames, this.retrievalProcesses.Where(n => n != retrievalInfo).Select(n => n.Name).ToList() },
};
var dialogReference = await this.DialogService.ShowAsync<RetrievalProcessDialog>("Edit Retrieval Process", dialogParameters, DialogOptions.FULLSCREEN);
var dialogReference = await this.DialogService.ShowAsync<RetrievalProcessDialog>(T("Edit Retrieval Process"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
return;
@@ -903,10 +892,10 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
{
var dialogParameters = new DialogParameters
{
{ "Message", $"Are you sure you want to delete the retrieval process '{retrievalInfo.Name}'?" },
{ "Message", string.Format(T("Are you sure you want to delete the retrieval process '{0}'?"), retrievalInfo.Name) },
};
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>("Delete Retrieval Process", dialogParameters, DialogOptions.FULLSCREEN);
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>(T("Delete Retrieval Process"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
return;
@@ -957,14 +946,14 @@ public partial class AssistantERI : AssistantBaseCore<SettingsDialogERIServer>
if(this.retrievalProcesses.Count == 0)
{
this.AddInputIssue("Please describe at least one retrieval process.");
this.AddInputIssue(T("Please describe at least one retrieval process."));
return;
}
this.eriSpecification = await this.selectedERIVersion.ReadSpecification(this.HttpClient);
if (string.IsNullOrWhiteSpace(this.eriSpecification))
{
this.AddInputIssue("The ERI specification could not be loaded. Please try again later.");
this.AddInputIssue(T("The ERI specification could not be loaded. Please try again later."));
return;
}
@@ -2,15 +2,17 @@ namespace AIStudio.Assistants.ERI;
public static class AuthExtensions
{
private static string TB(string fallbackEN) => Tools.PluginSystem.I18N.I.T(fallbackEN, typeof(AuthExtensions).Namespace, nameof(AuthExtensions));
public static string Name(this Auth auth) => auth switch
{
Auth.NONE => "No login necessary: useful for public data sources",
Auth.NONE => TB("No login necessary: useful for public data sources"),
Auth.KERBEROS => "Login by single-sign-on (SSO) using Kerberos: very complex to implement and to operate, useful for many users",
Auth.USERNAME_PASSWORD => "Login by username and password: simple to implement and to operate, useful for few users; easy to use for users",
Auth.TOKEN => "Login by token: simple to implement and to operate, useful for few users; unusual for many users",
Auth.KERBEROS => TB("Login by single-sign-on (SSO) using Kerberos: very complex to implement and to operate, useful for many users"),
Auth.USERNAME_PASSWORD => TB("Login by username and password: simple to implement and to operate, useful for few users; easy to use for users"),
Auth.TOKEN => TB("Login by token: simple to implement and to operate, useful for few users; unusual for many users"),
_ => "Unknown login method"
_ => TB("Unknown login method")
};
public static string ToPrompt(this Auth auth) => auth switch
@@ -2,18 +2,20 @@ namespace AIStudio.Assistants.ERI;
public static class DataSourcesExtensions
{
private static string TB(string fallbackEN) => Tools.PluginSystem.I18N.I.T(fallbackEN, typeof(DataSourcesExtensions).Namespace, nameof(DataSourcesExtensions));
public static string Name(this DataSources dataSource) => dataSource switch
{
DataSources.NONE => "No data source selected",
DataSources.CUSTOM => "Custom description",
DataSources.NONE => TB("No data source selected"),
DataSources.CUSTOM => TB("Custom description"),
DataSources.FILE_SYSTEM => "File system (local or network share)",
DataSources.OBJECT_STORAGE => "Object storage, like Amazon S3, MinIO, etc.",
DataSources.KEY_VALUE_STORE => "Key-Value store, like Redis, etc.",
DataSources.DOCUMENT_STORE => "Document store, like MongoDB, etc.",
DataSources.RELATIONAL_DATABASE => "Relational database, like MySQL, PostgreSQL, etc.",
DataSources.GRAPH_DATABASE => "Graph database, like Neo4j, ArangoDB, etc.",
DataSources.FILE_SYSTEM => TB("File system (local or network share)"),
DataSources.OBJECT_STORAGE => TB("Object storage, like Amazon S3, MinIO, etc."),
DataSources.KEY_VALUE_STORE => TB("Key-Value store, like Redis, etc."),
DataSources.DOCUMENT_STORE => TB("Document store, like MongoDB, etc."),
DataSources.RELATIONAL_DATABASE => TB("Relational database, like MySQL, PostgreSQL, etc."),
DataSources.GRAPH_DATABASE => TB("Graph database, like Neo4j, ArangoDB, etc."),
_ => "Unknown data source"
_ => TB("Unknown data source")
};
}
@@ -2,7 +2,19 @@ namespace AIStudio.Assistants.ERI;
public static class OperatingSystemExtensions
{
private static string TB(string fallbackEN) => Tools.PluginSystem.I18N.I.T(fallbackEN, typeof(OperatingSystemExtensions).Namespace, nameof(OperatingSystemExtensions));
public static string Name(this OperatingSystem os) => os switch
{
OperatingSystem.NONE => TB("No operating system specified"),
OperatingSystem.WINDOWS => TB("Windows"),
OperatingSystem.LINUX => TB("Linux"),
_ => TB("Unknown operating system")
};
public static string ToPrompt(this OperatingSystem os) => os switch
{
OperatingSystem.NONE => "No operating system specified",
@@ -2,7 +2,29 @@ namespace AIStudio.Assistants.ERI;
public static class ProgrammingLanguagesExtensions
{
private static string TB(string fallbackEN) => Tools.PluginSystem.I18N.I.T(fallbackEN, typeof(ProgrammingLanguagesExtensions).Namespace, nameof(ProgrammingLanguagesExtensions));
public static string Name(this ProgrammingLanguages language) => language switch
{
ProgrammingLanguages.NONE => TB("No programming language selected"),
ProgrammingLanguages.C => "C",
ProgrammingLanguages.CPP => "C++",
ProgrammingLanguages.CSHARP => "C#",
ProgrammingLanguages.GO => "Go",
ProgrammingLanguages.JAVA => "Java",
ProgrammingLanguages.JAVASCRIPT => "JavaScript",
ProgrammingLanguages.JULIA => "Julia",
ProgrammingLanguages.MATLAB => "MATLAB",
ProgrammingLanguages.PHP => "PHP",
ProgrammingLanguages.PYTHON => "Python",
ProgrammingLanguages.RUST => "Rust",
ProgrammingLanguages.OTHER => TB("Other"),
_ => TB("Unknown")
};
public static string ToPrompt(this ProgrammingLanguages language) => language switch
{
ProgrammingLanguages.NONE => "No programming language selected",
@@ -2,35 +2,35 @@
@using AIStudio.Settings
@inherits AssistantBaseCore<AIStudio.Dialogs.Settings.SettingsDialogI18N>
<EnumSelection T="CommonLanguages" NameFunc="@(language => language.NameSelecting())" @bind-Value="@this.selectedTargetLanguage" ValidateSelection="@this.ValidatingTargetLanguage" Icon="@Icons.Material.Filled.Translate" Label="Target language" AllowOther="@true" OtherValue="CommonLanguages.OTHER" @bind-OtherInput="@this.customTargetLanguage" ValidateOther="@this.ValidateCustomLanguage" LabelOther="Custom target language" SelectionUpdated="_ => this.OnChangedLanguage()" />
<ConfigurationSelect OptionDescription="Language plugin used for comparision" SelectedValue="@(() => this.selectedLanguagePluginId)" Data="@ConfigurationSelectDataFactory.GetLanguagesData()" SelectionUpdate="@(async void (id) => await this.OnLanguagePluginChanged(id))" OptionHelp="Select the language plugin used for comparision."/>
<EnumSelection T="CommonLanguages" NameFunc="@(language => language.NameSelecting())" @bind-Value="@this.selectedTargetLanguage" ValidateSelection="@this.ValidatingTargetLanguage" Icon="@Icons.Material.Filled.Translate" Label="@T("Target language")" AllowOther="@true" OtherValue="CommonLanguages.OTHER" @bind-OtherInput="@this.customTargetLanguage" ValidateOther="@this.ValidateCustomLanguage" LabelOther="@T("Custom target language")" SelectionUpdated="_ => this.OnChangedLanguage()" />
<ConfigurationSelect OptionDescription="@T("Language plugin used for comparision")" SelectedValue="@(() => this.selectedLanguagePluginId)" Data="@ConfigurationSelectDataFactory.GetLanguagesData()" SelectionUpdate="@(async void (id) => await this.OnLanguagePluginChanged(id))" OptionHelp="@T("Select the language plugin used for comparision.")"/>
@if (this.isLoading)
{
<MudText Typo="Typo.body1" Class="mb-6">
The data is being loaded, please wait...
@T("The data is being loaded, please wait...")
</MudText>
} else if (!this.isLoading && !string.IsNullOrWhiteSpace(this.loadingIssue))
{
<MudText Typo="Typo.body1" Class="mb-6">
While loading the I18N data, an issue occurred: @this.loadingIssue
@T("While loading the I18N data, an issue occurred:") @this.loadingIssue
</MudText>
}
else if (!this.isLoading && string.IsNullOrWhiteSpace(this.loadingIssue))
{
<MudText Typo="Typo.h6">
Added Content (@this.addedContent.Count entries)
@this.AddedContentText
</MudText>
<MudTable Items="@this.addedContent" Hover="@true" Filter="@this.FilterFunc" Class="border-dashed border rounded-lg mb-6">
<ToolBarContent>
<MudTextField @bind-Value="@this.searchString" Immediate="true" Placeholder="Search" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"/>
<MudTextField @bind-Value="@this.searchString" Immediate="true" Placeholder="@T("Search")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"/>
</ToolBarContent>
<ColGroup>
<col/>
<col/>
</ColGroup>
<HeaderContent>
<MudTh>Key</MudTh>
<MudTh>Text</MudTh>
<MudTh>@T("Key")</MudTh>
<MudTh>@T("Text")</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>
@@ -48,19 +48,19 @@ else if (!this.isLoading && string.IsNullOrWhiteSpace(this.loadingIssue))
</MudTable>
<MudText Typo="Typo.h6">
Removed Content (@this.removedContent.Count entries)
@this.RemovedContentText
</MudText>
<MudTable Items="@this.removedContent" Hover="@true" Filter="@this.FilterFunc" Class="border-dashed border rounded-lg mb-6">
<ToolBarContent>
<MudTextField @bind-Value="@this.searchString" Immediate="true" Placeholder="Search" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"/>
<MudTextField @bind-Value="@this.searchString" Immediate="true" Placeholder="@T("Search")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"/>
</ToolBarContent>
<ColGroup>
<col/>
<col/>
</ColGroup>
<HeaderContent>
<MudTh>Key</MudTh>
<MudTh>Text</MudTh>
<MudTh>@T("Key")</MudTh>
<MudTh>@T("Text")</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>
@@ -80,7 +80,7 @@ else if (!this.isLoading && string.IsNullOrWhiteSpace(this.loadingIssue))
@if (this.selectedTargetLanguage is CommonLanguages.EN_US)
{
<MudJustifiedText Typo="Typo.body1" Class="mb-6">
Please note: neither is a translation needed nor performed for English (USA). Anyway, you might want to generate the related Lua code.
@T("Please note: neither is a translation needed nor performed for English (USA). Anyway, you might want to generate the related Lua code.")
</MudJustifiedText>
}
else
@@ -92,19 +92,19 @@ else if (!this.isLoading && string.IsNullOrWhiteSpace(this.loadingIssue))
{
<hr style="width: 100%; border-width: 0.25ch;" class="mt-6 mb-6"/>
<MudText Typo="Typo.h6">
Localized Content (@this.localizedContent.Count entries of @this.NumTotalItems)
@this.LocalizedContentText
</MudText>
<MudTable Items="@this.localizedContent" Hover="@true" Filter="@this.FilterFunc" Class="border-dashed border rounded-lg mb-6">
<ToolBarContent>
<MudTextField @bind-Value="@this.searchString" Immediate="true" Placeholder="Search" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"/>
<MudTextField @bind-Value="@this.searchString" Immediate="true" Placeholder="@T("Search")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"/>
</ToolBarContent>
<ColGroup>
<col/>
<col/>
</ColGroup>
<HeaderContent>
<MudTh>Key</MudTh>
<MudTh>Text</MudTh>
<MudTh>@T("Key")</MudTh>
<MudTh>@T("Text")</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>
@@ -18,12 +18,9 @@ public partial class AssistantI18N : AssistantBaseCore<SettingsDialogI18N>
{
public override Tools.Components Component => Tools.Components.I18N_ASSISTANT;
protected override string Title => "Localization";
protected override string Title => T("Localization");
protected override string Description =>
"""
Translate MindWork AI Studio text content into another language.
""";
protected override string Description => T("Translate MindWork AI Studio text content into another language.");
protected override string SystemPrompt =>
$"""
@@ -59,7 +56,7 @@ public partial class AssistantI18N : AssistantBaseCore<SettingsDialogI18N>
[
new ButtonData
{
Text = "Copy Lua code to clipboard",
Text = T("Copy Lua code to clipboard"),
Icon = Icons.Material.Filled.Extension,
Color = Color.Default,
AsyncAction = async () => await this.RustService.CopyText2Clipboard(this.Snackbar, this.finalLuaCode.ToString()),
@@ -67,7 +64,7 @@ public partial class AssistantI18N : AssistantBaseCore<SettingsDialogI18N>
},
];
protected override string SubmitText => "Localize AI Studio & generate the Lua code";
protected override string SubmitText => T("Localize AI Studio & generate the Lua code");
protected override Func<Task> SubmitAction => this.LocalizeTextContent;
@@ -143,12 +140,12 @@ public partial class AssistantI18N : AssistantBaseCore<SettingsDialogI18N>
this.localizationPossible = false;
if (PluginFactory.RunningPlugins.FirstOrDefault(n => n is PluginLanguage && n.Id == this.selectedLanguagePluginId) is not PluginLanguage comparisonPlugin)
{
this.loadingIssue = $"Was not able to load the language plugin for comparison ({this.selectedLanguagePluginId}). Please select a valid, loaded & running language plugin.";
this.loadingIssue = string.Format(T("Was not able to load the language plugin for comparison ({0}). Please select a valid, loaded & running language plugin."), this.selectedLanguagePluginId);
this.selectedLanguagePlugin = null;
}
else if (comparisonPlugin.IETFTag != this.selectedTargetLanguage.ToIETFTag())
{
this.loadingIssue = $"The selected language plugin for comparison uses the IETF tag '{comparisonPlugin.IETFTag}' which does not match the selected target language '{this.selectedTargetLanguage.ToIETFTag()}'. Please select a valid, loaded & running language plugin which matches the target language.";
this.loadingIssue = string.Format(T("The selected language plugin for comparison uses the IETF tag '{0}' which does not match the selected target language '{1}'. Please select a valid, loaded & running language plugin which matches the target language."), comparisonPlugin.IETFTag, this.selectedTargetLanguage.ToIETFTag());
this.selectedLanguagePlugin = null;
}
else
@@ -165,7 +162,7 @@ public partial class AssistantI18N : AssistantBaseCore<SettingsDialogI18N>
{
if (this.selectedLanguagePlugin is null)
{
this.loadingIssue = "Please select a language plugin for comparison.";
this.loadingIssue = T("Please select a language plugin for comparison.");
this.localizationPossible = false;
this.isLoading = false;
this.StateHasChanged();
@@ -202,7 +199,7 @@ public partial class AssistantI18N : AssistantBaseCore<SettingsDialogI18N>
break;
case NoPlugin:
this.loadingIssue = "Was not able to load the I18N plugin. Please check the plugin code.";
this.loadingIssue = T("Was not able to load the I18N plugin. Please check the plugin code.");
break;
case { IsValid: false } plugin when plugin.Issues.Any():
@@ -241,7 +238,7 @@ public partial class AssistantI18N : AssistantBaseCore<SettingsDialogI18N>
private string? ValidatingTargetLanguage(CommonLanguages language)
{
if(language == CommonLanguages.AS_IS)
return "Please select a target language.";
return T("Please select a target language.");
return null;
}
@@ -249,13 +246,19 @@ public partial class AssistantI18N : AssistantBaseCore<SettingsDialogI18N>
private string? ValidateCustomLanguage(string language)
{
if(this.selectedTargetLanguage == CommonLanguages.OTHER && string.IsNullOrWhiteSpace(language))
return "Please provide a custom language.";
return T("Please provide a custom language.");
return null;
}
private int NumTotalItems => (this.selectedLanguagePlugin?.Content.Count ?? 0) + this.addedContent.Count - this.removedContent.Count;
private string AddedContentText => string.Format(T("Added Content ({0} entries)"), this.addedContent.Count);
private string RemovedContentText => string.Format(T("Removed Content ({0} entries)"), this.removedContent.Count);
private string LocalizedContentText => string.Format(T("Localized Content ({0} entries of {1})"), this.localizedContent.Count, this.NumTotalItems);
private async Task LocalizeTextContent()
{
await this.form!.Validate();
File diff suppressed because it is too large. Load diff
@@ -1,15 +1,15 @@
@attribute [Route(Routes.ASSISTANT_JOB_POSTING)]
@inherits AssistantBaseCore<AIStudio.Dialogs.Settings.SettingsDialogJobPostings>
<MudTextField T="string" @bind-Text="@this.inputCompanyName" Label="(Optional) The company name" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Warehouse" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputCountryLegalFramework" Label="Provide the country, where the company is located" Validation="@this.ValidateCountryLegalFramework" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Flag" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3" HelperText="This is important to consider the legal framework of the country."/>
<MudTextField T="string" @bind-Text="@this.inputMandatoryInformation" Label="(Optional) Provide mandatory information" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.TextSnippet" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Mandatory information that your company requires for all job postings. This can include the company description, etc." />
<MudTextField T="string" @bind-Text="@this.inputJobDescription" Label="Job description" Validation="@this.ValidateJobDescription" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Settings" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Describe what the person is supposed to do in the company. This might be just short bullet points." />
<MudTextField T="string" @bind-Text="@this.inputQualifications" Label="(Optional) Provide necessary job qualifications" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Settings" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Describe what the person should bring to the table. This might be just short bullet points." />
<MudTextField T="string" @bind-Text="@this.inputResponsibilities" Label="(Optional) Provide job responsibilities" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Settings" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Describe the responsibilities the person should take on in the company." />
<MudTextField T="string" @bind-Text="@this.inputWorkLocation" Label="(Optional) Provide the work location" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.MyLocation" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputEntryDate" Label="(Optional) Provide the entry date" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.DateRange" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputValidUntil" Label="(Optional) Provide the date until the job posting is valid" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.DateRange" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputCompanyName" Label="@T("(Optional) The company name")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Warehouse" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputCountryLegalFramework" Label="@T("Provide the country, where the company is located")" Validation="@this.ValidateCountryLegalFramework" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Flag" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3" HelperText="@T("This is important to consider the legal framework of the country.")"/>
<MudTextField T="string" @bind-Text="@this.inputMandatoryInformation" Label="@T("(Optional) Provide mandatory information")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.TextSnippet" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@T("Mandatory information that your company requires for all job postings. This can include the company description, etc.")" />
<MudTextField T="string" @bind-Text="@this.inputJobDescription" Label="@T("Job description")" Validation="@this.ValidateJobDescription" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Settings" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@T("Describe what the person is supposed to do in the company. This might be just short bullet points.")" />
<MudTextField T="string" @bind-Text="@this.inputQualifications" Label="@T("(Optional) Provide necessary job qualifications")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Settings" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@T("Describe what the person should bring to the table. This might be just short bullet points.")" />
<MudTextField T="string" @bind-Text="@this.inputResponsibilities" Label="@T("(Optional) Provide job responsibilities")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Settings" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@T("Describe the responsibilities the person should take on in the company.")" />
<MudTextField T="string" @bind-Text="@this.inputWorkLocation" Label="@T("(Optional) Provide the work location")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.MyLocation" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputEntryDate" Label="@T("(Optional) Provide the entry date")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.DateRange" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputValidUntil" Label="@T("(Optional) Provide the date until the job posting is valid")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.DateRange" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" Class="mb-3"/>
<EnumSelection T="CommonLanguages" NameFunc="@(language => language.NameSelectingOptional())" @bind-Value="@this.selectedTargetLanguage" Icon="@Icons.Material.Filled.Translate" Label="Target language" AllowOther="@true" OtherValue="CommonLanguages.OTHER" @bind-OtherInput="@this.customTargetLanguage" ValidateOther="@this.ValidateCustomLanguage" LabelOther="Custom target language" />
<EnumSelection T="CommonLanguages" NameFunc="@(language => language.NameSelectingOptional())" @bind-Value="@this.selectedTargetLanguage" Icon="@Icons.Material.Filled.Translate" Label="@T("Target language")" AllowOther="@true" OtherValue="CommonLanguages.OTHER" @bind-OtherInput="@this.customTargetLanguage" ValidateOther="@this.ValidateCustomLanguage" LabelOther="@T("Custom target language")" />
<ProviderSelection @bind-ProviderSettings="@this.providerSettings" ValidateProvider="@this.ValidatingProvider"/>
@@ -7,13 +7,9 @@ public partial class AssistantJobPostings : AssistantBaseCore<SettingsDialogJobP
{
public override Tools.Components Component => Tools.Components.JOB_POSTING_ASSISTANT;
protected override string Title => "Job Posting";
protected override string Title => T("Job Posting");
protected override string Description =>
"""
Provide some key points about the job you want to post. The AI will then
formulate a suggestion that you can finalize.
""";
protected override string Description => T("Provide some key points about the job you want to post. The AI will then formulate a suggestion that you can finalize.");
protected override string SystemPrompt =>
$"""
@@ -47,7 +43,7 @@ public partial class AssistantJobPostings : AssistantBaseCore<SettingsDialogJobP
protected override IReadOnlyList<IButtonData> FooterButtons => [];
protected override string SubmitText => "Create the job posting";
protected override string SubmitText => T("Create the job posting");
protected override Func<Task> SubmitAction => this.CreateJobPosting;
@@ -126,7 +122,7 @@ public partial class AssistantJobPostings : AssistantBaseCore<SettingsDialogJobP
private string? ValidateCustomLanguage(string language)
{
if(this.selectedTargetLanguage == CommonLanguages.OTHER && string.IsNullOrWhiteSpace(language))
return "Please provide a custom target language.";
return T("Please provide a custom target language.");
return null;
}
@@ -134,7 +130,7 @@ public partial class AssistantJobPostings : AssistantBaseCore<SettingsDialogJobP
private string? ValidateJobDescription(string jobDescription)
{
if(string.IsNullOrWhiteSpace(jobDescription))
return "Please provide a job description.";
return T("Please provide a job description.");
return null;
}
@@ -142,7 +138,7 @@ public partial class AssistantJobPostings : AssistantBaseCore<SettingsDialogJobP
private string? ValidateCountryLegalFramework(string countryLegalFramework)
{
if(string.IsNullOrWhiteSpace(countryLegalFramework))
return "Please provide the country where the job is posted (legal framework).";
return T("Please provide the country where the job is posted (legal framework).");
return null;
}
@@ -13,6 +13,7 @@ public partial class Changelog
public static readonly Log[] LOGS =
[
new (221, "v0.9.46, build 221 (2025-06-01 19:19 UTC)", "v0.9.46.md"),
new (220, "v0.9.45, build 220 (2025-05-25 13:56 UTC)", "v0.9.45.md"),
new (219, "v0.9.44, build 219 (2025-05-18 19:33 UTC)", "v0.9.44.md"),
new (218, "v0.9.43, build 218 (2025-05-11 17:22 UTC)", "v0.9.43.md"),
@@ -0,0 +1,22 @@
@if (!this.IsInline)
{
@if (this.ParentTabs is null)
{
<MudPaper Class="code-block no-elevation" Style="@this.BlockPadding">
<pre>
<code>
@this.ChildContent
</code>
</pre>
</MudPaper>
}
}
else
{
<span class="inline-code-block">
<kbd>
@this.ChildContent
</kbd>
</span>
}
@@ -0,0 +1,37 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
namespace AIStudio.Components;
public partial class CodeBlock : ComponentBase
{
[Parameter]
public RenderFragment? ChildContent { get; set; }
[Parameter]
public string? Title { get; set; } = string.Empty;
[Parameter]
public bool IsInline { get; set; }
[CascadingParameter]
public CodeTabs? ParentTabs { get; set; }
protected override void OnInitialized()
{
if (this.ParentTabs is not null && this.Title is not null)
{
void BlockSelf(RenderTreeBuilder builder)
{
builder.OpenComponent<CodeBlock>(0);
builder.AddAttribute(1, "Title", this.Title);
builder.AddAttribute(2, "ChildContent", this.ChildContent);
builder.CloseComponent();
}
this.ParentTabs.RegisterBlock(this.Title, BlockSelf);
}
}
private string BlockPadding => this.ParentTabs is null ? "padding: 16px !important;" : "padding: 8px !important";
}
@@ -0,0 +1,11 @@
<MudTabs ActivePanelIndex="this.SelectedIndex" ActivePanelIndexChanged="async idx => await this.TabChanged(idx)" PanelClass="code-block mt-1" MinimumTabWidth="30px" Class="mt-2">
@foreach (var block in this.blocks)
{
<MudTabPanel Text="@block.Title">
@block.Fragment
</MudTabPanel>
}
</MudTabs>
<CascadingValue Value="this">
@this.ChildContent
</CascadingValue>
@@ -0,0 +1,42 @@
using Microsoft.AspNetCore.Components;
namespace AIStudio.Components;
public partial class CodeTabs : ComponentBase
{
[Parameter]
public RenderFragment? ChildContent { get; set; }
[Parameter]
public int SelectedIndex { get; set; }
[Parameter]
public EventCallback<int> SelectedIndexChanged { get; set; }
private readonly List<CodeTabItem> blocks = new();
internal void RegisterBlock(string title, RenderFragment fragment)
{
this.blocks.Add(new CodeTabItem
{
Title = title,
Fragment = fragment,
});
this.StateHasChanged();
}
private class CodeTabItem
{
public string Title { get; init; } = string.Empty;
public RenderFragment Fragment { get; init; } = null!;
}
private async Task TabChanged(int index)
{
this.SelectedIndex = index;
await this.SelectedIndexChanged.InvokeAsync(index);
await this.InvokeAsync(this.StateHasChanged);
}
}
@@ -44,7 +44,7 @@ public partial class ConfidenceInfo : MSGComponentBase
{
var index = 0;
foreach (var source in this.currentConfidence.Sources)
yield return ($"Source {++index}", source);
yield return (string.Format(T("Source {0}"), ++index), source);
}
private string GetCurrentConfidenceColor() => $"color: {this.currentConfidence.Level.GetColor(this.SettingsManager)};";
@@ -56,7 +56,7 @@
}
else if (this.showDataSourceSelection)
{
<MudTextSwitch Label="Are data sources enabled?" Value="@this.areDataSourcesEnabled" LabelOn="@T("Yes, I want to use data sources.")" LabelOff="@T("No, I don't want to use data sources.")" ValueChanged="@this.EnabledChanged"/>
<MudTextSwitch Label="@T("Are data sources enabled?")" Value="@this.areDataSourcesEnabled" LabelOn="@T("Yes, I want to use data sources.")" LabelOff="@T("No, I don't want to use data sources.")" ValueChanged="@this.EnabledChanged"/>
@if (this.areDataSourcesEnabled)
{
<MudTextSwitch Label="@T("AI-based data source selection")" Value="@this.aiBasedSourceSelection" LabelOn="@T("Yes, let the AI decide which data sources are needed.")" LabelOff="@T("No, I manually decide which data source to use.")" ValueChanged="@this.AutoModeChanged"/>
@@ -1,4 +1,4 @@
<MudExpansionPanel Class="border-solid border rounded-lg" Expanded="@this.IsExpanded">
<MudExpansionPanel Class="border-solid border rounded-lg" Expanded="@this.IsExpanded" MaxHeight="@this.MaxHeight" ExpandedChanged="async s => await this.ExpandedChanged(s)">
<TitleContent>
<div class="d-flex align-center">
<MudIcon Icon="@this.HeaderIcon" Size="@this.IconSize" Color="@this.IconColor" class="mr-3"/>
@@ -16,6 +16,12 @@ public partial class ExpansionPanel : ComponentBase
[Parameter]
public string HeaderText { get; set; } = "n/a";
[Parameter]
public int? MaxHeight { get; set; }
[Parameter]
public Func<bool, Task> ExpandedChanged { get; set; } = _ => Task.CompletedTask;
[Parameter]
public RenderFragment? ChildContent { get; set; }
@@ -0,0 +1,10 @@
@inherits MSGComponentBase
<MudStack Row="false" Class="mb-3 pa-3 border-dashed border rounded-lg">
<MudJustifiedText Typo="Typo.body1">
@this.DetermineIntroText()
</MudJustifiedText>
<MudButton Color="@this.DetermineButtonColor()" Variant="Variant.Filled" OnClick="() => this.ShowPandocDialogAsync()">
@this.DetermineButtonText()
</MudButton>
</MudStack>
@@ -0,0 +1,97 @@
using AIStudio.Dialogs;
using AIStudio.Tools.Services;
using Microsoft.AspNetCore.Components;
using DialogOptions = AIStudio.Dialogs.DialogOptions;
namespace AIStudio.Components;
public partial class ManagePandocDependency : MSGComponentBase
{
[Parameter]
public string IntroText { get; set; } = string.Empty;
[Inject]
private IDialogService DialogService { get; init; } = null!;
[Inject]
private RustService RustService { get; init; } = null!;
private PandocInstallation pandocInstallation;
#region Overrides of MSGComponentBase
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
this.pandocInstallation = await Pandoc.CheckAvailabilityAsync(this.RustService, false);
}
#endregion
private Color DetermineButtonColor()
{
if (this.pandocInstallation == default)
return Color.Default;
switch (this.pandocInstallation)
{
case { CheckWasSuccessful: true, IsAvailable: true }:
return Color.Default;
case { CheckWasSuccessful: true, IsAvailable: false }:
return Color.Warning;
case { CheckWasSuccessful: false }:
return Color.Error;
}
}
private string DetermineButtonText()
{
if(this.pandocInstallation == default)
return T("Please wait while we check the availability of Pandoc.");
switch (this.pandocInstallation)
{
case { CheckWasSuccessful: true, IsAvailable: true }:
return T("Check your Pandoc installation");
case { CheckWasSuccessful: true, IsAvailable: false }:
return T("Update Pandoc");
case { CheckWasSuccessful: false }:
return T("Install Pandoc");
}
}
private string DetermineIntroText()
{
if (this.pandocInstallation == default)
return $"{this.IntroText} {T("Please wait while we check the availability of Pandoc.")}";
switch (this.pandocInstallation)
{
case { CheckWasSuccessful: true, IsAvailable: true }:
return $"{this.IntroText} {T("Your Pandoc installation meets the requirements.")}";
case { CheckWasSuccessful: true, IsAvailable: false }:
return $"{this.IntroText} {T("Your Pandoc installation is outdated. Please update it to the latest version to ensure compatibility with all features.")}";
case { CheckWasSuccessful: false }:
return $"{this.IntroText} {T("Pandoc is not installed or not available. Please install it to use the features that require Pandoc.")}";
}
}
private async Task ShowPandocDialogAsync()
{
var dialogReference = await this.DialogService.ShowAsync<PandocDialog>(T("Pandoc Installation"), DialogOptions.FULLSCREEN);
await dialogReference.Result;
// Refresh the availability of Pandoc after the dialog is closed:
this.pandocInstallation = await Pandoc.CheckAvailabilityAsync(this.RustService, false);
await this.InvokeAsync(this.StateHasChanged);
}
}
@@ -1,3 +1,5 @@
@inherits MSGComponentBase
<MudStack Row="@true" Spacing="3" Class="mb-3" StretchItems="StretchItems.None" AlignItems="AlignItems.Center">
<MudTextField
T="string"
@@ -12,6 +14,6 @@
/>
<MudButton StartIcon="@Icons.Material.Filled.FolderOpen" Variant="Variant.Outlined" Color="Color.Primary" Disabled="this.Disabled" OnClick="@this.OpenDirectoryDialog">
Choose Directory
@T("Choose Directory")
</MudButton>
</MudStack>
@@ -1,11 +1,10 @@
using AIStudio.Settings;
using AIStudio.Tools.Services;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Components;
public partial class SelectDirectory : ComponentBase
public partial class SelectDirectory : MSGComponentBase
{
[Parameter]
public string Directory { get; set; } = string.Empty;
@@ -24,9 +23,6 @@ public partial class SelectDirectory : ComponentBase
[Parameter]
public Func<string, string?> Validation { get; set; } = _ => null;
[Inject]
private SettingsManager SettingsManager { get; init; } = null!;
[Inject]
public RustService RustService { get; set; } = null!;
@@ -1,3 +1,5 @@
@inherits MSGComponentBase
<MudStack Row="@true" Spacing="3" Class="mb-3" StretchItems="StretchItems.None" AlignItems="AlignItems.Center">
<MudTextField
T="string"
@@ -12,6 +14,6 @@
/>
<MudButton StartIcon="@Icons.Material.Filled.FolderOpen" Variant="Variant.Outlined" Color="Color.Primary" Disabled="this.Disabled" OnClick="@this.OpenFileDialog">
Choose File
@T("Choose File")
</MudButton>
</MudStack>
@@ -1,4 +1,3 @@
using AIStudio.Settings;
using AIStudio.Tools.Rust;
using AIStudio.Tools.Services;
@@ -6,7 +5,7 @@ using Microsoft.AspNetCore.Components;
namespace AIStudio.Components;
public partial class SelectFile : ComponentBase
public partial class SelectFile : MSGComponentBase
{
[Parameter]
public string File { get; set; } = string.Empty;
@@ -28,9 +27,6 @@ public partial class SelectFile : ComponentBase
[Parameter]
public Func<string, string?> Validation { get; set; } = _ => null;
[Inject]
private SettingsManager SettingsManager { get; init; } = null!;
[Inject]
public RustService RustService { get; set; } = null!;
@@ -3,10 +3,9 @@
<ExpansionPanel HeaderIcon="@Icons.Material.Filled.TextFields" HeaderText="Agent: Text Content Cleaner Options">
<MudPaper Class="pa-3 mb-8 border-dashed border rounded-lg">
<MudText Typo="Typo.body1" Class="mb-3">
Use Case: this agent is used to clean up text content. It extracts the main content, removes advertisements and other irrelevant things,
and attempts to convert relative links into absolute links so that they can be used.
@T("Use Case: this agent is used to clean up text content. It extracts the main content, removes advertisements and other irrelevant things, and attempts to convert relative links into absolute links so that they can be used.")
</MudText>
<ConfigurationOption OptionDescription="Preselect text content cleaner options?" LabelOn="Options are preselected" LabelOff="No options are preselected" State="@(() => this.SettingsManager.ConfigurationData.TextContentCleaner.PreselectAgentOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.TextContentCleaner.PreselectAgentOptions = updatedState)" OptionHelp="When enabled, you can preselect some agent options. This is might be useful when you prefer an LLM."/>
<ConfigurationOption OptionDescription="@T("Preselect text content cleaner options?")" LabelOn="@T("Options are preselected")" LabelOff="@T("No options are preselected")" State="@(() => this.SettingsManager.ConfigurationData.TextContentCleaner.PreselectAgentOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.TextContentCleaner.PreselectAgentOptions = updatedState)" OptionHelp="@T("When enabled, you can preselect some agent options. This is might be useful when you prefer an LLM.")"/>
<ConfigurationProviderSelection Data="@this.AvailableLLMProvidersFunc()" Disabled="@(() => !this.SettingsManager.ConfigurationData.TextContentCleaner.PreselectAgentOptions)" SelectedValue="@(() => this.SettingsManager.ConfigurationData.TextContentCleaner.PreselectedAgentProvider)" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.TextContentCleaner.PreselectedAgentProvider = selectedValue)"/>
</MudPaper>
</ExpansionPanel>
@@ -1,11 +1,11 @@
@inherits SettingsPanelBase
<ExpansionPanel HeaderIcon="@Icons.Material.Filled.SelectAll" HeaderText="Agent: Data Source Selection Options">
<ExpansionPanel HeaderIcon="@Icons.Material.Filled.SelectAll" HeaderText="@T("Agent: Data Source Selection Options")">
<MudPaper Class="pa-3 mb-8 border-dashed border rounded-lg">
<MudText Typo="Typo.body1" Class="mb-3">
Use Case: this agent is used to select the appropriate data sources for the current prompt.
@T("Use Case: this agent is used to select the appropriate data sources for the current prompt.")
</MudText>
<ConfigurationOption OptionDescription="Preselect data source selection options?" LabelOn="Options are preselected" LabelOff="No options are preselected" State="@(() => this.SettingsManager.ConfigurationData.AgentDataSourceSelection.PreselectAgentOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.AgentDataSourceSelection.PreselectAgentOptions = updatedState)" OptionHelp="When enabled, you can preselect some agent options. This is might be useful when you prefer an LLM."/>
<ConfigurationOption OptionDescription="@T("Preselect data source selection options?")" LabelOn="@T("Options are preselected")" LabelOff="@T("No options are preselected")" State="@(() => this.SettingsManager.ConfigurationData.AgentDataSourceSelection.PreselectAgentOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.AgentDataSourceSelection.PreselectAgentOptions = updatedState)" OptionHelp="@T("When enabled, you can preselect some agent options. This is might be useful when you prefer an LLM.")"/>
<ConfigurationProviderSelection Data="@this.AvailableLLMProvidersFunc()" Disabled="@(() => !this.SettingsManager.ConfigurationData.AgentDataSourceSelection.PreselectAgentOptions)" SelectedValue="@(() => this.SettingsManager.ConfigurationData.AgentDataSourceSelection.PreselectedAgentProvider)" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.AgentDataSourceSelection.PreselectedAgentProvider = selectedValue)"/>
</MudPaper>
</ExpansionPanel>
@@ -1,17 +1,15 @@
@inherits SettingsPanelBase
<ExpansionPanel HeaderIcon="@Icons.Material.Filled.Assessment" HeaderText="Agent: Retrieval Context Validation Options">
<ExpansionPanel HeaderIcon="@Icons.Material.Filled.Assessment" HeaderText="@T("Agent: Retrieval Context Validation Options")">
<MudText Typo="Typo.body1" Class="mb-3">
Use Case: this agent is used to validate any retrieval context of any retrieval process. Perhaps there are many of these
retrieval contexts and you want to validate them all. Therefore, you might want to use a cheap and fast LLM for this
job. When using a local or self-hosted LLM, look for a small (e.g. 3B) and fast model.
@T("Use Case: this agent is used to validate any retrieval context of any retrieval process. Perhaps there are many of these retrieval contexts and you want to validate them all. Therefore, you might want to use a cheap and fast LLM for this job. When using a local or self-hosted LLM, look for a small (e.g. 3B) and fast model.")
</MudText>
<ConfigurationOption OptionDescription="Enable the retrieval context validation agent?" LabelOn="The validation agent is enabled" LabelOff="No validation is performed" State="@(() => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.EnableRetrievalContextValidation)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.EnableRetrievalContextValidation = updatedState)" OptionHelp="When enabled, the retrieval context validation agent will check each retrieval context of any retrieval process, whether a context makes sense for the given prompt."/>
<ConfigurationOption OptionDescription="@T("Enable the retrieval context validation agent?")" LabelOn="@T("The validation agent is enabled")" LabelOff="@T("No validation is performed")" State="@(() => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.EnableRetrievalContextValidation)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.EnableRetrievalContextValidation = updatedState)" OptionHelp="@T("When enabled, the retrieval context validation agent will check each retrieval context of any retrieval process, whether a context makes sense for the given prompt.")"/>
@if (this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.EnableRetrievalContextValidation)
{
<MudPaper Class="pa-3 mb-8 border-dashed border rounded-lg">
<ConfigurationOption OptionDescription="Preselect retrieval context validation options?" LabelOn="Options are preselected" LabelOff="No options are preselected" State="@(() => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectAgentOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectAgentOptions = updatedState)" OptionHelp="When enabled, you can preselect some agent options. This is might be useful when you prefer an LLM."/>
<ConfigurationSlider T="int" OptionDescription="How many validation agents should work simultaneously?" Min="1" Max="100" Step="1" Unit="agents" Value="@(() => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.NumParallelValidations)" ValueUpdate="@(updatedValue => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.NumParallelValidations = updatedValue)" OptionHelp="More active agents also mean that a corresponding number of requests are made simultaneously. Some providers limit the number of requests per minute. When you are unsure, choose a low setting between 1 to 6 agents."/>
<ConfigurationOption OptionDescription="@T("Preselect retrieval context validation options?")" LabelOn="@T("Options are preselected")" LabelOff="@T("No options are preselected")" State="@(() => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectAgentOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectAgentOptions = updatedState)" OptionHelp="@T("When enabled, you can preselect some agent options. This is might be useful when you prefer an LLM.")"/>
<ConfigurationSlider T="int" OptionDescription="@T("How many validation agents should work simultaneously?")" Min="1" Max="100" Step="1" Unit="@T("agents")" Value="@(() => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.NumParallelValidations)" ValueUpdate="@(updatedValue => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.NumParallelValidations = updatedValue)" OptionHelp="@T("More active agents also mean that a corresponding number of requests are made simultaneously. Some providers limit the number of requests per minute. When you are unsure, choose a low setting between 1 to 6 agents.")"/>
<ConfigurationProviderSelection Data="@this.AvailableLLMProvidersFunc()" Disabled="@(() => !this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectAgentOptions)" SelectedValue="@(() => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectedAgentProvider)" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectedAgentProvider = selectedValue)"/>
</MudPaper>
}
@@ -4,20 +4,16 @@
<ExpansionPanel HeaderIcon="@Icons.Material.Filled.Apps" HeaderText="@T("App Options")">
@if (PreviewFeatures.PRE_PLUGINS_2025.IsEnabled(this.SettingsManager))
<ConfigurationSelect OptionDescription="@T("Language behavior")" SelectedValue="@(() => this.SettingsManager.ConfigurationData.App.LanguageBehavior)" Data="@ConfigurationSelectDataFactory.GetLangBehaviorData()" SelectionUpdate="@(selectedValue => _ = this.UpdateLangBehaviour(selectedValue))" OptionHelp="@T("Select the language behavior for the app. The default is to use the system language. You might want to choose a language manually?")"/>
@if (this.SettingsManager.ConfigurationData.App.LanguageBehavior is LangBehavior.MANUAL)
{
<ConfigurationSelect OptionDescription="@T("Language behavior")" SelectedValue="@(() => this.SettingsManager.ConfigurationData.App.LanguageBehavior)" Data="@ConfigurationSelectDataFactory.GetLangBehaviorData()" SelectionUpdate="@(selectedValue => _ = this.UpdateLangBehaviour(selectedValue))" OptionHelp="@T("Select the language behavior for the app. The default is to use the system language. You might want to choose a language manually?")"/>
@if (this.SettingsManager.ConfigurationData.App.LanguageBehavior is LangBehavior.MANUAL)
{
<ConfigurationSelect OptionDescription="@T("Language")" SelectedValue="@(() => this.SettingsManager.ConfigurationData.App.LanguagePluginId)" Data="@ConfigurationSelectDataFactory.GetLanguagesData()" SelectionUpdate="@(selectedValue => _ = this.UpdateManuallySelectedLanguage(selectedValue))" OptionHelp="@T("Select the language for the app.")"/>
}
<ConfigurationSelect OptionDescription="@T("Language")" SelectedValue="@(() => this.SettingsManager.ConfigurationData.App.LanguagePluginId)" Data="@ConfigurationSelectDataFactory.GetLanguagesData()" SelectionUpdate="@(selectedValue => _ = this.UpdateManuallySelectedLanguage(selectedValue))" OptionHelp="@T("Select the language for the app.")"/>
}
<ConfigurationSelect OptionDescription="@T("Color theme")" SelectedValue="@(() => this.SettingsManager.ConfigurationData.App.PreferredTheme)" Data="@ConfigurationSelectDataFactory.GetThemesData()" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.App.PreferredTheme = selectedValue)" OptionHelp="@T("Choose the color theme that best suits for you.")"/>
<ConfigurationOption OptionDescription="@T("Save energy?")" LabelOn="@T("Energy saving is enabled")" LabelOff="@T("Energy saving is disabled")" State="@(() => this.SettingsManager.ConfigurationData.App.IsSavingEnergy)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.App.IsSavingEnergy = updatedState)" OptionHelp="@T("When enabled, streamed content from the AI is updated once every third second. When disabled, streamed content will be updated as soon as it is available.")"/>
<ConfigurationOption OptionDescription="@T("Enable spellchecking?")" LabelOn="@T("Spellchecking is enabled")" LabelOff="@T("Spellchecking is disabled")" State="@(() => this.SettingsManager.ConfigurationData.App.EnableSpellchecking)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.App.EnableSpellchecking = updatedState)" OptionHelp="@T("When enabled, spellchecking will be active in all input fields. Depending on your operating system, errors may not be visually highlighted, but right-clicking may still offer possible corrections.")"/>
<ConfigurationSelect OptionDescription="@T("Check for updates")" SelectedValue="@(() => this.SettingsManager.ConfigurationData.App.UpdateBehavior)" Data="@ConfigurationSelectDataFactory.GetUpdateBehaviorData()" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.App.UpdateBehavior = selectedValue)" OptionHelp="@T("How often should we check for app updates?")"/>
<ConfigurationSelect OptionDescription="@T("Check for updates")" SelectedValue="@(() => this.SettingsManager.ConfigurationData.App.UpdateBehavior)" Data="@ConfigurationSelectDataFactory.GetUpdateBehaviorData()" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.App.UpdateBehavior = selectedValue)" OptionHelp="@T("How often should we check for app updates?")" Disabled="() => this.SettingsLocker.IsLocked<DataApp>(x => x.UpdateBehavior)"/>
<ConfigurationSelect OptionDescription="@T("Navigation bar behavior")" SelectedValue="@(() => this.SettingsManager.ConfigurationData.App.NavigationBehavior)" Data="@ConfigurationSelectDataFactory.GetNavBehaviorData()" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.App.NavigationBehavior = selectedValue)" OptionHelp="@T("Select the desired behavior for the navigation bar.")"/>
<ConfigurationSelect OptionDescription="@T("Preview feature visibility")" SelectedValue="@(() => this.SettingsManager.ConfigurationData.App.PreviewVisibility)" Data="@ConfigurationSelectDataFactory.GetPreviewVisibility()" SelectionUpdate="@this.UpdatePreviewFeatures" OptionHelp="@T("Do you want to show preview features in the app?")"/>
@@ -15,4 +15,7 @@ public abstract class SettingsPanelBase : MSGComponentBase
[Inject]
protected RustService RustService { get; init; } = null!;
[Inject]
protected SettingsLocker SettingsLocker { get; init; } = null!;
}
@@ -45,15 +45,24 @@
</MudTd>
<MudTd>
<MudStack Row="true" Class="mb-2 mt-2" Spacing="1" Wrap="Wrap.Wrap">
<MudTooltip Text="@T("Open Dashboard")">
<MudIconButton Color="Color.Info" Icon="@Icons.Material.Filled.OpenInBrowser" Href="@context.UsedLLMProvider.GetDashboardURL()" Target="_blank" Disabled="@(!context.UsedLLMProvider.HasDashboard())"/>
</MudTooltip>
<MudTooltip Text="@T("Edit")">
<MudIconButton Color="Color.Info" Icon="@Icons.Material.Filled.Edit" OnClick="() => this.EditLLMProvider(context)"/>
</MudTooltip>
<MudTooltip Text="@T("Delete")">
<MudIconButton Color="Color.Error" Icon="@Icons.Material.Filled.Delete" OnClick="() => this.DeleteLLMProvider(context)"/>
</MudTooltip>
@if (context.IsEnterpriseConfiguration)
{
<MudTooltip Text="@T("This provider is managed by your organization.")">
<MudIconButton Color="Color.Info" Icon="@Icons.Material.Filled.Business" Disabled="true"/>
</MudTooltip>
}
else
{
<MudTooltip Text="@T("Open Dashboard")">
<MudIconButton Color="Color.Info" Icon="@Icons.Material.Filled.OpenInBrowser" Href="@context.UsedLLMProvider.GetDashboardURL()" Target="_blank" Disabled="@(!context.UsedLLMProvider.HasDashboard())"/>
</MudTooltip>
<MudTooltip Text="@T("Edit")">
<MudIconButton Color="Color.Info" Icon="@Icons.Material.Filled.Edit" OnClick="() => this.EditLLMProvider(context)"/>
</MudTooltip>
<MudTooltip Text="@T("Delete")">
<MudIconButton Color="Color.Error" Icon="@Icons.Material.Filled.Delete" OnClick="() => this.DeleteLLMProvider(context)"/>
</MudTooltip>
}
</MudStack>
</MudTd>
</RowTemplate>
@@ -120,6 +120,8 @@
}
</MudSelect>
<MudNumericField T="ushort" Min="10" @bind-Value="@this.dataMaxMatches" Label="@T("How many matches do you want at most per query?")" Variant="Variant.Outlined" Step="10" />
</MudForm>
<Issues IssuesData="@this.dataIssues"/>
</DialogContent>
@@ -47,6 +47,7 @@ public partial class DataSourceERI_V1Dialog : MSGComponentBase, ISecretId
private List<AuthMethod> availableAuthMethods = [];
private DataSourceSecurity dataSecurityPolicy;
private SecurityRequirements dataSourceSecurityRequirements;
private ushort dataMaxMatches = 10;
private bool connectionTested;
private bool connectionSuccessfulTested;
@@ -104,6 +105,7 @@ public partial class DataSourceERI_V1Dialog : MSGComponentBase, ISecretId
this.dataAuthMethod = this.DataSource.AuthMethod;
this.dataUsername = this.DataSource.Username;
this.dataSecurityPolicy = this.DataSource.SecurityPolicy;
this.dataMaxMatches = this.DataSource.MaxMatches;
if (this.dataAuthMethod is AuthMethod.TOKEN or AuthMethod.USERNAME_PASSWORD)
{
@@ -114,7 +116,7 @@ public partial class DataSourceERI_V1Dialog : MSGComponentBase, ISecretId
else
{
this.dataSecret = string.Empty;
this.dataSecretStorageIssue = $"Failed to load the auth. secret from the operating system. The message was: {requestedSecret.Issue}. You might ignore this message and provide the secret again.";
this.dataSecretStorageIssue = string.Format(T("Failed to load the auth. secret from the operating system. The message was: {0}. You might ignore this message and provide the secret again."), requestedSecret.Issue);
await this.form.Validate();
}
}
@@ -164,6 +166,7 @@ public partial class DataSourceERI_V1Dialog : MSGComponentBase, ISecretId
Type = DataSourceType.ERI_V1,
SecurityPolicy = this.dataSecurityPolicy,
SelectedRetrievalId = this.dataSelectedRetrievalProcess.Id,
MaxMatches = this.dataMaxMatches,
};
}
@@ -27,6 +27,7 @@
<TextInfoLines Label="@T("Server description")" MaxLines="14" Value="@this.serverDescription" ClipboardTooltipSubject="@T("the server description")"/>
<TextInfoLines Label="@T("Security requirements of the data provider")" MaxLines="3" Value="@this.securityRequirements.Explain()" ClipboardTooltipSubject="@T("the security requirements of the data provider")"/>
<TextInfoLines Label="@T("Your security policy")" MaxLines="3" Value="@this.DataSource.SecurityPolicy.ToInfoText()" Color="@this.DataSource.SecurityPolicy.GetColor()" ClipboardTooltipSubject="@T("your security policy")"/>
<TextInfoLine Label="@T("Maximum matches per query")" Value="@this.DataSource.MaxMatches.ToString()" ClipboardTooltipSubject="@T("the maximum number of matches per query")"/>
<MudText Typo="Typo.h5" Class="mt-6">
@T("Retrieval information")
@@ -60,6 +60,8 @@
</MudJustifiedText>
}
}
<ManagePandocDependency IntroText="@T("For some data types, such as Office files, MindWork AI Studio requires the open-source application Pandoc.")"/>
<MudSelect @bind-Value="@this.dataSecurityPolicy" Text="@this.dataSecurityPolicy.ToSelectionText()" Label="@T("Your security policy")" Class="mb-3" OpenIcon="@Icons.Material.Filled.ExpandMore" AdornmentColor="Color.Info" Adornment="Adornment.Start" Validation="@this.dataSourceValidation.ValidateSecurityPolicy">
@foreach (var policy in Enum.GetValues<DataSourceSecurity>())
@@ -69,6 +71,8 @@
</MudSelectItem>
}
</MudSelect>
<MudNumericField T="ushort" Min="10" @bind-Value="@this.dataMaxMatches" Label="@T("How many matches do you want at most per query?")" Variant="Variant.Outlined" Step="10" />
</MudForm>
<Issues IssuesData="@this.dataIssues"/>
</DialogContent>
@@ -40,6 +40,7 @@ public partial class DataSourceLocalDirectoryDialog : MSGComponentBase
private bool dataUserAcknowledgedCloudEmbedding;
private string dataEmbeddingId = string.Empty;
private string dataPath = string.Empty;
private ushort dataMaxMatches = 10;
private DataSourceSecurity dataSecurityPolicy;
// We get the form reference from Blazor code to validate it manually:
@@ -75,6 +76,7 @@ public partial class DataSourceLocalDirectoryDialog : MSGComponentBase
this.dataEmbeddingId = this.DataSource.EmbeddingId;
this.dataPath = this.DataSource.Path;
this.dataSecurityPolicy = this.DataSource.SecurityPolicy;
this.dataMaxMatches = this.DataSource.MaxMatches;
}
await base.OnInitializedAsync();
@@ -103,6 +105,7 @@ public partial class DataSourceLocalDirectoryDialog : MSGComponentBase
EmbeddingId = this.dataEmbeddingId,
Path = this.dataPath,
SecurityPolicy = this.dataSecurityPolicy,
MaxMatches = this.dataMaxMatches,
};
private async Task Store()
@@ -34,6 +34,7 @@
}
<TextInfoLines Label="@T("Your security policy")" MaxLines="3" Value="@this.DataSource.SecurityPolicy.ToInfoText()" Color="@this.DataSource.SecurityPolicy.GetColor()" ClipboardTooltipSubject="@T("your security policy")"/>
<TextInfoLine Label="@T("Maximum matches per query")" Value="@this.DataSource.MaxMatches.ToString()" ClipboardTooltipSubject="@T("the maximum number of matches per query")"/>
<TextInfoLine Icon="@Icons.Material.Filled.SquareFoot" Label="@T("Number of files")" Value="@this.NumberFilesInDirectory" ClipboardTooltipSubject="@T("the number of files in the directory")"/>
<TextInfoLines Label="@T("Files list")" MaxLines="14" Value="@this.directoryFiles.ToString()" ClipboardTooltipSubject="@T("the files list")"/>
@@ -60,6 +60,8 @@
</MudJustifiedText>
}
}
<ManagePandocDependency IntroText="@T("For some data types, such as Office files, MindWork AI Studio requires the open-source application Pandoc.")"/>
<MudSelect @bind-Value="@this.dataSecurityPolicy" Text="@this.dataSecurityPolicy.ToSelectionText()" Label="@T("Your security policy")" Class="mb-3" OpenIcon="@Icons.Material.Filled.ExpandMore" AdornmentColor="Color.Info" Adornment="Adornment.Start" Validation="@this.dataSourceValidation.ValidateSecurityPolicy">
@foreach (var policy in Enum.GetValues<DataSourceSecurity>())
@@ -69,6 +71,8 @@
</MudSelectItem>
}
</MudSelect>
<MudNumericField T="ushort" Min="10" @bind-Value="@this.dataMaxMatches" Label="@T("How many matches do you want at most per query?")" Variant="Variant.Outlined" Step="10" />
</MudForm>
<Issues IssuesData="@this.dataIssues"/>
</DialogContent>
@@ -40,6 +40,7 @@ public partial class DataSourceLocalFileDialog : MSGComponentBase
private bool dataUserAcknowledgedCloudEmbedding;
private string dataEmbeddingId = string.Empty;
private string dataFilePath = string.Empty;
private ushort dataMaxMatches = 10;
private DataSourceSecurity dataSecurityPolicy;
// We get the form reference from Blazor code to validate it manually:
@@ -75,6 +76,7 @@ public partial class DataSourceLocalFileDialog : MSGComponentBase
this.dataEmbeddingId = this.DataSource.EmbeddingId;
this.dataFilePath = this.DataSource.FilePath;
this.dataSecurityPolicy = this.DataSource.SecurityPolicy;
this.dataMaxMatches = this.DataSource.MaxMatches;
}
await base.OnInitializedAsync();
@@ -103,6 +105,7 @@ public partial class DataSourceLocalFileDialog : MSGComponentBase
EmbeddingId = this.dataEmbeddingId,
FilePath = this.dataFilePath,
SecurityPolicy = this.dataSecurityPolicy,
MaxMatches = this.dataMaxMatches,
};
private async Task Store()
@@ -4,7 +4,6 @@
<MudDialog>
<DialogContent>
<TextInfoLine Icon="@Icons.Material.Filled.Tag" Label="@T("Data source name")" Value="@this.DataSource.Name" ClipboardTooltipSubject="@T("the data source name")"/>
<TextInfoLine Icon="@Icons.Material.Filled.FolderOpen" Label="@T("File path")" Value="@this.DataSource.FilePath" ClipboardTooltipSubject="@T("this path")"/>
@if (!this.IsFileAvailable)
{
@@ -34,6 +33,7 @@
}
<TextInfoLines Label="@T("Your security policy")" MaxLines="3" Value="@this.DataSource.SecurityPolicy.ToInfoText()" Color="@this.DataSource.SecurityPolicy.GetColor()" ClipboardTooltipSubject="@T("your security policy")"/>
<TextInfoLine Label="@T("Maximum matches per query")" Value="@this.DataSource.MaxMatches.ToString()" ClipboardTooltipSubject="@T("the maximum number of matches per query")"/>
<TextInfoLine Icon="@Icons.Material.Filled.SquareFoot" Label="@T("File size")" Value="@this.FileSize" ClipboardTooltipSubject="@T("the file size")"/>
</DialogContent>
<DialogActions>
@@ -0,0 +1,229 @@
@inherits MSGComponentBase
<MudDialog>
<DialogContent>
@if (this.isInstallationInProgress)
{
<MudText Typo="Typo.h4" Class="mb-3">
@T("Please wait for the installation to complete...")
</MudText>
<MudProgressLinear Color="Color.Primary" Indeterminate="@true" Size="Size.Large" Rounded="@true"/>
}
else if (this.ShowInstallationPage)
{
<div class="mb-4">
<MudJustifiedText Typo="Typo.body1" Class="mb-2">
@T("AI Studio uses the free and open-source third-party app Pandoc to process and retrieve data from local Office files (such as Word files) or to generate Office documents.")
</MudJustifiedText>
<MudJustifiedText Typo="Typo.body1">
@T("Unfortunately, Pandoc's GPL license isn't compatible with the AI Studios licenses. However, software under the GPL is free to use and free of charge. You'll need to accept the GPL license before we can download and install Pandoc for you automatically (recommended). Alternatively, you might download it yourself using the instructions below or install it otherwise, e.g., by using a package manager of your operating system.")
</MudJustifiedText>
</div>
<MudExpansionPanels Class="mb-3" MultiExpansion="@false" Outlined="false" Elevation="0">
<ExpansionPanel HeaderIcon="@Icons.Material.Filled.Verified" HeaderText="@T("View the GNU General Public License v2 (GPL)")" MaxHeight="300" ExpandedChanged="this.WhenExpandingLicence">
@if (this.isLoadingLicence)
{
<MudSkeleton/>
<MudSkeleton Animation="Animation.Wave"/>
<MudSkeleton/>
}
else if (!string.IsNullOrWhiteSpace(this.licenseText))
{
<MudMarkdown Value="@this.licenseText" OverrideHeaderTypo="@Markdown.OverrideHeaderTypo"/>
}
</ExpansionPanel>
<ExpansionPanel HeaderIcon="@Icons.Material.Filled.AutoFixHigh" HeaderText="@T("Automatic installation")" IsExpanded="true">
<MudJustifiedText Typo="Typo.body1">
@T("""Pandoc is distributed under the GNU General Public License v2 (GPL). By clicking "Accept GPL and Install," you agree to the terms of the GPL license, and Pandoc will be installed automatically for you. Software under GPL is free of charge and free to use.""")
</MudJustifiedText>
<MudButton OnClick="this.InstallPandocAsync" Color="Color.Primary" Class="mt-4" Variant="Variant.Filled" Size="Size.Medium" StartIcon="@Icons.Material.Filled.InstallDesktop">
@T("Accept the GPL and start the installation")
</MudButton>
</ExpansionPanel>
<ExpansionPanel HeaderIcon="@Icons.Material.Filled.Build" HeaderText="@T("Manual installation")" ExpandedChanged="this.WhenExpandingManualInstallation">
<MudJustifiedText Typo="Typo.body1" Class="mb-2">
@T("If you want to install Pandoc yourself, follow one of these two guides. The first guide uses an installer and is available for Windows and macOS. Alternatively, you might use a package manager of your operating system to install Pandoc.")
</MudJustifiedText>
<MudExpansionPanels Outlined="false" Elevation="0">
<ExpansionPanel HeaderIcon="@Icons.Material.Filled.AppRegistration" HeaderText="@T("Download installer")" IsExpanded="true">
<MudList T="string">
<MudListItem T="string" Class="mb-2">
<MudJustifiedText Typo="Typo.body1">
@T("Accept the terms of the GPL license and download the latest installer with the download button below. Eventually, you need to allow the download of the installer in the download window.")
</MudJustifiedText>
<CodeTabs @bind-SelectedIndex="this.selectedInstallerIndex">
<CodeBlock Title="Windows">pandoc-@(LATEST_PANDOC_VERSION)-windows-x86_64.msi</CodeBlock>
<CodeBlock Title="macOS ARM">pandoc-@(LATEST_PANDOC_VERSION)-arm64-macOS.pkg</CodeBlock>
<CodeBlock Title="macOS x86">pandoc-@(LATEST_PANDOC_VERSION)-x86_64-macOS.pkg</CodeBlock>
</CodeTabs>
</MudListItem>
<MudListItem T="string">
<MudJustifiedText Typo="Typo.body1">
@T("Execute the installer and follow the instructions.")
</MudJustifiedText>
</MudListItem>
</MudList>
<MudJustifiedText Class="mb-3" Typo="Typo.body1">
@T("""Pandoc is distributed under the GNU General Public License v2 (GPL). By clicking "Accept GPL and download installer," you agree to the terms of the GPL license. Software under GPL is free of charge and free to use.""")
</MudJustifiedText>
<MudButton Href="@this.downloadUrlInstaller" Target="_blank" Color="Color.Primary" Class="mt-4" Variant="Variant.Filled" Size="Size.Medium" StartIcon="@Icons.Material.Filled.Downloading">
@T("Accept the GPL and download the installer")
</MudButton>
</ExpansionPanel>
<ExpansionPanel HeaderIcon="@Icons.Material.Outlined.Archive" HeaderText="Download archive">
<MudList T="string">
<MudListItem T="string" Class="mb-2">
<MudJustifiedText Typo="Typo.body1">
@T("Accept the terms of the GPL license and download the latest archive with the download button below.")
</MudJustifiedText>
</MudListItem>
<MudListItem T="string" Class="mb-2">
<MudJustifiedText Typo="Typo.body1">
@T("Extract the archive to a folder of your choice, e.g.:")
</MudJustifiedText>
<CodeTabs @bind-SelectedIndex="this.selectedArchiveIndex">
<CodeBlock Title="Windows">C:\Users\%USERNAME%\pandoc</CodeBlock>
<CodeBlock Title="macOS">~/pandoc</CodeBlock>
<CodeBlock Title="Linux">/usr/local/bin/pandoc</CodeBlock>
</CodeTabs>
</MudListItem>
<MudListItem T="string" Class="mb-2">
<MudJustifiedText Typo="Typo.body1">
@T("Open the folder and copy the full path to the folder where your Pandoc executable file is into your clipboard:")
</MudJustifiedText>
<CodeTabs @bind-SelectedIndex="this.selectedArchiveIndex">
<CodeBlock Title="Windows">C:\Users\%USERNAME%\pandoc\pandoc-@(LATEST_PANDOC_VERSION)</CodeBlock>
<CodeBlock Title="macOS">~/pandoc/pandoc-@(LATEST_PANDOC_VERSION)</CodeBlock>
<CodeBlock Title="Linux">/usr/local/bin/pandoc/pandoc-@(LATEST_PANDOC_VERSION)</CodeBlock>
</CodeTabs>
</MudListItem>
<MudListItem T="string">
<MudJustifiedText Typo="Typo.body1">
@T("Add the copied path to your system's or user's PATH environment variable, restart your terminal, and check the installation:")
</MudJustifiedText>
<CodeTabs @bind-SelectedIndex="this.selectedArchiveIndex">
<CodeBlock Title="Windows">> pandoc.exe --version<br/>> pandoc @(LATEST_PANDOC_VERSION)</CodeBlock>
<CodeBlock Title="macOS">> pandoc --version<br/>> pandoc @(LATEST_PANDOC_VERSION)</CodeBlock>
<CodeBlock Title="Linux">> pandoc --version<br/>> pandoc @(LATEST_PANDOC_VERSION)</CodeBlock>
</CodeTabs>
</MudListItem>
</MudList>
<MudText Class="mb-3" Typo="Typo.caption">
<MudJustifiedText Typo="Typo.body1">
@T("""Pandoc is distributed under the GNU General Public License v2 (GPL). By clicking "Accept GPL and archive," you agree to the terms of the GPL license. Software under GPL is free of charge and free to use.""")
</MudJustifiedText>
</MudText>
<MudButton Href="@this.downloadUrlArchive" Target="_blank" Color="Color.Primary" Class="mt-4" Variant="Variant.Filled" Size="Size.Medium" StartIcon="@Icons.Material.Filled.Downloading">
@T("Accept the GPL and download the archive")
</MudButton>
</ExpansionPanel>
</MudExpansionPanels>
</ExpansionPanel>
</MudExpansionPanels>
}
else
{
<MudItem Class="px-8 py-2">
@if (this.pandocInstallation == default)
{
<MudStack Row="true" AlignItems="AlignItems.Center">
<MudSkeleton SkeletonType="SkeletonType.Circle" Width="4em" Height="4em" Animation="Animation.Pulse"/>
<MudStack Row="false" Class="d-flex flex-column flex-grow-1">
<MudSkeleton Width="90%" Animation="Animation.Wave"/>
<MudSkeleton Width="75%" Animation="Animation.Wave"/>
<MudSkeleton Width="55%"/>
<MudSkeleton Width="12%"/>
</MudStack>
</MudStack>
}
else
{
switch (this.pandocInstallation)
{
case { CheckWasSuccessful: true, IsAvailable: true }:
<MudStack Row="true" AlignItems="AlignItems.Center">
<MudIcon Style="width: 2.5em; height: 2.5em;" Icon="@Icons.Material.Filled.Check" Color="Color.Success"/>
<MudJustifiedText Typo="Typo.body1">
@T("Pandoc is installed and the version meets the requirements of MindWork AI Studio.")
</MudJustifiedText>
</MudStack>
break;
case { CheckWasSuccessful: true, IsAvailable: false }:
<MudStack Row="true" AlignItems="AlignItems.Center">
<MudIcon Style="width: 3.5em; height: 3.5em;" Icon="@Icons.Material.Filled.Error" Color="Color.Error"/>
<MudJustifiedText Typo="Typo.body1">
@T("Pandoc is installed, but the version is too old and does not meet the requirements of MindWork AI Studio. AI Studio can help you install a newer version.")
</MudJustifiedText>
</MudStack>
break;
case { CheckWasSuccessful: false }:
<MudStack Row="true" AlignItems="AlignItems.Center">
<MudIcon Style="width: 3.5em; height: 3.5em;" Icon="@Icons.Material.Filled.Error" Color="Color.Error"/>
<MudJustifiedText Typo="Typo.body1">
@T("Pandoc doesn't seem to be installed on this system. AI Studio can help you install the correct version.")
</MudJustifiedText>
</MudStack>
break;
}
}
</MudItem>
}
</DialogContent>
<DialogActions>
@if (this.isInstallationInProgress)
{
<MudButton OnClick="@this.Cancel" Variant="Variant.Filled">
@T("Close")
</MudButton>
}
else if (this.ShowInstallationPage)
{
<MudButton OnClick="@this.Cancel" Variant="Variant.Filled">
@T("Close")
</MudButton>
<MudButton Color="Color.Warning" OnClick="@this.RejectLicense" Variant="Variant.Filled" Size="Size.Medium">
@T("Reject the GPL licence")
</MudButton>
}
else
{
<MudButton OnClick="@this.Cancel" Variant="Variant.Filled">
@T("Close")
</MudButton>
@if (this.pandocInstallation != default)
{
switch (this.pandocInstallation)
{
case { CheckWasSuccessful: true, IsAvailable: false }:
case { CheckWasSuccessful: false, IsAvailable: false }:
<MudButton Color="Color.Primary" OnClick="@this.ProceedToInstallation" Variant="Variant.Filled" Size="Size.Medium">
@T("Proceed to the installation")
</MudButton>
break;
case { CheckWasSuccessful: true, IsAvailable: true }:
<MudButton Color="Color.Default" OnClick="@this.ProceedToInstallation" Variant="Variant.Filled" Size="Size.Medium">
@T("Re-install Pandoc")
</MudButton>
break;
}
}
}
</DialogActions>
</MudDialog>
@@ -0,0 +1,167 @@
using System.Reflection;
using AIStudio.Components;
using AIStudio.Tools.Metadata;
using AIStudio.Tools.Services;
using Microsoft.AspNetCore.Components;
using SharedTools;
namespace AIStudio.Dialogs;
public partial class PandocDialog : MSGComponentBase
{
private static readonly Assembly ASSEMBLY = Assembly.GetExecutingAssembly();
private static readonly MetaDataArchitectureAttribute META_DATA_ARCH = ASSEMBLY.GetCustomAttribute<MetaDataArchitectureAttribute>()!;
private static readonly RID CPU_ARCHITECTURE = META_DATA_ARCH.Architecture.ToRID();
[Parameter]
public bool ShowInstallationPage { get; set; }
[Parameter]
public bool ShowInitialResultInSnackbar { get; set; } = true;
[Inject]
private HttpClient HttpClient { get; set; } = null!;
[Inject]
private RustService RustService { get; init; } = null!;
[Inject]
private IDialogService DialogService { get; init; } = null!;
[CascadingParameter]
private IMudDialogInstance MudDialog { get; set; } = null!;
private static readonly ILogger LOG = Program.LOGGER_FACTORY.CreateLogger("PandocDialog");
private static readonly string LICENCE_URI = "https://raw.githubusercontent.com/jgm/pandoc/refs/heads/main/COPYING.md";
private static string LATEST_PANDOC_VERSION = string.Empty;
private PandocInstallation pandocInstallation;
private string? licenseText;
private bool isLoadingLicence;
private bool isInstallationInProgress;
private int selectedInstallerIndex = SelectInstallerIndex();
private int selectedArchiveIndex = SelectArchiveIndex();
private string downloadUrlArchive = string.Empty;
private string downloadUrlInstaller = string.Empty;
#region Overrides of ComponentBase
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
LATEST_PANDOC_VERSION = await Pandoc.FetchLatestVersionAsync();
await this.CheckPandocAvailabilityAsync(this.ShowInitialResultInSnackbar);
}
#endregion
private void Cancel() => this.MudDialog.Cancel();
private async Task CheckPandocAvailabilityAsync(bool useSnackbar)
{
this.pandocInstallation = await Pandoc.CheckAvailabilityAsync(this.RustService, useSnackbar);
await this.InvokeAsync(this.StateHasChanged);
}
private async Task InstallPandocAsync()
{
this.isInstallationInProgress = true;
this.StateHasChanged();
await Pandoc.InstallAsync(this.RustService);
this.isInstallationInProgress = false;
this.MudDialog.Close(DialogResult.Ok(true));
await this.DialogService.ShowAsync<PandocDialog>("Pandoc Installation", DialogOptions.FULLSCREEN);
}
private void ProceedToInstallation() => this.ShowInstallationPage = true;
private async Task RejectLicense()
{
var message = T("Pandoc is open-source and free, but if you reject its license, you can't install it and some MindWork AI Studio features will be limited (like the integration of Office files) or unavailable (like the generation of Office files). You can change your decision anytime. Are you sure you want to reject the license?");
var dialogParameters = new DialogParameters
{
{ "Message", message },
};
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>(T("Reject Pandoc's Licence"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
dialogReference.Close();
else
this.Cancel();
}
private async Task WhenExpandingManualInstallation(bool isExpanded)
{
if(string.IsNullOrWhiteSpace(this.downloadUrlArchive))
this.downloadUrlArchive = await Pandoc.GenerateArchiveUriAsync();
if(string.IsNullOrWhiteSpace(this.downloadUrlInstaller))
this.downloadUrlInstaller = await Pandoc.GenerateInstallerUriAsync();
}
private async Task WhenExpandingLicence(bool isExpanded)
{
if (isExpanded)
{
this.isLoadingLicence = true;
try
{
this.licenseText = await this.LoadLicenseTextAsync();
}
catch (Exception ex)
{
this.licenseText = T("Error loading license text, please consider following the links to read the GPL.");
LOG.LogError("Error loading GPL license text: {ErrorMessage}", ex.Message);
}
finally
{
this.isLoadingLicence = false;
}
}
else
{
this.licenseText = string.Empty;
}
}
private async Task<string> LoadLicenseTextAsync()
{
var response = await this.HttpClient.GetAsync(LICENCE_URI);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
// ReSharper disable RedundantSwitchExpressionArms
private static int SelectInstallerIndex() => CPU_ARCHITECTURE switch
{
RID.OSX_ARM64 => 1,
RID.OSX_X64 => 2,
RID.WIN_ARM64 => 0,
RID.WIN_X64 => 0,
_ => 0,
};
private static int SelectArchiveIndex() => CPU_ARCHITECTURE switch
{
RID.OSX_ARM64 => 1,
RID.OSX_X64 => 1,
RID.WIN_ARM64 => 0,
RID.WIN_X64 => 0,
RID.LINUX_ARM64 => 2,
RID.LINUX_X64 => 2,
_ => 0,
};
// ReSharper restore RedundantSwitchExpressionArms
}
@@ -133,6 +133,7 @@ public partial class ProviderDialog : MSGComponentBase, ISecretId
_ => this.DataModel
},
IsSelfHosted = this.DataLLMProvider is LLMProviders.SELF_HOSTED,
IsEnterpriseConfiguration = false,
Hostname = cleanedHostname.EndsWith('/') ? cleanedHostname[..^1] : cleanedHostname,
Host = this.DataHost,
HFInferenceProvider = this.HFInferenceProviderId,
@@ -90,7 +90,8 @@ public partial class MainLayout : LayoutComponentBase, IMessageBusReceiver, ILan
this.MessageBus.ApplyFilters(this, [],
[
Event.UPDATE_AVAILABLE, Event.CONFIGURATION_CHANGED, Event.COLOR_THEME_CHANGED, Event.SHOW_ERROR,
Event.STARTUP_PLUGIN_SYSTEM, Event.PLUGINS_RELOADED
Event.SHOW_ERROR, Event.SHOW_WARNING, Event.SHOW_SUCCESS, Event.STARTUP_PLUGIN_SYSTEM,
Event.PLUGINS_RELOADED
]);
// Set the snackbar for the update service:
@@ -176,34 +177,42 @@ public partial class MainLayout : LayoutComponentBase, IMessageBusReceiver, ILan
this.StateHasChanged();
break;
case Event.SHOW_SUCCESS:
if (data is DataSuccessMessage success)
success.Show(this.Snackbar);
break;
case Event.SHOW_ERROR:
if (data is Error error)
if (data is DataErrorMessage error)
error.Show(this.Snackbar);
break;
case Event.STARTUP_PLUGIN_SYSTEM:
if(PreviewFeatures.PRE_PLUGINS_2025.IsEnabled(this.SettingsManager))
{
_ = Task.Run(async () =>
{
// Set up the plugin system:
if (PluginFactory.Setup())
{
// Ensure that all internal plugins are present:
await PluginFactory.EnsureInternalPlugins();
// Load (but not start) all plugins, without waiting for them:
var pluginLoadingTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await PluginFactory.LoadAll(pluginLoadingTimeout.Token);
// Set up hot reloading for plugins:
PluginFactory.SetUpHotReloading();
}
});
}
case Event.SHOW_WARNING:
if (data is DataWarningMessage warning)
warning.Show(this.Snackbar);
break;
case Event.STARTUP_PLUGIN_SYSTEM:
_ = Task.Run(async () =>
{
// Set up the plugin system:
if (PluginFactory.Setup())
{
// Ensure that all internal plugins are present:
await PluginFactory.EnsureInternalPlugins();
// Load (but not start) all plugins, without waiting for them:
var pluginLoadingTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await PluginFactory.LoadAll(pluginLoadingTimeout.Token);
// Set up hot reloading for plugins:
PluginFactory.SetUpHotReloading();
}
});
break;
case Event.PLUGINS_RELOADED:
this.Lang = await this.SettingsManager.GetActiveLanguagePlugin();
@@ -233,9 +242,7 @@ public partial class MainLayout : LayoutComponentBase, IMessageBusReceiver, ILan
if (PreviewFeatures.PRE_WRITER_MODE_2024.IsEnabled(this.SettingsManager))
yield return new(T("Writer"), Icons.Material.Filled.Create, palette.DarkLighten, palette.GrayLight, Routes.WRITER, false);
if (PreviewFeatures.PRE_PLUGINS_2025.IsEnabled(this.SettingsManager))
yield return new(T("Plugins"), Icons.Material.TwoTone.Extension, palette.DarkLighten, palette.GrayLight, Routes.PLUGINS, false);
yield return new(T("Plugins"), Icons.Material.TwoTone.Extension, palette.DarkLighten, palette.GrayLight, Routes.PLUGINS, false);
yield return new(T("Supporters"), Icons.Material.Filled.Favorite, palette.Error.Value, "#801a00", Routes.SUPPORTERS, false);
yield return new(T("About"), Icons.Material.Filled.Info, palette.DarkLighten, palette.GrayLight, Routes.ABOUT, false);
yield return new(T("Settings"), Icons.Material.Filled.Settings, palette.DarkLighten, palette.GrayLight, Routes.SETTINGS, false);
+12 -4
View File
@@ -19,13 +19,20 @@
<MudListItem T="string" Icon="@Icons.Material.Outlined.Memory" Text="@VersionDotnetRuntime"/>
<MudListItem T="string" Icon="@Icons.Material.Outlined.Build" Text="@VersionRust"/>
<MudListItem T="string" Icon="@Icons.Material.Outlined.DocumentScanner" Text="@VersionPdfium"/>
<MudListItem T="string" Icon="@Icons.Material.Outlined.Article" Text="@this.versionPandoc"/>
<MudListItem T="string" Icon="@Icons.Material.Outlined.Widgets" Text="@MudBlazorVersion"/>
<MudListItem T="string" Icon="@Icons.Material.Outlined.Memory" Text="@TauriVersion"/>
<MudListItem T="string" Icon="@Icons.Material.Outlined.Translate" Text="@this.OSLanguage"/>
<MudListItem T="string" Icon="@Icons.Material.Outlined.Business" Text="@this.GetEnterpriseEnvironment()"/>
</MudList>
<MudButton Variant="Variant.Filled" Color="Color.Info" StartIcon="@Icons.Material.Filled.Update" OnClick="() => this.CheckForUpdate()">
@T("Check for updates")
</MudButton>
<MudStack Row="true">
<MudButton Variant="Variant.Filled" Color="Color.Info" StartIcon="@Icons.Material.Filled.Update" OnClick="() => this.CheckForUpdate()">
@T("Check for updates")
</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Default" StartIcon="@Icons.Material.Filled.Download" OnClick="async () => await this.ShowPandocDialog()">
@this.PandocButtonText
</MudButton>
</MudStack>
</ExpansionPanel>
<ExpansionPanel HeaderIcon="@Icons.Custom.Brands.GitHub" HeaderText="@T("Community & Code")">
@@ -100,7 +107,7 @@
<ThirdPartyComponent Name="Tauri" Developer="Daniel Thompson-Yvetot, Lucas Nogueira, Tensor, Boscop, Serge Zaitsev, George Burton & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/tauri-apps/tauri/blob/dev/LICENSE_MIT" RepositoryUrl="https://github.com/tauri-apps/tauri" UseCase="@T("Tauri is used to host the Blazor user interface. It is a great project that allows the creation of desktop applications using web technologies. I love Tauri!")"/>
<ThirdPartyComponent Name="Rocket" Developer="Sergio Benitez & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/rwf2/Rocket/blob/master/LICENSE-MIT" RepositoryUrl="https://github.com/rwf2/Rocket" UseCase="@T("We use Rocket to implement the runtime API. This is necessary because the runtime must be able to communicate with the user interface (IPC). Rocket is a great framework for implementing web APIs in Rust.")"/>
<ThirdPartyComponent Name="serde" Developer="Erick Tryzelaar, David Tolnay & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/serde-rs/serde/blob/master/LICENSE-MIT" RepositoryUrl="https://github.com/serde-rs/serde" UseCase="@T("Now we have multiple systems, some developed in .NET and others in Rust. The data format JSON is responsible for translating data between both worlds (called data serialization and deserialization). Serde takes on this task in the Rust world. The counterpart in the .NET world is an integral part of .NET and is located in System.Text.Json.")"/>
<ThirdPartyComponent Name="keyring" Developer="Walther Chen, Daniel Brotsky & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/hwchen/keyring-rs/blob/master/LICENSE-MIT" RepositoryUrl="https://github.com/hwchen/keyring-rs" UseCase="@T("In order to use any LLM, each user must store their so-called token for each LLM provider. This token must be kept secure, similar to a password. The safest way to do this is offered by operating systems like macOS, Windows, and Linux: They have mechanisms to store such data, if available, on special security hardware. Since this is currently not possible in .NET, we use this Rust library.")"/>
<ThirdPartyComponent Name="keyring" Developer="Walther Chen, Daniel Brotsky & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/hwchen/keyring-rs/blob/master/LICENSE-MIT" RepositoryUrl="https://github.com/hwchen/keyring-rs" UseCase="@T("In order to use any LLM, each user must store their so-called API key for each LLM provider. This key must be kept secure, similar to a password. The safest way to do this is offered by operating systems like macOS, Windows, and Linux: They have mechanisms to store such data, if available, on special security hardware. Since this is currently not possible in .NET, we use this Rust library.")"/>
<ThirdPartyComponent Name="arboard" Developer="Artur Kovacs, Avi Weinstock, 1Password & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/1Password/arboard/blob/master/LICENSE-MIT.txt" RepositoryUrl="https://github.com/1Password/arboard" UseCase="@T("To be able to use the responses of the LLM in other apps, we often use the clipboard of the respective operating system. Unfortunately, in .NET there is no solution that works with all operating systems. Therefore, I have opted for this library in Rust. This way, data transfer to other apps works on every system.")"/>
<ThirdPartyComponent Name="tokio" Developer="Alex Crichton, Carl Lerche, Alice Ryhl, Taiki Endo, Ivan Petkov, Eliza Weisman, Lucio Franco & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/tokio-rs/tokio/blob/master/LICENSE" RepositoryUrl="https://github.com/tokio-rs/tokio" UseCase="@T("Code in the Rust language can be specified as synchronous or asynchronous. Unlike .NET and the C# language, Rust cannot execute asynchronous code by itself. Rust requires support in the form of an executor for this. Tokio is one such executor.")"/>
<ThirdPartyComponent Name="futures" Developer="Alex Crichton, Taiki Endo, Taylor Cramer, Nemo157, Josef Brandl, Aaron Turon & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/rust-lang/futures-rs/blob/master/LICENSE-MIT" RepositoryUrl="https://github.com/rust-lang/futures-rs" UseCase="@T("This is a library providing the foundations for asynchronous programming in Rust. It includes key trait definitions like Stream, as well as utilities like join!, select!, and various futures combinator methods which enable expressive asynchronous control flow.")"/>
@@ -110,6 +117,7 @@
<ThirdPartyComponent Name="base64" Developer="Marshall Pierce, Alice Maz & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/marshallpierce/rust-base64/blob/master/LICENSE-MIT" RepositoryUrl="https://github.com/marshallpierce/rust-base64" UseCase="@T("For some data transfers, we need to encode the data in base64. This Rust library is great for this purpose.")"/>
<ThirdPartyComponent Name="Rust Crypto" Developer="Artyom Pavlov, Tony Arcieri, Brian Warner, Arthur Gautier, Vlad Filippov, Friedel Ziegelmayer, Nicolas Stalder & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/RustCrypto/traits/blob/master/cipher/LICENSE-MIT" RepositoryUrl="https://github.com/RustCrypto" UseCase="@T("When transferring sensitive data between Rust runtime and .NET app, we encrypt the data. We use some libraries from the Rust Crypto project for this purpose: cipher, aes, cbc, pbkdf2, hmac, and sha2. We are thankful for the great work of the Rust Crypto project.")"/>
<ThirdPartyComponent Name="rcgen" Developer="RustTLS developers, est31 & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/rustls/rcgen/blob/main/LICENSE" RepositoryUrl="https://github.com/rustls/rcgen" UseCase="@T("For the secure communication between the user interface and the runtime, we need to create certificates. This Rust library is great for this purpose.")"/>
<ThirdPartyComponent Name="windows-registry" Developer="Microsoft, Kenny Kerr, Ryan Levick, Rafael Rivera, sivadeilra, Marijn Suijten & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/microsoft/windows-rs/blob/master/license-mit" RepositoryUrl="https://github.com/microsoft/windows-rs" UseCase="@T("This library is used to access the Windows registry. We use this for Windows enterprise environments to read the desired configuration.")"/>
<ThirdPartyComponent Name="file-format" Developer="Mickaël Malécot & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/mmalecot/file-format/blob/main/LICENSE-MIT" RepositoryUrl="https://github.com/mmalecot/file-format" UseCase="@T("This library is used to determine the file type of a file. This is necessary, e.g., when we want to stream a file.")"/>
<ThirdPartyComponent Name="calamine" Developer="Johann Tuffe, Joel Natividad, Eric Jolibois, Dmitriy & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/tafia/calamine/blob/master/LICENSE-MIT.md" RepositoryUrl="https://github.com/tafia/calamine" UseCase="@T("This library is used to read Excel and OpenDocument spreadsheet files. This is necessary, e.g., for using spreadsheets as a data source for a chat.")"/>
<ThirdPartyComponent Name="PDFium" Developer="Lei Zhang, Tom Sepez, Dan Sinclair, and Foxit, Google, Chromium, Collabora, Ada, DocsCorp, Dropbox, Microsoft, and PSPDFKit Teams & Open Source Community" LicenseName="Apache-2.0" LicenseUrl="https://pdfium.googlesource.com/pdfium/+/refs/heads/main/LICENSE" RepositoryUrl="https://pdfium.googlesource.com/pdfium" UseCase="@T("This library is used to read PDF files. This is necessary, e.g., for using PDFs as a data source for a chat.")"/>
@@ -1,7 +1,9 @@
using System.Reflection;
using AIStudio.Components;
using AIStudio.Dialogs;
using AIStudio.Tools.Metadata;
using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Rust;
using AIStudio.Tools.Services;
@@ -9,6 +11,8 @@ using Microsoft.AspNetCore.Components;
using SharedTools;
using DialogOptions = AIStudio.Dialogs.DialogOptions;
namespace AIStudio.Pages;
public partial class About : MSGComponentBase
@@ -16,6 +20,9 @@ public partial class About : MSGComponentBase
[Inject]
private RustService RustService { get; init; } = null!;
[Inject]
private IDialogService DialogService { get; init; } = null!;
[Inject]
private ISnackbar Snackbar { get; init; } = null!;
@@ -23,6 +30,8 @@ public partial class About : MSGComponentBase
private static readonly MetaDataAttribute META_DATA = ASSEMBLY.GetCustomAttribute<MetaDataAttribute>()!;
private static readonly MetaDataArchitectureAttribute META_DATA_ARCH = ASSEMBLY.GetCustomAttribute<MetaDataArchitectureAttribute>()!;
private static readonly MetaDataLibrariesAttribute META_DATA_LIBRARIES = ASSEMBLY.GetCustomAttribute<MetaDataLibrariesAttribute>()!;
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(About).Namespace, nameof(About));
private string osLanguage = string.Empty;
@@ -43,6 +52,9 @@ public partial class About : MSGComponentBase
private string BuildTime => $"{T("Build time")}: {META_DATA.BuildTime}";
private string VersionPdfium => $"{T("Used PDFium version")}: v{META_DATA_LIBRARIES.PdfiumVersion}";
private string versionPandoc = TB("Determine Pandoc version, please wait...");
private PandocInstallation pandocInstallation;
private GetLogPathsResponse logPaths;
@@ -52,11 +64,80 @@ public partial class About : MSGComponentBase
{
this.osLanguage = await this.RustService.ReadUserLanguage();
this.logPaths = await this.RustService.GetLogPaths();
await base.OnInitializedAsync();
await this.DeterminePandocVersion();
}
#endregion
private async Task DeterminePandocVersion()
{
this.pandocInstallation = await Pandoc.CheckAvailabilityAsync(this.RustService, false);
var pandocInstallationType = this.pandocInstallation.IsLocalInstallation
? T("installed by AI Studio")
: T("installation provided by the system");
switch (this.pandocInstallation)
{
case { CheckWasSuccessful: true, IsAvailable: true }:
this.versionPandoc = $"{this.T("Installed Pandoc version")}: v{this.pandocInstallation.Version} ({pandocInstallationType}) - {T("OK")}";
break;
case { CheckWasSuccessful: true, IsAvailable: false }:
this.versionPandoc = $"{this.T("Installed Pandoc version")}: v{this.pandocInstallation.Version} ({pandocInstallationType}) - {T("this version does not met the requirements")}";
break;
default:
this.versionPandoc = TB("Installed Pandoc version: Pandoc is not installed or not available.");
break;
}
await this.InvokeAsync(this.StateHasChanged);
}
private string PandocButtonText
{
get
{
return this.pandocInstallation switch
{
{ IsAvailable: true, CheckWasSuccessful: true } => this.T("Check Pandoc Installation"),
{ IsAvailable: false, CheckWasSuccessful: true } => this.T("Update Pandoc"),
_ => this.T("Install Pandoc")
};
}
}
private async Task ShowPandocDialog()
{
var dialogReference = await this.DialogService.ShowAsync<PandocDialog>(T("Pandoc Installation"), DialogOptions.FULLSCREEN);
await dialogReference.Result;
await this.DeterminePandocVersion();
}
private string GetEnterpriseEnvironment()
{
var configPlug = PluginFactory.AvailablePlugins.FirstOrDefault(x => x.Type is PluginType.CONFIGURATION);
var currentEnvironment = EnterpriseEnvironmentService.CURRENT_ENVIRONMENT;
switch (currentEnvironment)
{
case { IsActive: false } when configPlug is null:
return T("AI Studio runs without an enterprise configuration.");
case { IsActive: false }:
return string.Format(T("AI Studio runs with an enterprise configuration using the configuration plugin '{0}', without central configuration management."), configPlug.Id);
case { IsActive: true } when configPlug is null:
return string.Format(T("AI Studio runs with an enterprise configuration id '{0}' and configuration server URL '{1}'. The configuration plugin is not yet available."), currentEnvironment.ConfigurationId, currentEnvironment.ConfigurationServerUrl);
case { IsActive: true }:
return string.Format(T("AI Studio runs with an enterprise configuration id '{0}' and configuration server URL '{1}'. The configuration plugin is active."), currentEnvironment.ConfigurationId, currentEnvironment.ConfigurationServerUrl);
}
}
private async Task CopyStartupLogPath()
{
await this.RustService.CopyText2Clipboard(this.Snackbar, this.logPaths.LogStartupPath);
@@ -51,15 +51,12 @@
}
</MudStack>
@if (PreviewFeatures.PRE_PLUGINS_2025.IsEnabled(this.SettingsManager))
{
<MudText Typo="Typo.h4" Class="mb-2 mr-3 mt-6">
@T("AI Studio Development")
</MudText>
<MudStack Row="@true" Wrap="@Wrap.Wrap" Class="mb-3">
<AssistantBlock TSettings="SettingsDialogI18N" Name="@T("Localization")" Description="@T("Translate AI Studio text content into other languages")" Icon="@Icons.Material.Filled.Translate" Link="@Routes.ASSISTANT_AI_STUDIO_I18N"/>
</MudStack>
}
<MudText Typo="Typo.h4" Class="mb-2 mr-3 mt-6">
@T("AI Studio Development")
</MudText>
<MudStack Row="@true" Wrap="@Wrap.Wrap" Class="mb-3">
<AssistantBlock TSettings="SettingsDialogI18N" Name="@T("Localization")" Description="@T("Translate AI Studio text content into other languages")" Icon="@Icons.Material.Filled.Translate" Link="@Routes.ASSISTANT_AI_STUDIO_I18N"/>
</MudStack>
</InnerScrolling>
</div>
+1 -2
View File
@@ -6,7 +6,6 @@
<MudText Typo="Typo.h3" Class="mb-2">
@T("Plugins")
</MudText>
<PreviewExperimental ApplyInnerScrollingFix="true"/>
<InnerScrolling>
@@ -64,7 +63,7 @@
</MudStack>
</MudTd>
<MudTd>
@if (!context.IsInternal)
@if (context is { IsInternal: false, Type: not PluginType.CONFIGURATION })
{
var isEnabled = this.SettingsManager.IsPluginEnabled(context);
<MudTooltip Text="@(isEnabled ? T("Disable plugin") : T("Enable plugin"))">
@@ -0,0 +1 @@
SVG = [[<svg enable-background="new 0 0 24 24" height="24px" viewBox="0 0 24 24" width="24px" fill="#1f1f1f"><g><path d="M0,0h24v24H0V0z" fill="none"/><path d="M19.14,12.94c0.04-0.3,0.06-0.61,0.06-0.94c0-0.32-0.02-0.64-0.07-0.94l2.03-1.58c0.18-0.14,0.23-0.41,0.12-0.61 l-1.92-3.32c-0.12-0.22-0.37-0.29-0.59-0.22l-2.39,0.96c-0.5-0.38-1.03-0.7-1.62-0.94L14.4,2.81c-0.04-0.24-0.24-0.41-0.48-0.41 h-3.84c-0.24,0-0.43,0.17-0.47,0.41L9.25,5.35C8.66,5.59,8.12,5.92,7.63,6.29L5.24,5.33c-0.22-0.08-0.47,0-0.59,0.22L2.74,8.87 C2.62,9.08,2.66,9.34,2.86,9.48l2.03,1.58C4.84,11.36,4.8,11.69,4.8,12s0.02,0.64,0.07,0.94l-2.03,1.58 c-0.18,0.14-0.23,0.41-0.12,0.61l1.92,3.32c0.12,0.22,0.37,0.29,0.59,0.22l2.39-0.96c0.5,0.38,1.03,0.7,1.62,0.94l0.36,2.54 c0.05,0.24,0.24,0.41,0.48,0.41h3.84c0.24,0,0.44-0.17,0.47-0.41l0.36-2.54c0.59-0.24,1.13-0.56,1.62-0.94l2.39,0.96 c0.22,0.08,0.47,0,0.59-0.22l1.92-3.32c0.12-0.22,0.07-0.47-0.12-0.61L19.14,12.94z M12,15.6c-1.98,0-3.6-1.62-3.6-3.6 s1.62-3.6,3.6-3.6s3.6,1.62,3.6,3.6S13.98,15.6,12,15.6z"/></g></svg>]]
@@ -0,0 +1,67 @@
require("icon")
-- ------
-- This is an example of a configuration plugin. Please replace
-- the placeholders and assign a valid ID.
-- ------
-- The ID for this plugin:
ID = "00000000-0000-0000-0000-000000000000"
-- The icon for the plugin:
ICON_SVG = SVG
-- The name of the plugin:
NAME = "<Company Name> - Configuration for <Department Name>"
-- The description of the plugin:
DESCRIPTION = "This is a pre-defined configuration of <Company Name>"
-- The version of the plugin:
VERSION = "1.0.0"
-- The type of the plugin:
TYPE = "CONFIGURATION"
-- The authors of the plugin:
AUTHORS = {"<Company Name>"}
-- The support contact for the plugin:
SUPPORT_CONTACT = "<IT Department of Company Name>"
-- The source URL for the plugin:
SOURCE_URL = "<Any internal Git repository>"
-- The categories for the plugin:
CATEGORIES = { "CORE" }
-- The target groups for the plugin:
TARGET_GROUPS = { "EVERYONE" }
-- The flag for whether the plugin is maintained:
IS_MAINTAINED = true
-- When the plugin is deprecated, this message will be shown to users:
DEPRECATION_MESSAGE = ""
CONFIG = {}
CONFIG["LLM_PROVIDERS"] = {}
-- An example of a configuration for a self-hosted ollama server:
CONFIG["LLM_PROVIDERS"][#CONFIG["LLM_PROVIDERS"]+1] = {
["Id"] = "00000000-0000-0000-0000-000000000000",
["InstanceName"] = "<user-friendly name for the combination of server and model>",
["UsedLLMProvider"] = "SELF_HOSTED",
["Host"] = "OLLAMA",
["Hostname"] = "<https address of the ollama server>",
["Model"] = {
["Id"] = "<the ollama model ID>",
["DisplayName"] = "<user-friendly name of the model>",
}
}
CONFIG["SETTINGS"] = {}
-- Configure the update behavior:
-- Allowed values are: NO_CHECK, ONCE_STARTUP, HOURLY, DAILY, WEEKLY
-- CONFIG["SETTINGS"]["DataApp.UpdateBehavior"] = "NO_CHECK"
+2
View File
@@ -126,12 +126,14 @@ internal sealed class Program
builder.Services.AddSingleton<SettingsManager>();
builder.Services.AddSingleton<ThreadSafeRandom>();
builder.Services.AddSingleton<DataSourceService>();
builder.Services.AddSingleton<SettingsLocker>();
builder.Services.AddTransient<HTMLParser>();
builder.Services.AddTransient<AgentDataSourceSelection>();
builder.Services.AddTransient<AgentRetrievalContextValidation>();
builder.Services.AddTransient<AgentTextContentCleaner>();
builder.Services.AddHostedService<UpdateService>();
builder.Services.AddHostedService<TemporaryChatService>();
builder.Services.AddHostedService<EnterpriseEnvironmentService>();
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents()
.AddHubOptions(options =>
@@ -53,6 +53,9 @@ public readonly record struct DataSourceERI_V1 : IERIDataSource
/// <inheritdoc />
public string SelectedRetrievalId { get; init; } = string.Empty;
/// <inheritdoc />
public ushort MaxMatches { get; init; } = 10;
/// <inheritdoc />
public async Task<IReadOnlyList<IRetrievalContext>> RetrieveDataAsync(IContent lastPrompt, ChatThread thread, CancellationToken token = default)
@@ -76,7 +79,7 @@ public readonly record struct DataSourceERI_V1 : IERIDataSource
},
Thread = await thread.ToERIChatThread(token),
MaxMatches = 10,
MaxMatches = this.MaxMatches,
RetrievalProcessId = string.IsNullOrWhiteSpace(this.SelectedRetrievalId) ? null : this.SelectedRetrievalId,
Parameters = null, // The ERI server selects useful default parameters
};
@@ -30,6 +30,9 @@ public readonly record struct DataSourceLocalDirectory : IInternalDataSource
/// <inheritdoc />
public DataSourceSecurity SecurityPolicy { get; init; } = DataSourceSecurity.NOT_SPECIFIED;
/// <inheritdoc />
public ushort MaxMatches { get; init; } = 10;
/// <inheritdoc />
public Task<IReadOnlyList<IRetrievalContext>> RetrieveDataAsync(IContent lastPrompt, ChatThread thread, CancellationToken token = default)
{
@@ -30,6 +30,9 @@ public readonly record struct DataSourceLocalFile : IInternalDataSource
/// <inheritdoc />
public DataSourceSecurity SecurityPolicy { get; init; } = DataSourceSecurity.NOT_SPECIFIED;
/// <inheritdoc />
public ushort MaxMatches { get; init; } = 10;
/// <inheritdoc />
public Task<IReadOnlyList<IRetrievalContext>> RetrieveDataAsync(IContent lastPrompt, ChatThread thread, CancellationToken token = default)
{
@@ -29,6 +29,8 @@ public static class PreviewFeaturesExtensions
public static bool IsReleased(this PreviewFeatures feature) => feature switch
{
PreviewFeatures.PRE_READ_PDF_2025 => true,
PreviewFeatures.PRE_PLUGINS_2025 => true,
_ => false
};
@@ -19,14 +19,12 @@ public static class PreviewVisibilityExtensions
if (visibility >= PreviewVisibility.PROTOTYPE)
{
features.Add(PreviewFeatures.PRE_READ_PDF_2025);
features.Add(PreviewFeatures.PRE_RAG_2024);
}
if (visibility >= PreviewVisibility.EXPERIMENTAL)
{
features.Add(PreviewFeatures.PRE_WRITER_MODE_2024);
features.Add(PreviewFeatures.PRE_PLUGINS_2025);
}
return features;
@@ -40,6 +40,11 @@ public interface IDataSource
/// </summary>
public DataSourceSecurity SecurityPolicy { get; init; }
/// <summary>
/// The maximum number of matches to return when retrieving data from the ERI server.
/// </summary>
public ushort MaxMatches { get; init; }
/// <summary>
/// Perform the data retrieval process.
/// </summary>
@@ -23,6 +23,8 @@ public readonly record struct Provider(
LLMProviders UsedLLMProvider,
Model Model,
bool IsSelfHosted = false,
bool IsEnterpriseConfiguration = false,
Guid EnterpriseConfigurationPluginId = default,
string Hostname = "http://localhost:1234",
Host Host = Host.NONE,
HFInferenceProvider HFInferenceProvider = HFInferenceProvider.NONE) : ISecretId
@@ -0,0 +1,78 @@
using System.Linq.Expressions;
namespace AIStudio.Settings;
public sealed class SettingsLocker
{
private static readonly ILogger<SettingsLocker> LOGGER = Program.LOGGER_FACTORY.CreateLogger<SettingsLocker>();
private readonly Dictionary<string, Dictionary<string, Guid>> lockedProperties = new();
public void Register<T>(Expression<Func<T, object>> propertyExpression, Guid configurationPluginId)
{
var memberExpression = GetMemberExpression(propertyExpression);
var className = typeof(T).Name;
var propertyName = memberExpression.Member.Name;
if (!this.lockedProperties.ContainsKey(className))
this.lockedProperties[className] = [];
this.lockedProperties[className].TryAdd(propertyName, configurationPluginId);
}
public void Remove<T>(Expression<Func<T, object>> propertyExpression)
{
var memberExpression = GetMemberExpression(propertyExpression);
var className = typeof(T).Name;
var propertyName = memberExpression.Member.Name;
if (this.lockedProperties.TryGetValue(className, out var props))
{
if (props.Remove(propertyName))
{
// If the property was removed, check if the class has no more locked properties:
if (props.Count == 0)
this.lockedProperties.Remove(className);
}
}
}
public Guid GetConfigurationPluginId<T>(Expression<Func<T, object>> propertyExpression)
{
var memberExpression = GetMemberExpression(propertyExpression);
var className = typeof(T).Name;
var propertyName = memberExpression.Member.Name;
if (this.lockedProperties.TryGetValue(className, out var props) && props.TryGetValue(propertyName, out var configurationPluginId))
return configurationPluginId;
// No configuration plugin ID found for this property:
return Guid.Empty;
}
public bool IsLocked<T>(Expression<Func<T, object>> propertyExpression)
{
var memberExpression = GetMemberExpression(propertyExpression);
var className = typeof(T).Name;
var propertyName = memberExpression.Member.Name;
return this.lockedProperties.TryGetValue(className, out var props) && props.ContainsKey(propertyName);
}
private static MemberExpression GetMemberExpression<T>(Expression<Func<T, object>> expression)
{
switch (expression.Body)
{
// Case for value types, which are wrapped in UnaryExpression:
case UnaryExpression { NodeType: ExpressionType.Convert } unaryExpression:
return (MemberExpression)unaryExpression.Operand;
// Case for reference types, which are directly MemberExpressions:
case MemberExpression memberExpression:
return memberExpression;
default:
LOGGER.LogError($"Expression '{expression}' is not a valid property expression.");
throw new ArgumentException($"Expression '{expression}' is not a valid property expression.", nameof(expression));
}
}
}
@@ -159,7 +159,7 @@ public sealed class SettingsManager
/// </summary>
/// <param name="plugin">The plugin to check.</param>
/// <returns>True, when the plugin is enabled, false otherwise.</returns>
public bool IsPluginEnabled(IPluginMetadata plugin) => this.ConfigurationData.EnabledPlugins.Contains(plugin.Id);
public bool IsPluginEnabled(IPluginMetadata plugin) => plugin.Type is PluginType.CONFIGURATION || this.ConfigurationData.EnabledPlugins.Contains(plugin.Id);
/// <summary>
/// Returns the active language plugin.
@@ -1,6 +1,6 @@
namespace AIStudio.Tools;
public readonly record struct Error(string Icon, string Message)
public readonly record struct DataErrorMessage(string Icon, string Message)
{
public void Show(ISnackbar snackbar)
{
@@ -0,0 +1,16 @@
namespace AIStudio.Tools;
public readonly record struct DataSuccessMessage(string Icon, string Message)
{
public void Show(ISnackbar snackbar)
{
var icon = this.Icon;
snackbar.Add(this.Message, Severity.Success, config =>
{
config.Icon = icon;
config.IconSize = Size.Large;
config.HideTransitionDuration = 600;
config.VisibleStateDuration = 10_000;
});
}
}
@@ -0,0 +1,16 @@
namespace AIStudio.Tools;
public readonly record struct DataWarningMessage(string Icon, string Message)
{
public void Show(ISnackbar snackbar)
{
var icon = this.Icon;
snackbar.Add(this.Message, Severity.Warning, config =>
{
config.Icon = icon;
config.IconSize = Size.Large;
config.HideTransitionDuration = 600;
config.VisibleStateDuration = 12_000;
});
}
}
@@ -0,0 +1,6 @@
namespace AIStudio.Tools;
public readonly record struct EnterpriseEnvironment(string ConfigurationServerUrl, Guid ConfigurationId)
{
public bool IsActive => !string.IsNullOrEmpty(this.ConfigurationServerUrl) && this.ConfigurationId != Guid.Empty;
}
+2
View File
@@ -11,6 +11,8 @@ public enum Event
STARTUP_PLUGIN_SYSTEM,
PLUGINS_RELOADED,
SHOW_ERROR,
SHOW_WARNING,
SHOW_SUCCESS,
// Update events:
USER_SEARCH_FOR_UPDATE,
+5 -1
View File
@@ -72,7 +72,11 @@ public sealed class MessageBus
}
}
public Task SendError(Error error) => this.SendMessage(null, Event.SHOW_ERROR, error);
public Task SendError(DataErrorMessage dataErrorMessage) => this.SendMessage(null, Event.SHOW_ERROR, dataErrorMessage);
public Task SendWarning(DataWarningMessage dataWarningMessage) => this.SendMessage(null, Event.SHOW_WARNING, dataWarningMessage);
public Task SendSuccess(DataSuccessMessage dataSuccessMessage) => this.SendMessage(null, Event.SHOW_SUCCESS, dataSuccessMessage);
public void DeferMessage<T>(ComponentBase? sendingComponent, Event triggeredEvent, T? data = default)
{
+297
View File
@@ -0,0 +1,297 @@
using System.Diagnostics;
using System.Formats.Tar;
using System.IO.Compression;
using System.Reflection;
using System.Text.RegularExpressions;
using AIStudio.Tools.Metadata;
using AIStudio.Tools.Services;
using SharedTools;
namespace AIStudio.Tools;
public static partial class Pandoc
{
private static string TB(string fallbackEN) => PluginSystem.I18N.I.T(fallbackEN, typeof(Pandoc).Namespace, nameof(Pandoc));
private static readonly Assembly ASSEMBLY = Assembly.GetExecutingAssembly();
private static readonly MetaDataArchitectureAttribute META_DATA_ARCH = ASSEMBLY.GetCustomAttribute<MetaDataArchitectureAttribute>()!;
private static readonly RID CPU_ARCHITECTURE = META_DATA_ARCH.Architecture.ToRID();
private const string DOWNLOAD_URL = "https://github.com/jgm/pandoc/releases/download";
private const string LATEST_URL = "https://github.com/jgm/pandoc/releases/latest";
private static readonly ILogger LOG = Program.LOGGER_FACTORY.CreateLogger("Pandoc");
private static readonly Version MINIMUM_REQUIRED_VERSION = new (3, 7, 0, 2);
private static readonly Version FALLBACK_VERSION = new (3, 7, 0, 2);
/// <summary>
/// Prepares a Pandoc process by using the Pandoc process builder.
/// </summary>
/// <returns>The Pandoc process builder with default settings.</returns>
public static PandocProcessBuilder PreparePandocProcess() => PandocProcessBuilder.Create();
/// <summary>
/// Checks if pandoc is available on the system and can be started as a process or is present in AI Studio's data dir.
/// </summary>
/// <param name="rustService">Global rust service to access file system and data dir.</param>
/// <param name="showMessages">Controls if snackbars are shown to the user.</param>
/// <returns>True, if pandoc is available and the minimum required version is met, else false.</returns>
public static async Task<PandocInstallation> CheckAvailabilityAsync(RustService rustService, bool showMessages = true)
{
try
{
var preparedProcess = await PreparePandocProcess().AddArgument("--version").BuildAsync(rustService);
using var process = Process.Start(preparedProcess.StartInfo);
if (process == null)
{
if (showMessages)
await MessageBus.INSTANCE.SendError(new (Icons.Material.Filled.Help, TB("Was not able to check the Pandoc installation.")));
LOG.LogInformation("The Pandoc process was not started, it was null");
return new(false, TB("Was not able to check the Pandoc installation."), false, string.Empty, preparedProcess.IsLocal);
}
var output = await process.StandardOutput.ReadToEndAsync();
await process.WaitForExitAsync();
if (process.ExitCode != 0)
{
if (showMessages)
await MessageBus.INSTANCE.SendError(new (Icons.Material.Filled.Error, TB("Pandoc is not available on the system or the process had issues.")));
LOG.LogError("The Pandoc process was exited with code {ProcessExitCode}", process.ExitCode);
return new(false, TB("Pandoc is not available on the system or the process had issues."), false, string.Empty, preparedProcess.IsLocal);
}
var versionMatch = PandocCmdRegex().Match(output);
if (!versionMatch.Success)
{
if (showMessages)
await MessageBus.INSTANCE.SendError(new (Icons.Material.Filled.Terminal, TB("Was not able to validate the Pandoc installation.")));
LOG.LogError("Pandoc --version returned an invalid format: {Output}", output);
return new(false, TB("Was not able to validate the Pandoc installation."), false, string.Empty, preparedProcess.IsLocal);
}
var versions = versionMatch.Groups[1].Value;
var installedVersion = Version.Parse(versions);
var installedVersionString = installedVersion.ToString();
if (installedVersion >= MINIMUM_REQUIRED_VERSION)
{
if (showMessages)
await MessageBus.INSTANCE.SendSuccess(new(Icons.Material.Filled.CheckCircle, string.Format(TB("Pandoc v{0} is installed."), installedVersionString)));
LOG.LogInformation("Pandoc v{0} is installed and matches the required version (v{1})", installedVersionString, MINIMUM_REQUIRED_VERSION.ToString());
return new(true, string.Empty, true, installedVersionString, preparedProcess.IsLocal);
}
if (showMessages)
await MessageBus.INSTANCE.SendError(new (Icons.Material.Filled.Build, string.Format(TB("Pandoc v{0} is installed, but it doesn't match the required version (v{1})."), installedVersionString, MINIMUM_REQUIRED_VERSION.ToString())));
LOG.LogWarning("Pandoc v{0} is installed, but it does not match the required version (v{1})", installedVersionString, MINIMUM_REQUIRED_VERSION.ToString());
return new(true, string.Format(TB("Pandoc v{0} is installed, but it does not match the required version (v{1})."), installedVersionString, MINIMUM_REQUIRED_VERSION.ToString()), false, installedVersionString, preparedProcess.IsLocal);
}
catch (Exception e)
{
if (showMessages)
await MessageBus.INSTANCE.SendError(new (@Icons.Material.Filled.AppsOutage, TB("It seems that Pandoc is not installed.")));
LOG.LogError("Pandoc is not installed and threw an exception: {0}", e.Message);
return new(false, TB("It seems that Pandoc is not installed."), false, string.Empty, false);
}
}
/// <summary>
/// Automatically decompresses the latest pandoc archive into AiStudio's data directory
/// </summary>
/// <param name="rustService">Global rust service to access file system and data dir</param>
/// <returns>None</returns>
public static async Task InstallAsync(RustService rustService)
{
var latestVersion = await FetchLatestVersionAsync();
var installDir = await GetPandocDataFolder(rustService);
ClearFolder(installDir);
LOG.LogInformation("Trying to install Pandoc v{0} to '{1}'...", latestVersion, installDir);
try
{
if (!Directory.Exists(installDir))
Directory.CreateDirectory(installDir);
// Create a temporary file to download the archive to:
var pandocTempDownloadFile = Path.GetTempFileName();
//
// Download the latest Pandoc archive from GitHub:
//
var uri = await GenerateArchiveUriAsync();
using (var client = new HttpClient())
{
var response = await client.GetAsync(uri);
if (!response.IsSuccessStatusCode)
{
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.Error, TB("Pandoc was not installed successfully, because the archive was not found.")));
LOG.LogError("Pandoc was not installed successfully, because the archive was not found (status code {0}): url='{1}', message='{2}'", response.StatusCode, uri, response.RequestMessage);
return;
}
// Download the archive to the temporary file:
await using var tempFileStream = File.Create(pandocTempDownloadFile);
await response.Content.CopyToAsync(tempFileStream);
}
if (uri.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
{
ZipFile.ExtractToDirectory(pandocTempDownloadFile, installDir);
}
else if (uri.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase))
{
await using var tgzStream = File.Open(pandocTempDownloadFile, FileMode.Open, FileAccess.Read, FileShare.Read);
await using var uncompressedStream = new GZipStream(tgzStream, CompressionMode.Decompress);
await TarFile.ExtractToDirectoryAsync(uncompressedStream, installDir, true);
}
else
{
await MessageBus.INSTANCE.SendError(new (Icons.Material.Filled.Error, TB("Pandoc was not installed successfully, because the archive type is unknown.")));
LOG.LogError("Pandoc was not installed, the archive is unknown: url='{0}'", uri);
return;
}
File.Delete(pandocTempDownloadFile);
await MessageBus.INSTANCE.SendSuccess(new(Icons.Material.Filled.CheckCircle, string.Format(TB("Pandoc v{0} was installed successfully."), latestVersion)));
LOG.LogInformation("Pandoc v{0} was installed successfully.", latestVersion);
}
catch (Exception ex)
{
LOG.LogError(ex, "An error occurred while installing Pandoc.");
}
}
private static void ClearFolder(string path)
{
if (!Directory.Exists(path))
return;
try
{
Directory.Delete(path, true);
}
catch (Exception ex)
{
LOG.LogError(ex, "Error clearing pandoc installation directory.");
}
}
/// <summary>
/// Asynchronously fetch the content from Pandoc's latest release page and extract the latest version number
/// </summary>
/// <remarks>Version numbers can have the following formats: x.x, x.x.x or x.x.x.x</remarks>
/// <returns>Latest Pandoc version number</returns>
public static async Task<string> FetchLatestVersionAsync() {
using var client = new HttpClient();
var response = await client.GetAsync(LATEST_URL);
if (!response.IsSuccessStatusCode)
{
LOG.LogError("Code {StatusCode}: Could not fetch Pandoc's latest page: {Response}", response.StatusCode, response.RequestMessage);
await MessageBus.INSTANCE.SendWarning(new (Icons.Material.Filled.Warning, string.Format(TB("The latest Pandoc version was not found, installing version {0} instead."), FALLBACK_VERSION.ToString())));
return FALLBACK_VERSION.ToString();
}
var htmlContent = await response.Content.ReadAsStringAsync();
var versionMatch = LatestVersionRegex().Match(htmlContent);
if (!versionMatch.Success)
{
LOG.LogError("The latest version regex returned nothing: {0}", versionMatch.Groups.ToString());
await MessageBus.INSTANCE.SendWarning(new (Icons.Material.Filled.Warning, string.Format(TB("The latest Pandoc version was not found, installing version {0} instead."), FALLBACK_VERSION.ToString())));
return FALLBACK_VERSION.ToString();
}
var version = versionMatch.Groups[1].Value;
return version;
}
/// <summary>
/// Reads the systems architecture to find the correct archive.
/// </summary>
/// <returns>Full URI to the right archive in Pandoc's repository.</returns>
public static async Task<string> GenerateArchiveUriAsync()
{
var version = await FetchLatestVersionAsync();
var baseUri = $"{DOWNLOAD_URL}/{version}/pandoc-{version}-";
return CPU_ARCHITECTURE switch
{
//
// Unfortunately, pandoc is not yet available for ARM64 Windows systems,
// so we have to use the x86_64 version for now. ARM Windows contains
// an x86_64 emulation layer, so it should work fine for now.
//
// Pandoc would be available for ARM64 Windows, but the Haskell compiler
// does not support ARM64 Windows yet. Here are the related issues:
//
// - Haskell compiler: https://gitlab.haskell.org/ghc/ghc/-/issues/24603
// - Haskell ARM MR: https://gitlab.haskell.org/ghc/ghc/-/merge_requests/13856
// - Pandoc ARM64: https://github.com/jgm/pandoc/issues/10095
//
RID.WIN_X64 or RID.WIN_ARM64 => $"{baseUri}windows-x86_64.zip",
RID.OSX_X64 => $"{baseUri}x86_64-macOS.zip",
RID.OSX_ARM64 => $"{baseUri}arm64-macOS.zip",
RID.LINUX_X64 => $"{baseUri}linux-amd64.tar.gz",
RID.LINUX_ARM64 => $"{baseUri}linux-arm64.tar.gz",
_ => string.Empty,
};
}
/// <summary>
/// Reads the systems architecture to find the correct Pandoc installer
/// </summary>
/// <returns>Full URI to the right installer in Pandoc's repo</returns>
public static async Task<string> GenerateInstallerUriAsync()
{
var version = await FetchLatestVersionAsync();
var baseUri = $"{DOWNLOAD_URL}/{version}/pandoc-{version}-";
switch (CPU_ARCHITECTURE)
{
//
// Unfortunately, pandoc is not yet available for ARM64 Windows systems,
// so we have to use the x86_64 version for now. ARM Windows contains
// an x86_64 emulation layer, so it should work fine for now.
//
// Pandoc would be available for ARM64 Windows, but the Haskell compiler
// does not support ARM64 Windows yet. Here are the related issues:
//
// - Haskell compiler: https://gitlab.haskell.org/ghc/ghc/-/issues/24603
// - Haskell ARM MR: https://gitlab.haskell.org/ghc/ghc/-/merge_requests/13856
// - Pandoc ARM64: https://github.com/jgm/pandoc/issues/10095
//
case RID.WIN_X64 or RID.WIN_ARM64:
return $"{baseUri}windows-x86_64.msi";
case RID.OSX_X64:
return $"{baseUri}x86_64-macOS.pkg";
case RID.OSX_ARM64:
return $"{baseUri}arm64-macOS.pkg";
default:
await MessageBus.INSTANCE.SendError(new (Icons.Material.Filled.Terminal, string.Format(TB("Installers are not available on {0} systems."), CPU_ARCHITECTURE.ToUserFriendlyName())));
return string.Empty;
}
}
public static async Task<string> GetPandocDataFolder(RustService rustService) => Path.Join(await rustService.GetDataDirectory(), "pandoc");
[GeneratedRegex(@"pandoc(?:\.exe)?\s*([0-9]+\.[0-9]+(?:\.[0-9]+)?(?:\.[0-9]+)?)")]
private static partial Regex PandocCmdRegex();
[GeneratedRegex(@"pandoc(?:\.exe)?\s*([0-9]+\.[0-9]+(?:\.[0-9]+)?(?:\.[0-9]+)?)")]
private static partial Regex LatestVersionRegex();
}
@@ -0,0 +1,3 @@
namespace AIStudio.Tools;
public readonly record struct PandocExecutable(string Executable, bool IsLocalInstallation);
@@ -0,0 +1,3 @@
namespace AIStudio.Tools;
public readonly record struct PandocInstallation(bool CheckWasSuccessful, string ErrorMessage, bool IsAvailable, string Version, bool IsLocalInstallation);
@@ -0,0 +1,10 @@
using System.Diagnostics;
namespace AIStudio.Tools;
public sealed class PandocPreparedProcess(ProcessStartInfo startInfo, bool isLocal)
{
public ProcessStartInfo StartInfo => startInfo;
public bool IsLocal => isLocal;
}
@@ -0,0 +1,135 @@
using System.Diagnostics;
using System.Reflection;
using System.Text;
using AIStudio.Tools.Metadata;
using AIStudio.Tools.Services;
using SharedTools;
namespace AIStudio.Tools;
public sealed class PandocProcessBuilder
{
private static readonly Assembly ASSEMBLY = Assembly.GetExecutingAssembly();
private static readonly MetaDataArchitectureAttribute META_DATA_ARCH = ASSEMBLY.GetCustomAttribute<MetaDataArchitectureAttribute>()!;
private static readonly RID CPU_ARCHITECTURE = META_DATA_ARCH.Architecture.ToRID();
private string? providedInputFile;
private string? providedOutputFile;
private string? providedInputFormat;
private string? providedOutputFormat;
private readonly List<string> additionalArguments = new();
private PandocProcessBuilder()
{
}
public static PandocProcessBuilder Create() => new();
public PandocProcessBuilder WithInputFile(string inputFile)
{
this.providedInputFile = inputFile;
return this;
}
public PandocProcessBuilder WithOutputFile(string outputFile)
{
this.providedOutputFile = outputFile;
return this;
}
public PandocProcessBuilder WithInputFormat(string inputFormat)
{
this.providedInputFormat = inputFormat;
return this;
}
public PandocProcessBuilder WithOutputFormat(string outputFormat)
{
this.providedOutputFormat = outputFormat;
return this;
}
public PandocProcessBuilder AddArgument(string argument)
{
this.additionalArguments.Add(argument);
return this;
}
public async Task<PandocPreparedProcess> BuildAsync(RustService rustService)
{
var sbArguments = new StringBuilder();
if(!string.IsNullOrWhiteSpace(this.providedInputFile))
sbArguments.Append(this.providedInputFile);
if(!string.IsNullOrWhiteSpace(this.providedInputFormat))
sbArguments.Append($" -f {this.providedInputFormat}");
if(!string.IsNullOrWhiteSpace(this.providedOutputFormat))
sbArguments.Append($" -t {this.providedOutputFormat}");
foreach (var additionalArgument in this.additionalArguments)
sbArguments.Append($" {additionalArgument}");
if(!string.IsNullOrWhiteSpace(this.providedOutputFile))
sbArguments.Append($" -o {this.providedOutputFile}");
var pandocExecutable = await PandocExecutablePath(rustService);
return new (new ProcessStartInfo
{
FileName = pandocExecutable.Executable,
Arguments = sbArguments.ToString(),
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
}, pandocExecutable.IsLocalInstallation);
}
/// <summary>
/// Returns the path to the pandoc executable.
/// </summary>
/// <remarks>
/// Any local installation of pandoc will be preferred over the system-wide installation.
/// When a local installation is found, its absolute path will be returned. In case no local
/// installation is found, the name of the pandoc executable will be returned.
/// </remarks>
/// <param name="rustService">Global rust service to access file system and data dir.</param>
/// <returns>Path to the pandoc executable.</returns>
private static async Task<PandocExecutable> PandocExecutablePath(RustService rustService)
{
//
// First, we try to find the pandoc executable in the data directory.
// Any local installation should be preferred over the system-wide installation.
//
var localInstallationRootDirectory = await Pandoc.GetPandocDataFolder(rustService);
try
{
var executableName = PandocExecutableName;
var subdirectories = Directory.GetDirectories(localInstallationRootDirectory, "*", SearchOption.AllDirectories);
foreach (var subdirectory in subdirectories)
{
var pandocPath = Path.Combine(subdirectory, executableName);
if (File.Exists(pandocPath))
return new(pandocPath, true);
}
}
catch
{
// ignored
}
//
// When no local installation was found, we assume that the pandoc executable is in the system PATH.
//
return new(PandocExecutableName, false);
}
/// <summary>
/// Reads the os platform to determine the used executable name.
/// </summary>
public static string PandocExecutableName => CPU_ARCHITECTURE is RID.WIN_ARM64 or RID.WIN_X64 ? "pandoc.exe" : "pandoc";
}
@@ -0,0 +1,193 @@
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
using Lua;
using Host = AIStudio.Provider.SelfHosted.Host;
using Model = AIStudio.Provider.Model;
namespace AIStudio.Tools.PluginSystem;
public sealed class PluginConfiguration(bool isInternal, LuaState state, PluginType type) : PluginBase(isInternal, state, type)
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(PluginConfiguration).Namespace, nameof(PluginConfiguration));
private static readonly ILogger<PluginConfiguration> LOGGER = Program.LOGGER_FACTORY.CreateLogger<PluginConfiguration>();
private static readonly SettingsLocker SETTINGS_LOCKER = Program.SERVICE_PROVIDER.GetRequiredService<SettingsLocker>();
private static readonly SettingsManager SETTINGS_MANAGER = Program.SERVICE_PROVIDER.GetRequiredService<SettingsManager>();
public async Task InitializeAsync()
{
if(!this.TryProcessConfiguration(out var issue))
this.pluginIssues.Add(issue);
await SETTINGS_MANAGER.StoreSettings();
await MessageBus.INSTANCE.SendMessage<bool>(null, Event.CONFIGURATION_CHANGED);
}
/// <summary>
/// Tries to initialize the UI text content of the plugin.
/// </summary>
/// <param name="message">The error message, when the UI text content could not be read.</param>
/// <returns>True, when the UI text content could be read successfully.</returns>
private bool TryProcessConfiguration(out string message)
{
// Ensure that the main CONFIG table exists and is a valid Lua table:
if (!this.state.Environment["CONFIG"].TryRead<LuaTable>(out var mainTable))
{
message = TB("The CONFIG table does not exist or is not a valid table.");
return false;
}
//
// Configured settings
//
if (!mainTable.TryGetValue("SETTINGS", out var settingsValue) || !settingsValue.TryRead<LuaTable>(out var settingsTable))
{
message = TB("The SETTINGS table does not exist or is not a valid table.");
return false;
}
if (settingsTable.TryGetValue("DataApp.UpdateBehavior", out var updateBehaviorValue) && updateBehaviorValue.TryRead<string>(out var updateBehaviorText) && Enum.TryParse<UpdateBehavior>(updateBehaviorText, true, out var updateBehavior))
{
SETTINGS_LOCKER.Register<DataApp>(x => x.UpdateBehavior, this.Id);
SETTINGS_MANAGER.ConfigurationData.App.UpdateBehavior = updateBehavior;
}
//
// Configured providers
//
if (!mainTable.TryGetValue("LLM_PROVIDERS", out var providersValue) || !providersValue.TryRead<LuaTable>(out var providersTable))
{
message = TB("The LLM_PROVIDERS table does not exist or is not a valid table.");
return false;
}
message = string.Empty;
var numberProviders = providersTable.ArrayLength;
var configuredProviders = new List<Settings.Provider>(numberProviders);
for (var i = 1; i <= numberProviders; i++)
{
var providerLuaTableValue = providersTable[i];
if (!providerLuaTableValue.TryRead<LuaTable>(out var providerLuaTable))
{
LOGGER.LogWarning($"The LLM_PROVIDERS table at index {i} is not a valid table.");
continue;
}
if(this.TryReadProviderTable(i, providerLuaTable, out var provider))
configuredProviders.Add(provider);
else
LOGGER.LogWarning($"The LLM_PROVIDERS table at index {i} does not contain a valid provider configuration.");
}
//
// Apply the configured providers to the system settings:
//
#pragma warning disable MWAIS0001
foreach (var configuredProvider in configuredProviders)
{
// The iterating variable is immutable, so we need to create a local copy:
var provider = configuredProvider;
var providerIndex = SETTINGS_MANAGER.ConfigurationData.Providers.FindIndex(p => p.Id == provider.Id);
if (providerIndex > -1)
{
// Case: The provider already exists, we update it:
var existingProvider = SETTINGS_MANAGER.ConfigurationData.Providers[providerIndex];
provider = provider with { Num = existingProvider.Num }; // Keep the original number
SETTINGS_MANAGER.ConfigurationData.Providers[providerIndex] = provider;
}
else
{
// Case: The provider does not exist, we add it:
provider = provider with { Num = SETTINGS_MANAGER.ConfigurationData.NextProviderNum++ };
SETTINGS_MANAGER.ConfigurationData.Providers.Add(provider);
}
}
#pragma warning restore MWAIS0001
return true;
}
private bool TryReadProviderTable(int idx, LuaTable table, out Settings.Provider provider)
{
provider = default;
if (!table.TryGetValue("Id", out var idValue) || !idValue.TryRead<string>(out var idText) || !Guid.TryParse(idText, out var id))
{
LOGGER.LogWarning($"The configured provider {idx} does not contain a valid ID. The ID must be a valid GUID.");
return false;
}
if (!table.TryGetValue("InstanceName", out var instanceNameValue) || !instanceNameValue.TryRead<string>(out var instanceName))
{
LOGGER.LogWarning($"The configured provider {idx} does not contain a valid instance name.");
return false;
}
if (!table.TryGetValue("UsedLLMProvider", out var usedLLMProviderValue) || !usedLLMProviderValue.TryRead<string>(out var usedLLMProviderText) || !Enum.TryParse<LLMProviders>(usedLLMProviderText, true, out var usedLLMProvider))
{
LOGGER.LogWarning($"The configured provider {idx} does not contain a valid LLM provider enum value.");
return false;
}
if (!table.TryGetValue("Host", out var hostValue) || !hostValue.TryRead<string>(out var hostText) || !Enum.TryParse<Host>(hostText, true, out var host))
{
LOGGER.LogWarning($"The configured provider {idx} does not contain a valid host enum value.");
return false;
}
if (!table.TryGetValue("Hostname", out var hostnameValue) || !hostnameValue.TryRead<string>(out var hostname))
{
LOGGER.LogWarning($"The configured provider {idx} does not contain a valid hostname.");
return false;
}
if (!table.TryGetValue("Model", out var modelValue) || !modelValue.TryRead<LuaTable>(out var modelTable))
{
LOGGER.LogWarning($"The configured provider {idx} does not contain a valid model table.");
return false;
}
if (!this.TryReadModelTable(idx, modelTable, out var model))
{
LOGGER.LogWarning($"The configured provider {idx} does not contain a valid model configuration.");
return false;
}
provider = new()
{
Num = 0,
Id = id.ToString(),
InstanceName = instanceName,
UsedLLMProvider = usedLLMProvider,
Model = model,
IsSelfHosted = usedLLMProvider is LLMProviders.SELF_HOSTED,
IsEnterpriseConfiguration = true,
EnterpriseConfigurationPluginId = this.Id,
Hostname = hostname,
Host = host
};
return true;
}
private bool TryReadModelTable(int idx, LuaTable table, out Model model)
{
model = default;
if (!table.TryGetValue("Id", out var idValue) || !idValue.TryRead<string>(out var id))
{
LOGGER.LogWarning($"The configured provider {idx} does not contain a valid model ID.");
return false;
}
if (!table.TryGetValue("DisplayName", out var displayNameValue) || !displayNameValue.TryRead<string>(out var displayName))
{
LOGGER.LogWarning($"The configured provider {idx} does not contain a valid model display name.");
return false;
}
model = new(id, displayName);
return true;
}
}
@@ -0,0 +1,56 @@
using System.IO.Compression;
namespace AIStudio.Tools.PluginSystem;
public static partial class PluginFactory
{
public static async Task<bool> TryDownloadingConfigPluginAsync(Guid configPlugId, string configServerUrl, CancellationToken cancellationToken = default)
{
if (!IS_INITIALIZED)
return false;
LOG.LogInformation($"Downloading configuration plugin with ID: {configPlugId} from server: {configServerUrl}");
var tempDownloadFile = Path.GetTempFileName();
try
{
using var httpClient = new HttpClient();
var response = await httpClient.GetAsync($"{configServerUrl}/{configPlugId}.zip", cancellationToken);
if (response.IsSuccessStatusCode)
{
await using var tempFileStream = File.Create(tempDownloadFile);
await response.Content.CopyToAsync(tempFileStream, cancellationToken);
var pluginDirectory = Path.Join(CONFIGURATION_PLUGINS_ROOT, configPlugId.ToString());
if(Directory.Exists(pluginDirectory))
Directory.Delete(pluginDirectory, true);
Directory.CreateDirectory(pluginDirectory);
ZipFile.ExtractToDirectory(tempDownloadFile, pluginDirectory);
LOG.LogInformation($"Configuration plugin with ID='{configPlugId}' downloaded and extracted successfully to '{pluginDirectory}'.");
}
else
LOG.LogError($"Failed to download the enterprise configuration plugin. HTTP Status: {response.StatusCode}");
}
catch (Exception e)
{
LOG.LogError(e, "An error occurred while downloading or extracting the enterprise configuration plugin.");
}
finally
{
if (File.Exists(tempDownloadFile))
{
try
{
File.Delete(tempDownloadFile);
}
catch (Exception e)
{
LOG.LogError(e, "Failed to delete the temporary download file.");
}
}
}
return true;
}
}
@@ -15,32 +15,11 @@ public static partial class PluginFactory
LOG.LogInformation($"Start hot reloading plugins for path '{HOT_RELOAD_WATCHER.Path}'.");
try
{
var messageBus = Program.SERVICE_PROVIDER.GetRequiredService<MessageBus>();
HOT_RELOAD_WATCHER.IncludeSubdirectories = true;
HOT_RELOAD_WATCHER.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
HOT_RELOAD_WATCHER.Filter = "*.lua";
HOT_RELOAD_WATCHER.Changed += async (_, args) =>
{
var changeType = args.ChangeType.ToString().ToLowerInvariant();
if (!await HOT_RELOAD_SEMAPHORE.WaitAsync(0))
{
LOG.LogInformation($"File changed ({changeType}): {args.FullPath}. Already processing another change.");
return;
}
try
{
LOG.LogInformation($"File changed ({changeType}): {args.FullPath}. Reloading plugins...");
await LoadAll();
await messageBus.SendMessage<bool>(null, Event.PLUGINS_RELOADED);
}
finally
{
HOT_RELOAD_SEMAPHORE.Release();
}
};
HOT_RELOAD_WATCHER.Changed += HotReloadEventHandler;
HOT_RELOAD_WATCHER.Deleted += HotReloadEventHandler;
HOT_RELOAD_WATCHER.EnableRaisingEvents = true;
}
catch (Exception e)
@@ -52,4 +31,32 @@ public static partial class PluginFactory
LOG.LogInformation("Hot reloading plugins set up.");
}
}
private static async void HotReloadEventHandler(object _, FileSystemEventArgs args)
{
try
{
var changeType = args.ChangeType.ToString().ToLowerInvariant();
if (!await HOT_RELOAD_SEMAPHORE.WaitAsync(0))
{
LOG.LogInformation($"File changed ({changeType}): {args.FullPath}. Already processing another change.");
return;
}
try
{
LOG.LogInformation($"File changed ({changeType}): {args.FullPath}. Reloading plugins...");
await LoadAll();
await MessageBus.INSTANCE.SendMessage<bool>(null, Event.PLUGINS_RELOADED);
}
finally
{
HOT_RELOAD_SEMAPHORE.Release();
}
}
catch (Exception e)
{
LOG.LogError(e, $"Error while handling hot reload event for file '{args.FullPath}' with change type '{args.ChangeType}'.");
}
}
}
@@ -1,5 +1,7 @@
using System.Text;
using AIStudio.Settings.DataModel;
using Lua;
using Lua.Standard;
@@ -58,8 +60,11 @@ public static partial class PluginFactory
try
{
if (cancellationToken.IsCancellationRequested)
{
LOG.LogWarning("Was not able to load all plugins, because the operation was cancelled. It seems to be a timeout.");
break;
}
LOG.LogInformation($"Try to load plugin: {pluginMainFile}");
var fileInfo = new FileInfo(pluginMainFile);
string code;
@@ -113,6 +118,61 @@ public static partial class PluginFactory
PLUGIN_LOAD_SEMAPHORE.Release();
LOG.LogInformation("Finished loading plugins.");
}
//
// Next, we have to clean up our settings. It is possible that a configuration plugin was removed.
// We have to remove the related settings as well:
//
var wasConfigurationChanged = false;
//
// Check LLM providers:
//
#pragma warning disable MWAIS0001
var configuredProviders = SETTINGS_MANAGER.ConfigurationData.Providers.ToList();
foreach (var configuredProvider in configuredProviders)
{
if(!configuredProvider.IsEnterpriseConfiguration)
continue;
var providerSourcePluginId = configuredProvider.EnterpriseConfigurationPluginId;
if(providerSourcePluginId == Guid.Empty)
continue;
var providerSourcePlugin = AVAILABLE_PLUGINS.FirstOrDefault(plugin => plugin.Id == providerSourcePluginId);
if(providerSourcePlugin is null)
{
LOG.LogWarning($"The configured LLM provider '{configuredProvider.InstanceName}' (id={configuredProvider.Id}) is based on a plugin that is not available anymore. Removing the provider from the settings.");
SETTINGS_MANAGER.ConfigurationData.Providers.Remove(configuredProvider);
wasConfigurationChanged = true;
}
}
#pragma warning restore MWAIS0001
//
// Check all possible settings:
//
if (SETTINGS_LOCKER.GetConfigurationPluginId<DataApp>(x => x.UpdateBehavior) is var updateBehaviorPluginId && updateBehaviorPluginId != Guid.Empty)
{
var sourcePlugin = AVAILABLE_PLUGINS.FirstOrDefault(plugin => plugin.Id == updateBehaviorPluginId);
if (sourcePlugin is null)
{
// Remove the locked state:
SETTINGS_LOCKER.Remove<DataApp>(x => x.UpdateBehavior);
// Reset the setting to the default value:
SETTINGS_MANAGER.ConfigurationData.App.UpdateBehavior = UpdateBehavior.HOURLY;
LOG.LogWarning($"The configured update behavior is based on a plugin that is not available anymore. Resetting the setting to the default value: {SETTINGS_MANAGER.ConfigurationData.App.UpdateBehavior}.");
wasConfigurationChanged = true;
}
}
if (wasConfigurationChanged)
{
await SETTINGS_MANAGER.StoreSettings();
await MessageBus.INSTANCE.SendMessage<bool>(null, Event.CONFIGURATION_CHANGED);
}
}
public static async Task<PluginBase> Load(string? pluginPath, string code, CancellationToken cancellationToken = default)
@@ -158,11 +218,18 @@ public static partial class PluginFactory
return new NoPlugin($"TYPE is not a valid plugin type. Valid types are: {CommonTools.GetAllEnumValues<PluginType>()}");
var isInternal = !string.IsNullOrWhiteSpace(pluginPath) && pluginPath.StartsWith(INTERNAL_PLUGINS_ROOT, StringComparison.OrdinalIgnoreCase);
return type switch
switch (type)
{
PluginType.LANGUAGE => new PluginLanguage(isInternal, state, type),
case PluginType.LANGUAGE:
return new PluginLanguage(isInternal, state, type);
_ => new NoPlugin("This plugin type is not supported yet. Please try again with a future version of AI Studio.")
};
case PluginType.CONFIGURATION:
var configPlug = new PluginConfiguration(isInternal, state, type);
await configPlug.InitializeAsync();
return configPlug;
default:
return new NoPlugin("This plugin type is not supported yet. Please try again with a future version of AI Studio.");
}
}
}
@@ -0,0 +1,54 @@
namespace AIStudio.Tools.PluginSystem;
public static partial class PluginFactory
{
public static void RemovePluginAsync(Guid pluginId)
{
if (!IS_INITIALIZED)
return;
LOG.LogWarning($"Try to remove plugin with ID: {pluginId}");
//
// Remove the plugin from the available plugins list:
//
var availablePluginToRemove = AVAILABLE_PLUGINS.FirstOrDefault(p => p.Id == pluginId);
if (availablePluginToRemove == null)
{
LOG.LogWarning($"No plugin found with ID: {pluginId}");
return;
}
AVAILABLE_PLUGINS.Remove(availablePluginToRemove);
//
// Remove the plugin from the running plugins list:
//
var runningPluginToRemove = RUNNING_PLUGINS.FirstOrDefault(p => p.Id == pluginId);
if (runningPluginToRemove == null)
LOG.LogWarning($"No running plugin found with ID: {pluginId}");
else
RUNNING_PLUGINS.Remove(runningPluginToRemove);
//
// Delete the plugin directory:
//
var pluginDirectory = Path.Join(CONFIGURATION_PLUGINS_ROOT, availablePluginToRemove.Id.ToString());
if (Directory.Exists(pluginDirectory))
{
try
{
Directory.Delete(pluginDirectory, true);
LOG.LogInformation($"Plugin directory '{pluginDirectory}' deleted successfully.");
}
catch (Exception ex)
{
LOG.LogError(ex, $"Failed to delete plugin directory '{pluginDirectory}'.");
}
}
else
LOG.LogWarning($"Plugin directory '{pluginDirectory}' does not exist.");
LOG.LogInformation($"Plugin with ID: {pluginId} removed successfully.");
}
}
@@ -22,48 +22,59 @@ public static partial class PluginFactory
var baseLanguagePluginId = InternalPlugin.LANGUAGE_EN_US.MetaData().Id;
var baseLanguagePluginMetaData = AVAILABLE_PLUGINS.FirstOrDefault(p => p.Id == baseLanguagePluginId);
if (baseLanguagePluginMetaData is null)
{
LOG.LogError($"Was not able to find the base language plugin: Id='{baseLanguagePluginId}'. Please check your installation.");
return;
}
var startedBasePlugin = await Start(baseLanguagePluginMetaData, cancellationToken);
if (startedBasePlugin is NoPlugin noPlugin)
{
LOG.LogError($"Was not able to start the base language plugin: Id='{baseLanguagePluginId}'. Reason: {noPlugin.Issues.First()}");
return;
}
if (startedBasePlugin is PluginLanguage languagePlugin)
{
BASE_LANGUAGE_PLUGIN = languagePlugin;
RUNNING_PLUGINS.Add(languagePlugin);
LOG.LogInformation($"Successfully started the base language plugin: Id='{languagePlugin.Id}', Type='{languagePlugin.Type}', Name='{languagePlugin.Name}', Version='{languagePlugin.Version}'");
}
else
{
LOG.LogError($"Was not able to start the base language plugin: Id='{baseLanguagePluginId}'. Reason: {string.Join("; ", startedBasePlugin.Issues)}");
return;
try
{
var startedBasePlugin = await Start(baseLanguagePluginMetaData, cancellationToken);
if (startedBasePlugin is NoPlugin noPlugin)
LOG.LogError($"Was not able to start the base language plugin: Id='{baseLanguagePluginId}'. Reason: {noPlugin.Issues.First()}");
if (startedBasePlugin is PluginLanguage languagePlugin)
{
BASE_LANGUAGE_PLUGIN = languagePlugin;
RUNNING_PLUGINS.Add(languagePlugin);
LOG.LogInformation($"Successfully started the base language plugin: Id='{languagePlugin.Id}', Type='{languagePlugin.Type}', Name='{languagePlugin.Name}', Version='{languagePlugin.Version}'");
}
else
LOG.LogError($"Was not able to start the base language plugin: Id='{baseLanguagePluginId}'. Reason: {string.Join("; ", startedBasePlugin.Issues)}");
}
catch (Exception e)
{
LOG.LogError(e, $"An error occurred while starting the base language plugin: Id='{baseLanguagePluginId}'.");
BASE_LANGUAGE_PLUGIN = NoPluginLanguage.INSTANCE;
}
}
//
// Iterate over all available plugins and try to start them.
//
foreach (var availablePlugin in AVAILABLE_PLUGINS)
{
if(cancellationToken.IsCancellationRequested)
{
LOG.LogWarning("Cancellation requested while starting plugins. Stopping the plugin startup process. Probably due to a timeout.");
break;
}
if (availablePlugin.Id == baseLanguagePluginId)
continue;
if (availablePlugin.IsInternal || SETTINGS_MANAGER.IsPluginEnabled(availablePlugin))
if(await Start(availablePlugin, cancellationToken) is { IsValid: true } plugin)
RUNNING_PLUGINS.Add(plugin);
// Inform all components that the plugins have been reloaded or started:
await MessageBus.INSTANCE.SendMessage<bool>(null, Event.PLUGINS_RELOADED);
try
{
if (availablePlugin.IsInternal || SETTINGS_MANAGER.IsPluginEnabled(availablePlugin) || availablePlugin.Type == PluginType.CONFIGURATION)
if(await Start(availablePlugin, cancellationToken) is { IsValid: true } plugin)
RUNNING_PLUGINS.Add(plugin);
}
catch (Exception e)
{
LOG.LogError(e, $"An error occurred while starting the plugin: Id='{availablePlugin.Id}', Type='{availablePlugin.Type}', Name='{availablePlugin.Name}', Version='{availablePlugin.Version}'.");
}
}
// Inform all components that the plugins have been reloaded or started:
await MessageBus.INSTANCE.SendMessage<bool>(null, Event.PLUGINS_RELOADED);
}
private static async Task<PluginBase> Start(IAvailablePlugin meta, CancellationToken cancellationToken = default)
@@ -91,6 +102,9 @@ public static partial class PluginFactory
if (plugin is PluginLanguage languagePlugin && BASE_LANGUAGE_PLUGIN != NoPluginLanguage.INSTANCE)
languagePlugin.SetBaseLanguage(BASE_LANGUAGE_PLUGIN);
if(plugin is PluginConfiguration configPlugin)
await configPlugin.InitializeAsync();
LOG.LogInformation($"Successfully started plugin: Id='{plugin.Id}', Type='{plugin.Type}', Name='{plugin.Name}', Version='{plugin.Version}'");
return plugin;
}
@@ -6,11 +6,13 @@ public static partial class PluginFactory
{
private static readonly ILogger LOG = Program.LOGGER_FACTORY.CreateLogger(nameof(PluginFactory));
private static readonly SettingsManager SETTINGS_MANAGER = Program.SERVICE_PROVIDER.GetRequiredService<SettingsManager>();
private static readonly SettingsLocker SETTINGS_LOCKER = Program.SERVICE_PROVIDER.GetRequiredService<SettingsLocker>();
private static bool IS_INITIALIZED;
private static string DATA_DIR = string.Empty;
private static string PLUGINS_ROOT = string.Empty;
private static string INTERNAL_PLUGINS_ROOT = string.Empty;
private static string CONFIGURATION_PLUGINS_ROOT = string.Empty;
private static FileSystemWatcher HOT_RELOAD_WATCHER = null!;
private static ILanguagePlugin BASE_LANGUAGE_PLUGIN = NoPluginLanguage.INSTANCE;
@@ -28,6 +30,7 @@ public static partial class PluginFactory
DATA_DIR = SettingsManager.DataDirectory!;
PLUGINS_ROOT = Path.Join(DATA_DIR, "plugins");
INTERNAL_PLUGINS_ROOT = Path.Join(PLUGINS_ROOT, ".internal");
CONFIGURATION_PLUGINS_ROOT = Path.Join(PLUGINS_ROOT, ".config");
if (!Directory.Exists(PLUGINS_ROOT))
Directory.CreateDirectory(PLUGINS_ROOT);
@@ -0,0 +1,75 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Tools.Services;
public sealed class EnterpriseEnvironmentService(ILogger<TemporaryChatService> logger, RustService rustService) : BackgroundService
{
public static EnterpriseEnvironment CURRENT_ENVIRONMENT;
private static readonly TimeSpan CHECK_INTERVAL = TimeSpan.FromMinutes(16);
#region Overrides of BackgroundService
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogInformation("The enterprise environment service was initialized.");
await this.StartUpdating();
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(CHECK_INTERVAL, stoppingToken);
await this.StartUpdating();
}
}
#endregion
private async Task StartUpdating()
{
try
{
logger.LogInformation("Starting update of the enterprise environment.");
var enterpriseRemoveConfigId = await rustService.EnterpriseEnvRemoveConfigId();
var isPlugin2RemoveInUse = PluginFactory.AvailablePlugins.Any(plugin => plugin.Id == enterpriseRemoveConfigId);
if (enterpriseRemoveConfigId != Guid.Empty && isPlugin2RemoveInUse)
{
logger.LogWarning($"The enterprise environment configuration ID '{enterpriseRemoveConfigId}' must be removed.");
PluginFactory.RemovePluginAsync(enterpriseRemoveConfigId);
}
var enterpriseConfigServerUrl = await rustService.EnterpriseEnvConfigServerUrl();
var enterpriseConfigId = await rustService.EnterpriseEnvConfigId();
var nextEnterpriseEnvironment = new EnterpriseEnvironment(enterpriseConfigServerUrl, enterpriseConfigId);
if (CURRENT_ENVIRONMENT != nextEnterpriseEnvironment)
{
logger.LogInformation("The enterprise environment has changed. Updating the current environment.");
CURRENT_ENVIRONMENT = nextEnterpriseEnvironment;
switch (enterpriseConfigServerUrl)
{
case null when enterpriseConfigId == Guid.Empty:
logger.LogInformation("AI Studio runs without an enterprise configuration.");
break;
case null:
logger.LogWarning($"AI Studio runs with an enterprise configuration id ('{enterpriseConfigId}'), but the configuration server URL is not set.");
break;
case not null when enterpriseConfigId == Guid.Empty:
logger.LogWarning($"AI Studio runs with an enterprise configuration server URL ('{enterpriseConfigServerUrl}'), but the configuration ID is not set.");
break;
default:
logger.LogInformation($"AI Studio runs with an enterprise configuration id ('{enterpriseConfigId}') and configuration server URL ('{enterpriseConfigServerUrl}').");
await PluginFactory.TryDownloadingConfigPluginAsync(enterpriseConfigId, enterpriseConfigServerUrl);
break;
}
}
}
catch (Exception e)
{
logger.LogError(e, "An error occurred while updating the enterprise environment.");
}
}
}
@@ -0,0 +1,68 @@
namespace AIStudio.Tools.Services;
public sealed partial class RustService
{
/// <summary>
/// Tries to read the enterprise environment for the current user's configuration ID.
/// </summary>
/// <returns>
/// Returns the empty Guid when the environment is not set or the request fails.
/// Otherwise, the configuration ID.
/// </returns>
public async Task<Guid> EnterpriseEnvConfigId()
{
var result = await this.http.GetAsync("/system/enterprise/config/id");
if (!result.IsSuccessStatusCode)
{
this.logger!.LogError($"Failed to query the enterprise configuration ID: '{result.StatusCode}'");
return Guid.Empty;
}
Guid.TryParse(await result.Content.ReadAsStringAsync(), out var configurationId);
return configurationId;
}
/// <summary>
/// Tries to read the enterprise environment for a configuration ID, which must be removed.
/// </summary>
/// <remarks>
/// Removing a configuration ID is necessary when the user moved to another department or
/// left the company, or when the configuration ID is no longer valid.
/// </remarks>
/// <returns>
/// Returns the empty Guid when the environment is not set or the request fails.
/// Otherwise, the configuration ID.
/// </returns>
public async Task<Guid> EnterpriseEnvRemoveConfigId()
{
var result = await this.http.DeleteAsync("/system/enterprise/config/id");
if (!result.IsSuccessStatusCode)
{
this.logger!.LogError($"Failed to query the enterprise configuration ID for removal: '{result.StatusCode}'");
return Guid.Empty;
}
Guid.TryParse(await result.Content.ReadAsStringAsync(), out var configurationId);
return configurationId;
}
/// <summary>
/// Tries to read the enterprise environment for the current user's configuration server URL.
/// </summary>
/// <returns>
/// Returns null when the environment is not set or the request fails.
/// Otherwise, the configuration server URL.
/// </returns>
public async Task<string> EnterpriseEnvConfigServerUrl()
{
var result = await this.http.GetAsync("/system/enterprise/config/server");
if (!result.IsSuccessStatusCode)
{
this.logger!.LogError($"Failed to query the enterprise configuration server URL: '{result.StatusCode}'");
return string.Empty;
}
var serverUrl = await result.Content.ReadAsStringAsync();
return string.IsNullOrWhiteSpace(serverUrl) ? string.Empty : serverUrl;
}
}
@@ -3,13 +3,11 @@ using AIStudio.Settings.DataModel;
namespace AIStudio.Tools.Services;
public class TemporaryChatService(ILogger<TemporaryChatService> logger, SettingsManager settingsManager) : BackgroundService
public sealed class TemporaryChatService(ILogger<TemporaryChatService> logger, SettingsManager settingsManager) : BackgroundService
{
private static readonly TimeSpan CHECK_INTERVAL = TimeSpan.FromDays(1);
private static bool IS_INITIALIZED;
private readonly ILogger<TemporaryChatService> logger = logger;
#region Overrides of BackgroundService
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
@@ -17,12 +15,12 @@ public class TemporaryChatService(ILogger<TemporaryChatService> logger, Settings
while (!stoppingToken.IsCancellationRequested && !IS_INITIALIZED)
await Task.Delay(TimeSpan.FromSeconds(3), stoppingToken);
this.logger.LogInformation("The temporary chat maintenance service was initialized.");
logger.LogInformation("The temporary chat maintenance service was initialized.");
await settingsManager.LoadSettings();
if(settingsManager.ConfigurationData.Workspace.StorageTemporaryMaintenancePolicy is WorkspaceStorageTemporaryMaintenancePolicy.NO_AUTOMATIC_MAINTENANCE)
{
this.logger.LogWarning("Automatic maintenance of temporary chat storage is disabled. Exiting maintenance service.");
logger.LogWarning("Automatic maintenance of temporary chat storage is disabled. Exiting maintenance service.");
return;
}
@@ -38,11 +36,11 @@ public class TemporaryChatService(ILogger<TemporaryChatService> logger, Settings
private Task StartMaintenance()
{
this.logger.LogInformation("Starting maintenance of temporary chat storage.");
logger.LogInformation("Starting maintenance of temporary chat storage.");
var temporaryDirectories = Path.Join(SettingsManager.DataDirectory, "tempChats");
if(!Directory.Exists(temporaryDirectories))
{
this.logger.LogWarning("Temporary chat storage directory does not exist. End maintenance.");
logger.LogWarning("Temporary chat storage directory does not exist. End maintenance.");
return Task.CompletedTask;
}
@@ -67,12 +65,12 @@ public class TemporaryChatService(ILogger<TemporaryChatService> logger, Settings
if(deleteChat)
{
this.logger.LogInformation($"Deleting temporary chat storage directory '{tempChatDirPath}' due to maintenance policy.");
logger.LogInformation($"Deleting temporary chat storage directory '{tempChatDirPath}' due to maintenance policy.");
Directory.Delete(tempChatDirPath, true);
}
}
this.logger.LogInformation("Finished maintenance of temporary chat storage.");
logger.LogInformation("Finished maintenance of temporary chat storage.");
return Task.CompletedTask;
}
+31
View File
@@ -109,4 +109,35 @@
/* Fixed the slider part of MudSplitter inside context div for inner scrolling component */
.inner-scrolling-context > .mud-splitter > .mud-slider > .mud-slider-container {
padding-bottom: 12px;
}
.code-block {
background-color: #2d2d2d;
color: #f8f8f2;
border-radius: 6px !important;
overflow: auto !important;
font-family: Consolas, "Courier New", monospace !important;
text-align: left !important;
}
.code-block pre {
margin: 0 !important;
}
.code-block code {
font-family: inherit !important;
}
.inline-code-block {
background-color: #2d2d2d;
color: #f8f8f2;
border-radius: 6px;
font-family: Consolas, "Courier New", monospace;
text-align: left;
padding: 4px 6px;
margin: 0 2px;
}
.no-elevation {
box-shadow: none !important;
}
@@ -1 +1,6 @@
# v0.9.46, build 221 (2025-06-xx xx:xx UTC)
# v0.9.46, build 221 (2025-06-01 19:19 UTC)
- We just finished the first version of our plugin system. Right now, there are language plugins to help localize AI Studio and configuration plugins for enterprise environments. In the future, you’ll also be able to develop custom assistants as plugins. Languages and assistants will be available in public repositories, and AI Studio will have an app-store-like view for easy access. We’re proud to have set the foundation with this version.
- Completed the I18N system and made all 1,856 AI Studio text contents localizable.
- AI Studio comes with two standard plugins: one for English (US) and one for German (Germany). When you start AI Studio, it tries to pick the language set on your operating system. If your language isn't supported yet, it uses English instead.
- Added the ability to configure the maximum number of results returned per request for all data sources. Please note that this feature remains in preview and is not visible to all users.
- Added the Pandoc integration, which enables us to use Pandoc for data processing (e.g., RAG) and for generating files (e.g., Office documents). We thank Nils `nilskruthoff` for the excellent contribution.
@@ -0,0 +1 @@
# v0.9.47, build 222 (2025-06-xx xx:xx UTC)
@@ -59,5 +59,5 @@ public sealed class LocalConstantsAnalyzer : DiagnosticAnalyzer
}
private static bool IsUpperCase(string name) => name.All(c => char.IsUpper(c) || char.IsDigit(c) || c == '_') &&
!string.IsNullOrEmpty(name) && name.Any(char.IsLetter);
!string.IsNullOrWhiteSpace(name) && name.Any(char.IsLetter);
}
+4 -4
View File
@@ -1,11 +1,11 @@
0.9.45
2025-05-25 13:56:04 UTC
220
0.9.46
2025-06-01 19:19:04 UTC
221
9.0.106 (commit 8cdf6f0897)
9.0.5 (commit e36e4d1a8f)
1.87.0 (commit 17067e9ac)
8.6.0
1.8.1
05544eca15a, release
e8cfce05fea, release
osx-arm64
137.0.7123.0
+28 -6
View File
@@ -2624,7 +2624,7 @@ checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "mindwork-ai-studio"
version = "0.9.45"
version = "0.9.46"
dependencies = [
"aes",
"arboard",
@@ -2632,6 +2632,7 @@ dependencies = [
"base64 0.22.1",
"calamine",
"cbc",
"cfg-if",
"cipher",
"crossbeam-channel",
"file-format",
@@ -2660,6 +2661,7 @@ dependencies = [
"tokio",
"tokio-stream",
"url",
"windows-registry 0.5.2",
]
[[package]]
@@ -3978,7 +3980,7 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"windows-registry",
"windows-registry 0.4.0",
]
[[package]]
@@ -5949,15 +5951,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4286ad90ddb45071efd1a66dfa43eb02dd0dfbae1545ad6cc3c51cf34d7e8ba3"
dependencies = [
"windows-result",
"windows-strings",
"windows-strings 0.3.1",
"windows-targets 0.53.0",
]
[[package]]
name = "windows-result"
version = "0.3.2"
name = "windows-registry"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c64fd11a4fd95df68efcfee5f44a294fe71b8bc6a91993e2791938abcc712252"
checksum = "b3bab093bdd303a1240bb99b8aba8ea8a69ee19d34c9e2ef9594e708a4878820"
dependencies = [
"windows-link",
"windows-result",
"windows-strings 0.4.2",
]
[[package]]
name = "windows-result"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"
dependencies = [
"windows-link",
]
@@ -5971,6 +5984,15 @@ dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-sys"
version = "0.42.0"
+5 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "mindwork-ai-studio"
version = "0.9.45"
version = "0.9.46"
edition = "2021"
description = "MindWork AI Studio"
authors = ["Thorsten Sommer"]
@@ -37,6 +37,7 @@ file-format = "0.27.0"
calamine = "0.27.0"
pdfium-render = "0.8.31"
sys-locale = "0.3.2"
cfg-if = "1.0.0"
# Fixes security vulnerability downstream, where the upstream is not fixed yet:
url = "2.5"
@@ -50,5 +51,8 @@ reqwest = { version = "0.12.15", features = ["native-tls-vendored"] }
# Fixes security vulnerability downstream, where the upstream is not fixed yet:
openssl = "0.10.72"
[target.'cfg(target_os = "windows")'.dependencies]
windows-registry = "0.5.2"
[features]
custom-protocol = ["tauri/custom-protocol"]
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more