Compare commits

...
25 Commits
Author SHA1 Message Date
Thorsten Sommer 85a867459e Prepared release v0.9.43 (#457) 2025-05-11 19:30:25 +02:00
Thorsten Sommer ba236c4012 Add the DLR as the first titan supporter (#456) 2025-05-11 17:40:24 +02:00
Thorsten Sommer 9fa0f95611 Localized the embedding configuration (#455) 2025-05-11 16:57:52 +02:00
Thorsten Sommer f10d9a5d88 Improved the embedding configuration dialog (#454) 2025-05-11 15:35:19 +02:00
Thorsten Sommer 1a4e4781cd Enhanced Google model selection and updated the changelog (#453) 2025-05-11 15:01:04 +02:00
Thorsten Sommer 99b4d616c7 Updated changelog (#452) 2025-05-11 14:40:39 +02:00
Peer Schütt ace125d7cb Proofreading the automatic German translation (#451) 2025-05-11 13:58:43 +02:00
Thorsten Sommer d6af5a3afd Add model capabilities (#450) 2025-05-11 12:51:35 +02:00
Thorsten Sommer 07b858fd72 Updated README to reflect recent I18N enhancements (#449) 2025-05-05 18:49:06 +02:00
Thorsten Sommer 5d7949211f Fixed build script for Windows by fixing Windows PDFium download (#448) 2025-05-05 08:42:54 +02:00
Thorsten Sommer c23f0f49f9 Prepared release v0.9.42 (#447) 2025-05-04 15:06:45 +02:00
Thorsten Sommer 7a08baf99b Added more text content to the I18N system (#446) 2025-05-04 14:59:30 +02:00
Thorsten Sommer cfc2103b43 Improved I18N system (#445) 2025-05-03 21:47:43 +02:00
Thorsten Sommer f8dbc186fb Improved chat name generation to remove line breaks, tabs, etc. (#444) 2025-05-03 16:25:51 +02:00
Thorsten Sommer 6041b42510 Refactored I18N key handling in build script (#443) 2025-05-03 16:17:23 +02:00
Thorsten Sommer 10dc03f33b Added file type filtering to file selection dialogs (#442) 2025-05-03 15:43:12 +02:00
Thorsten Sommer 437ea2c243 Refactored metadata initialization (#441) 2025-05-03 14:26:13 +02:00
Thorsten Sommer b0d4615506 Refactored PDFium initialization (#440) 2025-05-03 12:20:22 +02:00
Thorsten Sommer c4d9af18cd Add component to read PDF files into assistants (#439)
Build and Release / Read metadata (push) Has been cancelled
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-unknown-linux-gnu, linux-x64, ubuntu-22.04, x86_64-unknown-linux-gnu, appimage deb updater) (push) Has been cancelled
Build and Release / Prepare & create release (push) Has been cancelled
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-apple-darwin, osx-arm64, macos-latest, aarch64-apple-darwin, dmg updater) (push) Has been cancelled
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-pc-windows-msvc.exe, win-arm64, windows-latest, aarch64-pc-windows-msvc, nsis updater) (push) Has been cancelled
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-unknown-linux-gnu, linux-arm64, ubuntu-22.04-arm, aarch64-unknown-linux-gnu, appimage deb updater) (push) Has been cancelled
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-apple-darwin, osx-x64, macos-latest, x86_64-apple-darwin, dmg updater) (push) Has been cancelled
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-pc-windows-msvc.exe, win-x64, windows-latest, x86_64-pc-windows-msvc, nsis updater) (push) Has been cancelled
Build and Release / Publish release (push) Has been cancelled
2025-05-02 23:09:50 +02:00
Thorsten Sommer 9996b810e2 Added "Changelog" writing style to assist in creating release notes (#438)
Build and Release / Publish release (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-apple-darwin, osx-x64, macos-latest, x86_64-apple-darwin, dmg updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-pc-windows-msvc.exe, win-x64, windows-latest, x86_64-pc-windows-msvc, nsis updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-unknown-linux-gnu, linux-x64, ubuntu-22.04, x86_64-unknown-linux-gnu, appimage deb updater) (push) Blocked by required conditions
Build and Release / Prepare & create release (push) Blocked by required conditions
Build and Release / Read metadata (push) Waiting to run
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-apple-darwin, osx-arm64, macos-latest, aarch64-apple-darwin, dmg updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-pc-windows-msvc.exe, win-arm64, windows-latest, aarch64-pc-windows-msvc, nsis updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-unknown-linux-gnu, linux-arm64, ubuntu-22.04-arm, aarch64-unknown-linux-gnu, appimage deb updater) (push) Blocked by required conditions
2025-05-02 12:11:23 +02:00
Thorsten Sommer 53ec4c2162 Improved app settings to apply language changes immediately (#437)
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-apple-darwin, osx-arm64, macos-latest, aarch64-apple-darwin, dmg updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-pc-windows-msvc.exe, win-arm64, windows-latest, aarch64-pc-windows-msvc, nsis updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-unknown-linux-gnu, linux-arm64, ubuntu-22.04-arm, aarch64-unknown-linux-gnu, appimage deb updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-apple-darwin, osx-x64, macos-latest, x86_64-apple-darwin, dmg updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-pc-windows-msvc.exe, win-x64, windows-latest, x86_64-pc-windows-msvc, nsis updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-unknown-linux-gnu, linux-x64, ubuntu-22.04, x86_64-unknown-linux-gnu, appimage deb updater) (push) Blocked by required conditions
Build and Release / Prepare & create release (push) Blocked by required conditions
Build and Release / Publish release (push) Blocked by required conditions
Build and Release / Read metadata (push) Waiting to run
2025-05-02 11:50:14 +02:00
Thorsten Sommer 38facf3e04 Improved internal plugin maintenance (#436)
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-unknown-linux-gnu, linux-x64, ubuntu-22.04, x86_64-unknown-linux-gnu, appimage deb updater) (push) Blocked by required conditions
Build and Release / Prepare & create release (push) Blocked by required conditions
Build and Release / Read metadata (push) Waiting to run
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-apple-darwin, osx-arm64, macos-latest, aarch64-apple-darwin, dmg updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-pc-windows-msvc.exe, win-arm64, windows-latest, aarch64-pc-windows-msvc, nsis updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-unknown-linux-gnu, linux-arm64, ubuntu-22.04-arm, aarch64-unknown-linux-gnu, appimage deb updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-apple-darwin, osx-x64, macos-latest, x86_64-apple-darwin, dmg updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-pc-windows-msvc.exe, win-x64, windows-latest, x86_64-pc-windows-msvc, nsis updater) (push) Blocked by required conditions
Build and Release / Publish release (push) Blocked by required conditions
2025-05-02 11:27:21 +02:00
Thorsten Sommer 68404199ba Improved model selection for OpenAI by excluding unsupported models (#435)
Build and Release / Read metadata (push) Waiting to run
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-apple-darwin, osx-arm64, macos-latest, aarch64-apple-darwin, dmg updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-pc-windows-msvc.exe, win-arm64, windows-latest, aarch64-pc-windows-msvc, nsis updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-unknown-linux-gnu, linux-arm64, ubuntu-22.04-arm, aarch64-unknown-linux-gnu, appimage deb updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-apple-darwin, osx-x64, macos-latest, x86_64-apple-darwin, dmg updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-pc-windows-msvc.exe, win-x64, windows-latest, x86_64-pc-windows-msvc, nsis updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-unknown-linux-gnu, linux-x64, ubuntu-22.04, x86_64-unknown-linux-gnu, appimage deb updater) (push) Blocked by required conditions
Build and Release / Prepare & create release (push) Blocked by required conditions
Build and Release / Publish release (push) Blocked by required conditions
2025-05-01 13:35:27 +02:00
Thorsten Sommer 08b8f42c25 Fixed localization assistant file loading issue in the release app (#434) 2025-05-01 13:23:57 +02:00
Thorsten Sommer 3c41fe2771 Fixed Markdown rendering issue and upgrade dependencies (#433)
Build and Release / Read metadata (push) Waiting to run
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-apple-darwin, osx-arm64, macos-latest, aarch64-apple-darwin, dmg updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-unknown-linux-gnu, linux-arm64, ubuntu-22.04-arm, aarch64-unknown-linux-gnu, appimage deb updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-apple-darwin, osx-x64, macos-latest, x86_64-apple-darwin, dmg updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-pc-windows-msvc.exe, win-x64, windows-latest, x86_64-pc-windows-msvc, nsis updater) (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-x86_64-unknown-linux-gnu, linux-x64, ubuntu-22.04, x86_64-unknown-linux-gnu, appimage deb updater) (push) Blocked by required conditions
Build and Release / Prepare & create release (push) Blocked by required conditions
Build and Release / Publish release (push) Blocked by required conditions
Build and Release / Build app (${{ matrix.dotnet_runtime }}) (-aarch64-pc-windows-msvc.exe, win-arm64, windows-latest, aarch64-pc-windows-msvc, nsis updater) (push) Blocked by required conditions
2025-05-01 12:54:04 +02:00
132 changed files with 6424 additions and 843 deletions

No files matched your search

+127
View File
@@ -167,6 +167,12 @@ jobs:
sed -i '' "10s/.*/${{ matrix.dotnet_runtime }}/" metadata.txt
fi
# Next line is the necessary PDFium version.
# The format is '137.0.7123.0'. What we need
# is the '7123' part:
pdfium_version=$(sed -n '11p' metadata.txt)
pdfium_version=$(echo $pdfium_version | cut -d'.' -f3)
# Write the metadata to the environment:
echo "APP_VERSION=${app_version}" >> $GITHUB_ENV
echo "FORMATTED_APP_VERSION=${formatted_app_version}" >> $GITHUB_ENV
@@ -178,6 +184,7 @@ jobs:
echo "MUD_BLAZOR_VERSION=${mud_blazor_version}" >> $GITHUB_ENV
echo "TAURI_VERSION=${tauri_version}" >> $GITHUB_ENV
echo "ARCHITECTURE=${{ matrix.dotnet_runtime }}" >> $GITHUB_ENV
echo "PDFIUM_VERSION=${pdfium_version}" >> $GITHUB_ENV
# Log the metadata:
echo "App version: '${formatted_app_version}'"
@@ -189,6 +196,7 @@ jobs:
echo "MudBlazor version: '${mud_blazor_version}'"
echo "Tauri version: '${tauri_version}'"
echo "Architecture: '${{ matrix.dotnet_runtime }}'"
echo "PDFium version: '${pdfium_version}'"
- name: Read and format metadata (Windows)
if: matrix.platform == 'windows-latest'
@@ -227,6 +235,12 @@ jobs:
# Write the changed metadata back to the file:
Set-Content -Path metadata.txt -Value $metadata
# Next line is the necessary PDFium version.
# The format is '137.0.7123.0'. What we need
# is the '7123' part:
$pdfium_version = $metadata[10]
$pdfium_version = $pdfium_version.Split('.')[2]
# Write the metadata to the environment:
Write-Output "APP_VERSION=${app_version}" >> $env:GITHUB_ENV
Write-Output "FORMATTED_APP_VERSION=${formatted_app_version}" >> $env:GITHUB_ENV
@@ -237,6 +251,7 @@ jobs:
Write-Output "RUST_VERSION=${rust_version}" >> $env:GITHUB_ENV
Write-Output "MUD_BLAZOR_VERSION=${mud_blazor_version}" >> $env:GITHUB_ENV
Write-Output "ARCHITECTURE=${{ matrix.dotnet_runtime }}" >> $env:GITHUB_ENV
Write-Output "PDFIUM_VERSION=${pdfium_version}" >> $env:GITHUB_ENV
# Log the metadata:
Write-Output "App version: '${formatted_app_version}'"
@@ -248,6 +263,7 @@ jobs:
Write-Output "MudBlazor version: '${mud_blazor_version}'"
Write-Output "Tauri version: '${tauri_version}'"
Write-Output "Architecture: '${{ matrix.dotnet_runtime }}'"
Write-Output "PDFium version: '${pdfium_version}'"
- name: Setup .NET
uses: actions/setup-dotnet@v4
@@ -255,6 +271,117 @@ jobs:
dotnet-version: ${{ env.DOTNET_SDK_VERSION }}
cache: true
cache-dependency-path: 'app/MindWork AI Studio/packages.lock.json'
- name: Deploy PDFium (Unix)
if: matrix.platform != 'windows-latest'
env:
PDFIUM_VERSION: ${{ env.PDFIUM_VERSION }}
DOTNET_RUNTIME: ${{ matrix.dotnet_runtime }}
run: |
set -e
# Target directory:
TLIB_DIR="runtime/resources/libraries"
mkdir -p "$TLIB_DIR"
case "${DOTNET_RUNTIME}" in
linux-x64)
PDFIUM_FILE="linux-x64.tgz"
LIB_SOURCE="lib/libpdfium.so"
LIB_TARGET="libpdfium.so"
;;
linux-arm64)
PDFIUM_FILE="linux-arm64.tgz"
LIB_SOURCE="lib/libpdfium.so"
LIB_TARGET="libpdfium.so"
;;
osx-x64)
PDFIUM_FILE="mac-x64.tgz"
LIB_SOURCE="lib/libpdfium.dylib"
LIB_TARGET="libpdfium.dylib"
;;
osx-arm64)
PDFIUM_FILE="mac-arm64.tgz"
LIB_SOURCE="lib/libpdfium.dylib"
LIB_TARGET="libpdfium.dylib"
;;
*)
echo "Unknown platform: ${DOTNET_RUNTIME}"
exit 1
;;
esac
PDFIUM_URL="https://github.com/bblanchon/pdfium-binaries/releases/download/chromium%2F${PDFIUM_VERSION}/pdfium-${PDFIUM_FILE}"
echo "Download PDFium $PDFIUM_URL ..."
TMP=$(mktemp -d)
ARCHIVE="${TMP}/pdfium.tgz"
curl -fsSL -o "$ARCHIVE" "$PDFIUM_URL"
echo "Extracting PDFium ..."
tar xzf "$ARCHIVE" -C "$TMP"
SRC="${TMP}/${LIB_SOURCE}"
if [ ! -f "$SRC" ]; then
echo "Was not able to find PDFium source: $SRC"
exit 1
fi
echo "Copy PDFium from ${LIB_TARGET} to ${TLIB_DIR}/"
cp -f "$SRC" "$TLIB_DIR/$LIB_TARGET"
echo "Cleaning up ..."
rm -fr "$TMP"
- name: Install PDFium (Windows)
if: matrix.platform == 'windows-latest'
env:
PDFIUM_VERSION: ${{ env.PDFIUM_VERSION }}
DOTNET_RUNTIME: ${{ matrix.dotnet_runtime }}
run: |
$TLIB_DIR = "runtime\resources\libraries"
New-Item -ItemType Directory -Force -Path $TLIB_DIR | Out-Null
switch ($env:DOTNET_RUNTIME) {
"win-x64" {
$PDFIUM_FILE = "win-x64.tgz"
$LIB_SOURCE = "bin\pdfium.dll"
$LIB_TARGET = "pdfium.dll"
}
"win-arm64" {
$PDFIUM_FILE = "win-arm64.tgz"
$LIB_SOURCE = "bin\pdfium.dll"
$LIB_TARGET = "pdfium.dll"
}
default {
Write-Error "Unknown platform: $($env:DOTNET_RUNTIME)"
exit 1
}
}
$PDFIUM_URL = "https://github.com/bblanchon/pdfium-binaries/releases/download/chromium%2F$($env:PDFIUM_VERSION)/pdfium-$PDFIUM_FILE"
Write-Host "Download $PDFIUM_URL ..."
$TMP = New-TemporaryFile | Split-Path
$ARCHIVE = Join-Path $TMP "pdfium.tgz"
Invoke-WebRequest -Uri $PDFIUM_URL -OutFile $ARCHIVE
Write-Host "Extracting PDFium ..."
tar -xzf $ARCHIVE -C $TMP
$SRC = Join-Path $TMP $LIB_SOURCE
if (!(Test-Path $SRC)) {
Write-Error "Cannot find PDFium source: $SRC"
exit 1
}
$DEST = Join-Path $TLIB_DIR $LIB_TARGET
Copy-Item -Path $SRC -Destination $DEST -Force
Write-Host "Cleaning up ..."
Remove-Item $ARCHIVE -Force
Remove-Item $TMP -Recurse -Force
- name: Build .NET project
run: |
+5
View File
@@ -1,3 +1,8 @@
# Ignore pdfium library:
libpdfium.dylib
libpdfium.so
libpdfium.dll
# User-specific files
*.rsuser
*.suo
+2 -2
View File
@@ -31,9 +31,9 @@ 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))~~
- [ ] 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))~~
- [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))
- [ ] 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)~~)
- [ ] Add configuration plugins, which allow pre-defining some LLM providers in organizations
- [ ] 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
+5
View File
@@ -17,5 +17,10 @@ public sealed class CheckRidsCommand
{
Console.WriteLine($"- {rid}");
}
Console.WriteLine();
Console.WriteLine("The RID for the current OS and CPU is:");
var currentRid = Environment.GetCurrentRid();
Console.WriteLine($"- {currentRid}");
}
}
+37 -28
View File
@@ -10,6 +10,29 @@ namespace Build.Commands;
public sealed partial class CollectI18NKeysCommand
{
private const string START_TAG1 = """
T("
""";
private const string START_TAG2 = """
TB("
""";
private const string START_TAG3 = """
T(@"
""";
private const string END_TAG = """
")
""";
private static readonly (string Tag, int Length)[] START_TAGS =
[
(START_TAG1, START_TAG1.Length),
(START_TAG2, START_TAG2.Length),
(START_TAG3, START_TAG3.Length)
];
[Command("collect-i18n", Description = "Collect I18N keys")]
public async Task CollectI18NKeys()
{
@@ -133,36 +156,22 @@ public sealed partial class CollectI18NKeysCommand
private List<string> FindAllTextTags(ReadOnlySpan<char> fileContent)
{
const string START_TAG1 = """
T("
""";
const string START_TAG2 = """
TB("
""";
const string END_TAG = """
")
""";
(int Index, int Len) FindNextStart(ReadOnlySpan<char> content)
{
var startIdx1 = content.IndexOf(START_TAG1);
var startIdx2 = content.IndexOf(START_TAG2);
if (startIdx1 == -1 && startIdx2 == -1)
return (-1, 0);
if (startIdx1 == -1)
return (startIdx2, START_TAG2.Length);
if (startIdx2 == -1)
return (startIdx1, START_TAG1.Length);
if (startIdx1 < startIdx2)
return (startIdx1, START_TAG1.Length);
return (startIdx2, START_TAG2.Length);
var bestIndex = -1;
var bestLength = 0;
foreach (var (tag, length) in START_TAGS)
{
var index = content.IndexOf(tag);
if (index != -1 && (bestIndex == -1 || index < bestIndex))
{
bestIndex = index;
bestLength = length;
}
}
return (bestIndex, bestLength);
}
var matches = new List<string>();
+3
View File
@@ -0,0 +1,3 @@
namespace Build.Commands;
public record Library(string Path, string Filename);
+107
View File
@@ -0,0 +1,107 @@
using System.Formats.Tar;
using System.IO.Compression;
using SharedTools;
namespace Build.Commands;
public static class Pdfium
{
public static async Task InstallAsync(RID rid, string version)
{
Console.Write($"- Installing Pdfium {version} for {rid.ToUserFriendlyName()} ...");
var cwd = Environment.GetRustRuntimeDirectory();
var pdfiumTmpDownloadPath = Path.GetTempFileName();
var pdfiumTmpExtractPath = Directory.CreateTempSubdirectory();
var pdfiumUrl = GetPdfiumDownloadUrl(rid, version);
//
// Download the file:
//
Console.Write(" downloading ...");
using (var client = new HttpClient())
{
var response = await client.GetAsync(pdfiumUrl);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($" failed to download Pdfium {version} for {rid.ToUserFriendlyName()} from {pdfiumUrl}");
return;
}
await using var fileStream = File.Create(pdfiumTmpDownloadPath);
await response.Content.CopyToAsync(fileStream);
}
//
// Extract the downloaded file:
//
Console.Write(" extracting ...");
await using(var tgzStream = File.Open(pdfiumTmpDownloadPath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
await using var uncompressedStream = new GZipStream(tgzStream, CompressionMode.Decompress);
await TarFile.ExtractToDirectoryAsync(uncompressedStream, pdfiumTmpExtractPath.FullName, true);
}
//
// Copy the library to the target directory:
//
Console.Write(" deploying ...");
var library = GetLibraryPath(rid);
if (string.IsNullOrEmpty(library.Path))
{
Console.WriteLine($" failed to find the library path for {rid.ToUserFriendlyName()}");
return;
}
var pdfiumLibSourcePath = Path.Join(pdfiumTmpExtractPath.FullName, library.Path);
var pdfiumLibTargetPath = Path.Join(cwd, "resources", "libraries", library.Filename);
if (!File.Exists(pdfiumLibSourcePath))
{
Console.WriteLine($" failed to find the library file '{pdfiumLibSourcePath}'");
return;
}
Directory.CreateDirectory(Path.Join(cwd, "resources", "libraries"));
if (File.Exists(pdfiumLibTargetPath))
File.Delete(pdfiumLibTargetPath);
File.Copy(pdfiumLibSourcePath, pdfiumLibTargetPath);
//
// Cleanup:
//
Console.Write(" cleaning up ...");
File.Delete(pdfiumTmpDownloadPath);
Directory.Delete(pdfiumTmpExtractPath.FullName, true);
Console.WriteLine(" done.");
}
private static Library GetLibraryPath(RID rid) => rid switch
{
RID.LINUX_ARM64 or RID.LINUX_X64 => new(Path.Join("lib", "libpdfium.so"), "libpdfium.so"),
RID.OSX_ARM64 or RID.OSX_X64 => new(Path.Join("lib", "libpdfium.dylib"), "libpdfium.dylib"),
RID.WIN_ARM64 or RID.WIN_X64 => new(Path.Join("bin", "pdfium.dll"), "pdfium.dll"),
_ => new(string.Empty, string.Empty),
};
private static string GetPdfiumDownloadUrl(RID rid, string version)
{
var baseUrl = $"https://github.com/bblanchon/pdfium-binaries/releases/download/chromium%2F{version}/pdfium-";
return rid switch
{
RID.LINUX_ARM64 => $"{baseUrl}linux-arm64.tgz",
RID.LINUX_X64 => $"{baseUrl}linux-x64.tgz",
RID.OSX_ARM64 => $"{baseUrl}mac-arm64.tgz",
RID.OSX_X64 => $"{baseUrl}mac-x64.tgz",
RID.WIN_ARM64 => $"{baseUrl}win-arm64.tgz",
RID.WIN_X64 => $"{baseUrl}win-x64.tgz",
_ => string.Empty,
};
}
}
+99 -90
View File
@@ -105,105 +105,102 @@ public sealed partial class UpdateMetadataCommands
// Build the .NET project:
//
var pathApp = Environment.GetAIStudioDirectory();
var rids = Environment.GetRidsForCurrentOS();
foreach (var rid in rids)
{
Console.WriteLine("==============================");
await this.UpdateArchitecture(rid);
Console.Write($"- Start .NET build for '{rid.AsMicrosoftRid()}' ...");
await this.ReadCommandOutput(pathApp, "dotnet", $"clean --configuration release --runtime {rid.AsMicrosoftRid()}");
var dotnetBuildOutput = await this.ReadCommandOutput(pathApp, "dotnet", $"publish --configuration release --runtime {rid.AsMicrosoftRid()} --disable-build-servers --force");
var dotnetBuildOutputLines = dotnetBuildOutput.Split([global::System.Environment.NewLine], StringSplitOptions.RemoveEmptyEntries);
var foundIssue = false;
foreach (var buildOutputLine in dotnetBuildOutputLines)
{
if(buildOutputLine.Contains(" error ") || buildOutputLine.Contains("#warning"))
{
if(!foundIssue)
{
foundIssue = true;
Console.WriteLine();
Console.WriteLine("- Build has issues:");
}
Console.Write(" - ");
Console.WriteLine(buildOutputLine);
}
}
if(foundIssue)
Console.WriteLine();
else
{
Console.WriteLine(" completed successfully.");
}
//
// Prepare the .NET artifact to be used by Tauri as sidecar:
//
var os = Environment.GetOS();
var tauriSidecarArtifactName = rid switch
{
RID.WIN_X64 => "mindworkAIStudioServer-x86_64-pc-windows-msvc.exe",
RID.WIN_ARM64 => "mindworkAIStudioServer-aarch64-pc-windows-msvc.exe",
RID.LINUX_X64 => "mindworkAIStudioServer-x86_64-unknown-linux-gnu",
RID.LINUX_ARM64 => "mindworkAIStudioServer-aarch64-unknown-linux-gnu",
RID.OSX_ARM64 => "mindworkAIStudioServer-aarch64-apple-darwin",
RID.OSX_X64 => "mindworkAIStudioServer-x86_64-apple-darwin",
_ => string.Empty,
};
if (string.IsNullOrWhiteSpace(tauriSidecarArtifactName))
{
Console.WriteLine($"- Error: Unsupported rid '{rid.AsMicrosoftRid()}'.");
return;
}
var rid = Environment.GetCurrentRid();
var dotnetArtifactPath = Path.Combine(pathApp, "bin", "dist");
if(!Directory.Exists(dotnetArtifactPath))
Directory.CreateDirectory(dotnetArtifactPath);
var dotnetArtifactFilename = os switch
Console.WriteLine("==============================");
await this.UpdateArchitecture(rid);
var pdfiumVersion = await this.ReadPdfiumVersion();
await Pdfium.InstallAsync(rid, pdfiumVersion);
Console.Write($"- Start .NET build for {rid.ToUserFriendlyName()} ...");
await this.ReadCommandOutput(pathApp, "dotnet", $"clean --configuration release --runtime {rid.AsMicrosoftRid()}");
var dotnetBuildOutput = await this.ReadCommandOutput(pathApp, "dotnet", $"publish --configuration release --runtime {rid.AsMicrosoftRid()} --disable-build-servers --force");
var dotnetBuildOutputLines = dotnetBuildOutput.Split([global::System.Environment.NewLine], StringSplitOptions.RemoveEmptyEntries);
var foundIssue = false;
foreach (var buildOutputLine in dotnetBuildOutputLines)
{
if(buildOutputLine.Contains(" error ") || buildOutputLine.Contains("#warning"))
{
"windows" => "mindworkAIStudio.exe",
_ => "mindworkAIStudio",
};
var dotnetPublishedPath = Path.Combine(pathApp, "bin", "release", Environment.DOTNET_VERSION, rid.AsMicrosoftRid(), "publish", dotnetArtifactFilename);
var finalDestination = Path.Combine(dotnetArtifactPath, tauriSidecarArtifactName);
if(File.Exists(dotnetPublishedPath))
Console.WriteLine("- Published .NET artifact found.");
else
{
Console.WriteLine($"- Error: Published .NET artifact not found: '{dotnetPublishedPath}'.");
return;
}
if(!foundIssue)
{
foundIssue = true;
Console.WriteLine();
Console.WriteLine("- Build has issues:");
}
Console.Write($"- Move the .NET artifact to the Tauri sidecar destination ...");
try
{
File.Move(dotnetPublishedPath, finalDestination, true);
Console.WriteLine(" done.");
Console.Write(" - ");
Console.WriteLine(buildOutputLine);
}
catch (Exception e)
{
Console.WriteLine(" failed.");
Console.WriteLine($" - Error: {e.Message}");
}
}
if(foundIssue)
Console.WriteLine();
else
{
Console.WriteLine(" completed successfully.");
}
//
// Prepare the .NET artifact to be used by Tauri as sidecar:
//
var os = Environment.GetOS();
var tauriSidecarArtifactName = rid switch
{
RID.WIN_X64 => "mindworkAIStudioServer-x86_64-pc-windows-msvc.exe",
RID.WIN_ARM64 => "mindworkAIStudioServer-aarch64-pc-windows-msvc.exe",
RID.LINUX_X64 => "mindworkAIStudioServer-x86_64-unknown-linux-gnu",
RID.LINUX_ARM64 => "mindworkAIStudioServer-aarch64-unknown-linux-gnu",
RID.OSX_ARM64 => "mindworkAIStudioServer-aarch64-apple-darwin",
RID.OSX_X64 => "mindworkAIStudioServer-x86_64-apple-darwin",
_ => string.Empty,
};
if (string.IsNullOrWhiteSpace(tauriSidecarArtifactName))
{
Console.WriteLine($"- Error: Unsupported rid '{rid.AsMicrosoftRid()}'.");
return;
}
var dotnetArtifactPath = Path.Combine(pathApp, "bin", "dist");
if(!Directory.Exists(dotnetArtifactPath))
Directory.CreateDirectory(dotnetArtifactPath);
var dotnetArtifactFilename = os switch
{
"windows" => "mindworkAIStudio.exe",
_ => "mindworkAIStudio",
};
var dotnetPublishedPath = Path.Combine(pathApp, "bin", "release", Environment.DOTNET_VERSION, rid.AsMicrosoftRid(), "publish", dotnetArtifactFilename);
var finalDestination = Path.Combine(dotnetArtifactPath, tauriSidecarArtifactName);
if(File.Exists(dotnetPublishedPath))
Console.WriteLine("- Published .NET artifact found.");
else
{
Console.WriteLine($"- Error: Published .NET artifact not found: '{dotnetPublishedPath}'.");
return;
}
Console.Write($"- Move the .NET artifact to the Tauri sidecar destination ...");
try
{
File.Move(dotnetPublishedPath, finalDestination, true);
Console.WriteLine(" done.");
}
catch (Exception e)
{
Console.WriteLine(" failed.");
Console.WriteLine($" - Error: {e.Message}");
}
//
// Build the Rust project / runtime:
//
Console.WriteLine("==============================");
Console.WriteLine("- Start building the Rust runtime ...");
var pathRuntime = Environment.GetRustRuntimeDirectory();
@@ -314,6 +311,18 @@ public sealed partial class UpdateMetadataCommands
await File.WriteAllTextAsync(changelogCodePath, changelogCode, Environment.UTF8_NO_BOM);
Console.WriteLine(" done.");
}
private async Task<string> ReadPdfiumVersion()
{
const int PDFIUM_VERSION_INDEX = 10;
var pathMetadata = Environment.GetMetadataPath();
var lines = await File.ReadAllLinesAsync(pathMetadata, Encoding.UTF8);
var currentPdfiumVersion = lines[PDFIUM_VERSION_INDEX].Trim();
var shortVersion = currentPdfiumVersion.Split('.')[2];
return shortVersion;
}
private async Task UpdateArchitecture(RID rid)
{
@@ -321,7 +330,7 @@ public sealed partial class UpdateMetadataCommands
var pathMetadata = Environment.GetMetadataPath();
var lines = await File.ReadAllLinesAsync(pathMetadata, Encoding.UTF8);
Console.Write("- Updating architecture ...");
Console.Write($"- Updating architecture to {rid.ToUserFriendlyName()} ...");
lines[ARCHITECTURE_INDEX] = rid.AsMicrosoftRid();
await File.WriteAllLinesAsync(pathMetadata, lines, Environment.UTF8_NO_BOM);
+1 -1
View File
@@ -17,7 +17,7 @@ public sealed class UpdateWebAssetsCommand
Console.WriteLine("=========================");
Console.Write("- Updating web assets ...");
var rid = Environment.GetRidsForCurrentOS().First();
var rid = Environment.GetCurrentRid();
var cwd = Environment.GetAIStudioDirectory();
var contentPath = Path.Join(cwd, "bin", "release", Environment.DOTNET_VERSION, rid.AsMicrosoftRid(), "publish", "wwwroot", "_content");
var isMudBlazorDirectoryPresent = Directory.Exists(Path.Join(contentPath, "MudBlazor"));
+34
View File
@@ -76,4 +76,38 @@ public static class Environment
Console.WriteLine($"Error: Unsupported OS '{RuntimeInformation.OSDescription}'");
return [];
}
public static RID GetCurrentRid()
{
var arch = RuntimeInformation.ProcessArchitecture;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
return arch switch
{
Architecture.X64 => RID.WIN_X64,
Architecture.Arm64 => RID.WIN_ARM64,
_ => RID.NONE,
};
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return arch switch
{
Architecture.X64 => RID.OSX_X64,
Architecture.Arm64 => RID.OSX_ARM64,
_ => RID.NONE,
};
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
return arch switch
{
Architecture.X64 => RID.LINUX_X64,
Architecture.Arm64 => RID.LINUX_ARM64,
_ => RID.NONE,
};
Console.WriteLine($"Error: Unsupported OS '{RuntimeInformation.OSDescription}'");
return RID.NONE;
}
}
+1
View File
@@ -9,6 +9,7 @@
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=LM/@EntryIndexedValue">LM</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=MSG/@EntryIndexedValue">MSG</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=OS/@EntryIndexedValue">OS</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=PDF/@EntryIndexedValue">PDF</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=RAG/@EntryIndexedValue">RAG</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=RID/@EntryIndexedValue">RID</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=TB/@EntryIndexedValue">TB</s:String>
@@ -1,10 +1,10 @@
@attribute [Route(Routes.ASSISTANT_AGENDA)]
@inherits AssistantBaseCore<AIStudio.Dialogs.Settings.SettingsDialogAgenda>
<MudTextField T="string" @bind-Text="@this.inputName" Validation="@this.ValidateName" Label="Meeting Name" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Tag" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Name the meeting, seminar, etc." Placeholder="Weekly jour fixe" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputTopic" Validation="@this.ValidateTopic" Label="Topic" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.EventNote" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Describe the topic of the meeting, seminar, etc. Is it about quantum computing, software engineering, or is it a general business meeting?" Placeholder="Project meeting" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputContent" Validation="@this.ValidateContent" Label="Content list" Variant="Variant.Outlined" Lines="6" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Bullet list the content of the meeting, seminar, etc. roughly. Use dashes (-) to separate the items." Placeholder="@PLACEHOLDER_CONTENT" Class="mb-3" Immediate="@false" DebounceInterval="1_000" OnDebounceIntervalElapsed="@this.OnContentChanged" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.ListAlt"/>
<MudSelect T="string" Label="(Optional) What topics should be the focus?" MultiSelection="@true" @bind-SelectedValues="@this.selectedFoci" Variant="Variant.Outlined" Class="mb-3" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.ListAlt">
<MudTextField T="string" @bind-Text="@this.inputName" Validation="@this.ValidateName" Label="@T("Meeting Name")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Tag" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@T("Name the meeting, seminar, etc.")" Placeholder="@T("Weekly jour fixe")" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputTopic" Validation="@this.ValidateTopic" Label="@T("Topic")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.EventNote" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@T("Describe the topic of the meeting, seminar, etc. Is it about quantum computing, software engineering, or is it a general business meeting?")" Placeholder="@T("Project meeting")" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputContent" Validation="@this.ValidateContent" Label="@T("Content list")" Variant="Variant.Outlined" Lines="6" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@T("Bullet list the content of the meeting, seminar, etc. roughly. Use dashes (-) to separate the items.")" Placeholder="@PLACEHOLDER_CONTENT" Class="mb-3" Immediate="@false" DebounceInterval="1_000" OnDebounceIntervalElapsed="@this.OnContentChanged" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.ListAlt"/>
<MudSelect T="string" Label="@T("(Optional) What topics should be the focus?")" MultiSelection="@true" @bind-SelectedValues="@this.selectedFoci" Variant="Variant.Outlined" Class="mb-3" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.ListAlt">
@foreach (var contentLine in this.contentLines)
{
@if(!this.justBriefly.Contains(contentLine))
@@ -14,7 +14,7 @@
}
</MudSelect>
<MudSelect T="string" Label="(Optional) What topics should only be briefly addressed?" MultiSelection="@true" @bind-SelectedValues="@this.justBriefly" Variant="Variant.Outlined" Class="mb-3" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.ListAlt">
<MudSelect T="string" Label="@T("(Optional) What topics should only be briefly addressed?")" MultiSelection="@true" @bind-SelectedValues="@this.justBriefly" Variant="Variant.Outlined" Class="mb-3" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.ListAlt">
@foreach (var contentLine in this.contentLines)
{
@if(!this.selectedFoci.Contains(contentLine))
@@ -24,28 +24,28 @@
}
</MudSelect>
<MudTextField T="string" @bind-Text="@this.inputObjective" Validation="@this.ValidateObjective" Label="Objective" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Flag" Variant="Variant.Outlined" Lines="3" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Describe the objective(s) of the meeting, seminar, etc. What should be achieved?" Placeholder="Discuss the current project status and plan the next steps." Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputModerator" Validation="@this.ValidateModerator" Label="Moderator" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Person3" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Who will moderate the meeting, seminar, etc.?" Placeholder="Jane Doe" Class="mb-3" />
<MudTextField T="string" @bind-Text="@this.inputDuration" Validation="@this.ValidateDuration" Label="Duration" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Schedule" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="How long will the meeting, seminar, etc. last? E.g., '2 hours', or '2 days (first day 8 hours, then 4 hours)', etc." Placeholder="2 hours" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputStartTime" Validation="@this.ValidateStartTime" Label="Start time" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Schedule" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="When will the meeting, seminar, etc. start? E.g., '9:00 AM', or '9:00 AM (CET)', etc. When the meeting is a multi-day event, specify the start time for each day." Placeholder="9:00 AM" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputWhoIsPresenting" Label="(Optional) Who is presenting?" Variant="Variant.Outlined" Lines="6" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="(Optional) List the persons who will present at the meeting, seminar, etc. Use dashes (-) to separate the items." Placeholder="@PLACEHOLDER_WHO_IS_PRESENTING" Class="mb-3"/>
<MudTextSwitch Label="Do the participants need to get to know each other first?" @bind-Value="@this.introduceParticipants" LabelOn="Yes, introduce participants" LabelOff="No, participants know each other" />
<EnumSelection T="NumberParticipants" @bind-Value="@this.numberParticipants" NameFunc="@(participants => participants.Name())" Icon="@Icons.Material.Filled.Group" Label="Number of participants" ValidateSelection="@this.ValidateNumberParticipants"/>
<MudTextSwitch Label="Should the participants be involved passively or actively?" @bind-Value="@this.activeParticipation" LabelOn="Active participation, like world café, discussions, etc." LabelOff="Passive participation, like presentations, lectures, etc." />
<MudTextSwitch Label="Is this a virtual event, e.g., a call or webinar?" @bind-Value="@this.isMeetingVirtual" LabelOn="Yes, this is a virtual event" LabelOff="No, this is a physical event" />
<MudTextField T="string" @bind-Text="@this.inputObjective" Validation="@this.ValidateObjective" Label="@T("Objective")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Flag" Variant="Variant.Outlined" Lines="3" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@T("Describe the objective(s) of the meeting, seminar, etc. What should be achieved?")" Placeholder="@T("Discuss the current project status and plan the next steps.")" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputModerator" Validation="@this.ValidateModerator" Label="@T("Moderator")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Person3" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@T("Who will moderate the meeting, seminar, etc.?")" Placeholder="Jane Doe" Class="mb-3" />
<MudTextField T="string" @bind-Text="@this.inputDuration" Validation="@this.ValidateDuration" Label="@T("Duration")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Schedule" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@T("How long will the meeting, seminar, etc. last? E.g., '2 hours', or '2 days (first day 8 hours, then 4 hours)', etc.")" Placeholder="@T("2 hours")" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputStartTime" Validation="@this.ValidateStartTime" Label="Start time" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Schedule" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@T("When will the meeting, seminar, etc. start? E.g., '9:00 AM', or '9:00 AM (CET)', etc. When the meeting is a multi-day event, specify the start time for each day.")" Placeholder="@T("9:00 AM")" Class="mb-3"/>
<MudTextField T="string" @bind-Text="@this.inputWhoIsPresenting" Label="@T("(Optional) Who is presenting?")" Variant="Variant.Outlined" Lines="6" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@T("(Optional) List the persons who will present at the meeting, seminar, etc. Use dashes (-) to separate the items.")" Placeholder="@PLACEHOLDER_WHO_IS_PRESENTING" Class="mb-3"/>
<MudTextSwitch Label="@T("Do the participants need to get to know each other first?")" @bind-Value="@this.introduceParticipants" LabelOn="@T("Yes, introduce participants")" LabelOff="@T("No, participants know each other")" />
<EnumSelection T="NumberParticipants" @bind-Value="@this.numberParticipants" NameFunc="@(participants => participants.Name())" Icon="@Icons.Material.Filled.Group" Label="@T("Number of participants")" ValidateSelection="@this.ValidateNumberParticipants"/>
<MudTextSwitch Label="@T("Should the participants be involved passively or actively?")" @bind-Value="@this.activeParticipation" LabelOn="@T("Active participation, like world café, discussions, etc.")" LabelOff="@T("Passive participation, like presentations, lectures, etc.")" />
<MudTextSwitch Label="@T("Is this a virtual event, e.g., a call or webinar?")" @bind-Value="@this.isMeetingVirtual" LabelOn="@T("Yes, this is a virtual event")" LabelOff="@T("No, this is a physical event")" />
@if (!this.isMeetingVirtual)
{
<MudPaper Class="pa-3 mb-8 border-dashed border rounded-lg">
<MudTextField T="string" @bind-Text="@this.inputLocation" Validation="@this.ValidateLocation" Label="Location" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.MyLocation" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="Where will the meeting, seminar, etc. take place?" Placeholder="Hamburg, Germany" Class="mb-3"/>
<MudTextSwitch Label="Should there be a joint dinner?" @bind-Value="@this.goingToDinner" LabelOn="Yes, there should be a joint dinner" LabelOff="No, there should be no joint dinner" />
<MudTextSwitch Label="Should there be a social activity?" @bind-Value="@this.doingSocialActivity" LabelOn="Yes, there should be a social activity" LabelOff="No, there should be no social activity" />
<MudTextSwitch Label="Do participants need to arrive and depart?" @bind-Value="@this.needToArriveAndDepart" LabelOn="Yes, participants need to arrive and depart" LabelOff="No, participants do not need to arrive and depart" />
<MudTextField T="string" @bind-Text="@this.inputLocation" Validation="@this.ValidateLocation" Label="@T("Location")" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.MyLocation" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@T("Where will the meeting, seminar, etc. take place?")" Placeholder="@T("Hamburg, Germany")" Class="mb-3"/>
<MudTextSwitch Label="@T("Should there be a joint dinner?")" @bind-Value="@this.goingToDinner" LabelOn="@T("Yes, there should be a joint dinner")" LabelOff="@T("No, there should be no joint dinner")" />
<MudTextSwitch Label="@T("Should there be a social activity?")" @bind-Value="@this.doingSocialActivity" LabelOn="@T("Yes, there should be a social activity")" LabelOff="@T("No, there should be no social activity")" />
<MudTextSwitch Label="@T("Do participants need to arrive and depart?")" @bind-Value="@this.needToArriveAndDepart" LabelOn="@T("Yes, participants need to arrive and depart")" LabelOff="@T("No, participants do not need to arrive and depart")" />
<MudStack Row="@true" Wrap="Wrap.Wrap">
<MudTextSlider T="int" Label="Approx. duration of the lunch break" @bind-Value="@this.durationLunchBreak" Min="30" Max="120" Step="5" Unit="minutes"/>
<MudTextSlider T="int" Label="Approx. duration of the coffee or tea breaks" @bind-Value="@this.durationBreaks" Min="10" Max="60" Step="5" Unit="minutes"/>
<MudTextSlider T="int" Label="@T("Approx. duration of the lunch break")" @bind-Value="@this.durationLunchBreak" Min="30" Max="120" Step="5" Unit="@T("minutes")"/>
<MudTextSlider T="int" Label="@T("Approx. duration of the coffee or tea breaks")" @bind-Value="@this.durationBreaks" Min="10" Max="60" Step="5" Unit="@T("minutes")"/>
</MudStack>
</MudPaper>
}
<EnumSelection T="CommonLanguages" NameFunc="@(language => language.NameSelecting())" @bind-Value="@this.selectedTargetLanguage" ValidateSelection="@this.ValidateTargetLanguage" 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.NameSelecting())" @bind-Value="@this.selectedTargetLanguage" ValidateSelection="@this.ValidateTargetLanguage" 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"/>
@@ -9,14 +9,14 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
{
public override Tools.Components Component => Tools.Components.AGENDA_ASSISTANT;
protected override string Title => "Agenda Planner";
protected override string Title => T("Agenda Planner");
protected override string Description =>
"""
This agenda planner helps you create a structured agenda for your meeting or seminar. Just provide some basic
information about the event, and the assistant will generate an agenda for you. You can also specify the
duration, the start time, the location, the target language, and other details.
""";
T("""
This agenda planner helps you create a structured agenda for your meeting or seminar. Just provide some basic
information about the event, and the assistant will generate an agenda for you. You can also specify the
duration, the start time, the location, the target language, and other details.
""");
protected override string SystemPrompt =>
$"""
@@ -98,7 +98,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
protected override IReadOnlyList<IButtonData> FooterButtons => [];
protected override string SubmitText => "Create Agenda";
protected override string SubmitText => T("Create Agenda");
protected override Func<Task> SubmitAction => this.CreateAgenda;
@@ -235,7 +235,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateLocation(string location)
{
if(!this.isMeetingVirtual && string.IsNullOrWhiteSpace(location))
return "Please provide a location for the meeting or the seminar.";
return T("Please provide a location for the meeting or the seminar.");
return null;
}
@@ -243,7 +243,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateNumberParticipants(NumberParticipants selectedSize)
{
if(selectedSize is NumberParticipants.NOT_SPECIFIED)
return "Please select the number of participants.";
return T("Please select the number of participants.");
return null;
}
@@ -251,7 +251,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateTargetLanguage(CommonLanguages language)
{
if(language is CommonLanguages.AS_IS)
return "Please select a target language for the agenda.";
return T("Please select a target language for the agenda.");
return null;
}
@@ -259,7 +259,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateDuration(string duration)
{
if(string.IsNullOrWhiteSpace(duration))
return "Please provide a duration for the meeting or the seminar, e.g. '2 hours', or '2 days (8 hours and 4 hours)', etc.";
return T("Please provide a duration for the meeting or the seminar, e.g. '2 hours', or '2 days (8 hours and 4 hours)', etc.");
return null;
}
@@ -267,7 +267,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateStartTime(string startTime)
{
if(string.IsNullOrWhiteSpace(startTime))
return "Please provide a start time for the meeting or the seminar. When the meeting is a multi-day event, specify the start time for each day, e.g. '9:00 AM, 10:00 AM', etc.";
return T("Please provide a start time for the meeting or the seminar. When the meeting is a multi-day event, specify the start time for each day, e.g. '9:00 AM, 10:00 AM', etc.");
return null;
}
@@ -275,7 +275,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
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;
}
@@ -283,7 +283,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateTopic(string topic)
{
if(string.IsNullOrWhiteSpace(topic))
return "Please provide a topic for the agenda. What is the meeting or the seminar about?";
return T("Please provide a topic for the agenda. What is the meeting or the seminar about?");
return null;
}
@@ -291,7 +291,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateName(string name)
{
if(string.IsNullOrWhiteSpace(name))
return "Please provide a name for the meeting or the seminar.";
return T("Please provide a name for the meeting or the seminar.");
return null;
}
@@ -299,12 +299,12 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateContent(string content)
{
if(string.IsNullOrWhiteSpace(content))
return "Please provide some content for the agenda. What are the main points of the meeting or the seminar?";
return T("Please provide some content for the agenda. What are the main points of the meeting or the seminar?");
var lines = content.Split('\n', StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
if(!line.TrimStart().StartsWith('-'))
return "Please start each line of your content list with a dash (-) to create a bullet point list.";
return T("Please start each line of your content list with a dash (-) to create a bullet point list.");
return null;
}
@@ -312,7 +312,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateObjective(string objective)
{
if(string.IsNullOrWhiteSpace(objective))
return "Please provide an objective for the meeting or the seminar. What do you want to achieve?";
return T("Please provide an objective for the meeting or the seminar. What do you want to achieve?");
return null;
}
@@ -320,7 +320,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateModerator(string moderator)
{
if(string.IsNullOrWhiteSpace(moderator))
return "Please provide a moderator for the meeting or the seminar. Who will lead the discussion?";
return T("Please provide a moderator for the meeting or the seminar. Who will lead the discussion?");
return null;
}
@@ -5,10 +5,10 @@
<b>Links:</b>
</MudText>
<MudList T="string" Class="mb-6">
<MudListItem T="string" Icon="@Icons.Material.Filled.Link" Target="_blank" Href="https://en.wikipedia.org/wiki/List_of_cognitive_biases">Wikipedia list of cognitive biases</MudListItem>
<MudListItem T="string" Icon="@Icons.Material.Filled.Link" Target="_blank" Href="https://commons.wikimedia.org/wiki/File:Cognitive_Bias_Codex_With_Definitions_1-2,_an_Extension_of_the_work_of_John_Manoogian_by_Brian_Rene_Morrissette.png">Extended bias poster</MudListItem>
<MudListItem T="string" Icon="@Icons.Material.Filled.Link" Target="_blank" Href="https://betterhumans.pub/cognitive-bias-cheat-sheet-55a472476b18">Blog post of Buster Benson: "Cognitive bias cheat sheet"</MudListItem>
<MudListItem T="string" Icon="@Icons.Material.Filled.Link" Target="_blank" Href="https://en.wikipedia.org/wiki/List_of_cognitive_biases">@T("Wikipedia list of cognitive biases")</MudListItem>
<MudListItem T="string" Icon="@Icons.Material.Filled.Link" Target="_blank" Href="https://commons.wikimedia.org/wiki/File:Cognitive_Bias_Codex_With_Definitions_1-2,_an_Extension_of_the_work_of_John_Manoogian_by_Brian_Rene_Morrissette.png">@T("Extended bias poster")</MudListItem>
<MudListItem T="string" Icon="@Icons.Material.Filled.Link" Target="_blank" Href="https://betterhumans.pub/cognitive-bias-cheat-sheet-55a472476b18">@T("Blog post of Buster Benson:") "Cognitive bias cheat sheet"</MudListItem>
</MudList>
<EnumSelection T="CommonLanguages" NameFunc="@(language => language.NameSelecting())" @bind-Value="@this.selectedTargetLanguage" ValidateSelection="@this.ValidateTargetLanguage" 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.NameSelecting())" @bind-Value="@this.selectedTargetLanguage" ValidateSelection="@this.ValidateTargetLanguage" 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"/>
@@ -10,18 +10,9 @@ public partial class BiasOfTheDayAssistant : AssistantBaseCore<SettingsDialogAss
{
public override Tools.Components Component => Tools.Components.BIAS_DAY_ASSISTANT;
protected override string Title => "Bias of the Day";
protected override string Title => T("Bias of the Day");
protected override string Description =>
"""
Learn about a different cognitive bias every day. You can also ask the LLM your questions. The idea behind
"Bias of the Day" is based on work by Buster Benson, John Manoogian III, and Brian Rene Morrissette. Buster
Benson grouped the biases, and the original texts come from Wikipedia. Brian Rene Morrissette condensed them
into a shorter version. Finally, John Manoogian III created the original poster based on Benson's work and
Morrissette's texts. Thorsten Sommer compared all texts for integration into AI Studio with the current Wikipedia
versions, updated them, and added source references. The idea of learning about one bias each day based on John's
poster comes from Drew Nelson.
""";
protected override string Description => T("""Learn about a different cognitive bias every day. You can also ask the LLM your questions. The idea behind "Bias of the Day" is based on work by Buster Benson, John Manoogian III, and Brian Rene Morrissette. Buster Benson grouped the biases, and the original texts come from Wikipedia. Brian Rene Morrissette condensed them into a shorter version. Finally, John Manoogian III created the original poster based on Benson's work and Morrissette's texts. Thorsten Sommer compared all texts for integration into AI Studio with the current Wikipedia versions, updated them, and added source references. The idea of learning about one bias each day based on John's poster comes from Drew Nelson.""");
protected override string SystemPrompt => $"""
You are a friendly, helpful expert on cognitive bias. You studied psychology and
@@ -41,7 +32,7 @@ public partial class BiasOfTheDayAssistant : AssistantBaseCore<SettingsDialogAss
protected override IReadOnlyList<IButtonData> FooterButtons => [];
protected override string SubmitText => "Show me the bias of the day";
protected override string SubmitText => T("Show me the bias of the day");
protected override Func<Task> SubmitAction => this.TellBias;
@@ -79,7 +70,7 @@ public partial class BiasOfTheDayAssistant : AssistantBaseCore<SettingsDialogAss
private string? ValidateTargetLanguage(CommonLanguages language)
{
if(language is CommonLanguages.AS_IS)
return "Please select a target language for the bias.";
return T("Please select a target language for the bias.");
return null;
}
@@ -87,7 +78,7 @@ public partial class BiasOfTheDayAssistant : AssistantBaseCore<SettingsDialogAss
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;
}
@@ -2,14 +2,16 @@ namespace AIStudio.Assistants.EMail;
public static class WritingStylesExtensions
{
private static string TB(string fallbackEN) => Tools.PluginSystem.I18N.I.T(fallbackEN, typeof(WritingStylesExtensions).Namespace, nameof(WritingStylesExtensions));
public static string Name(this WritingStyles style) => style switch
{
WritingStyles.ACADEMIC => "Academic",
WritingStyles.PERSONAL => "Personal",
WritingStyles.BUSINESS_FORMAL => "Business formal",
WritingStyles.BUSINESS_INFORMAL => "Business informal",
WritingStyles.ACADEMIC => TB("Academic"),
WritingStyles.PERSONAL => TB("Personal"),
WritingStyles.BUSINESS_FORMAL => TB("Business formal"),
WritingStyles.BUSINESS_INFORMAL => TB("Business informal"),
_ => "Not specified",
_ => TB("Not specified"),
};
public static string Prompt(this WritingStyles style) => style switch
@@ -182,7 +182,7 @@ public partial class AssistantI18N : AssistantBaseCore<SettingsDialogI18N>
var filePath = Path.Join(Environment.CurrentDirectory, "Assistants", "I18N");
var resourceFileProvider = new PhysicalFileProvider(filePath);
#else
var resourceFileProvider = new ManifestEmbeddedFileProvider(Assembly.GetAssembly(type: typeof(Program))!, "Assistants.I18N");
var resourceFileProvider = new ManifestEmbeddedFileProvider(Assembly.GetAssembly(type: typeof(Program))!, "Assistants/I18N");
#endif
var file = resourceFileProvider.GetFileInfo("allTexts.lua");
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,5 @@
@attribute [Route(Routes.ASSISTANT_LEGAL_CHECK)]
@using AIStudio.Settings.DataModel
@inherits AssistantBaseCore<AIStudio.Dialogs.Settings.SettingsDialogLegalCheck>
@if (!this.SettingsManager.ConfigurationData.LegalCheck.HideWebContentReader)
@@ -6,6 +7,11 @@
<ReadWebContent @bind-Content="@this.inputLegalDocument" ProviderSettings="@this.providerSettings" @bind-AgentIsRunning="@this.isAgentRunning" Preselect="@(this.SettingsManager.ConfigurationData.LegalCheck.PreselectOptions && this.SettingsManager.ConfigurationData.LegalCheck.PreselectWebContentReader)" PreselectContentCleanerAgent="@(this.SettingsManager.ConfigurationData.LegalCheck.PreselectOptions && this.SettingsManager.ConfigurationData.LegalCheck.PreselectContentCleanerAgent)"/>
}
@if (PreviewFeatures.PRE_READ_PDF_2025.IsEnabled(this.SettingsManager))
{
<ReadPDFContent @bind-PDFContent="@this.inputLegalDocument"/>
}
<MudTextField T="string" Disabled="@this.isAgentRunning" @bind-Text="@this.inputLegalDocument" Validation="@this.ValidatingLegalDocument" AdornmentIcon="@Icons.Material.Filled.DocumentScanner" Adornment="Adornment.Start" Label="@T("Legal document")" Variant="Variant.Outlined" Lines="12" AutoGrow="@true" MaxLines="24" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudTextField T="string" Disabled="@this.isAgentRunning" @bind-Text="@this.inputQuestions" Validation="@this.ValidatingQuestions" AdornmentIcon="@Icons.Material.Filled.QuestionAnswer" Adornment="Adornment.Start" Label="@T("Your questions")" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<ProviderSelection @bind-ProviderSettings="@this.providerSettings" ValidateProvider="@this.ValidatingProvider"/>
@@ -2,12 +2,14 @@ namespace AIStudio.Assistants.RewriteImprove;
public static class SentenceStructureExtensions
{
private static string TB(string fallbackEN) => Tools.PluginSystem.I18N.I.T(fallbackEN, typeof(SentenceStructureExtensions).Namespace, nameof(SentenceStructureExtensions));
public static string Name(this SentenceStructure sentenceStructure) => sentenceStructure switch
{
SentenceStructure.ACTIVE => "Active voice",
SentenceStructure.PASSIVE => "Passive voice",
SentenceStructure.ACTIVE => TB("Active voice"),
SentenceStructure.PASSIVE => TB("Passive voice"),
_ => "Not Specified",
_ => TB("Not Specified"),
};
public static string Prompt(this SentenceStructure sentenceStructure) => sentenceStructure switch
@@ -13,4 +13,5 @@ public enum WritingStyles
MARKETING,
ACADEMIC,
LEGAL,
CHANGELOG,
}
@@ -2,19 +2,22 @@ namespace AIStudio.Assistants.RewriteImprove;
public static class WritingStylesExtensions
{
private static string TB(string fallbackEN) => Tools.PluginSystem.I18N.I.T(fallbackEN, typeof(WritingStylesExtensions).Namespace, nameof(WritingStylesExtensions));
public static string Name(this WritingStyles style) => style switch
{
WritingStyles.EVERYDAY => "Everyday (personal texts, social media)",
WritingStyles.BUSINESS => "Business (business emails, reports, presentations)",
WritingStyles.SCIENTIFIC => "Scientific (scientific papers, research reports)",
WritingStyles.JOURNALISTIC => "Journalistic (magazines, newspapers, news)",
WritingStyles.LITERARY => "Literary (fiction, poetry)",
WritingStyles.TECHNICAL => "Technical (manuals, documentation)",
WritingStyles.MARKETING => "Marketing (advertisements, sales texts)",
WritingStyles.ACADEMIC => "Academic (essays, seminar papers)",
WritingStyles.LEGAL => "Legal (legal texts, contracts)",
WritingStyles.EVERYDAY => TB("Everyday (personal texts, social media)"),
WritingStyles.BUSINESS => TB("Business (business emails, reports, presentations)"),
WritingStyles.SCIENTIFIC => TB("Scientific (scientific papers, research reports)"),
WritingStyles.JOURNALISTIC => TB("Journalistic (magazines, newspapers, news)"),
WritingStyles.LITERARY => TB("Literary (fiction, poetry)"),
WritingStyles.TECHNICAL => TB("Technical (manuals, documentation)"),
WritingStyles.MARKETING => TB("Marketing (advertisements, sales texts)"),
WritingStyles.ACADEMIC => TB("Academic (essays, seminar papers)"),
WritingStyles.LEGAL => TB("Legal (legal texts, contracts)"),
WritingStyles.CHANGELOG => TB("Changelog (release notes, version history)"),
_ => "Not specified",
_ => TB("Not specified"),
};
public static string Prompt(this WritingStyles style) => style switch
@@ -28,6 +31,7 @@ public static class WritingStylesExtensions
WritingStyles.MARKETING => "Use a marketing style like for advertisements, sales texts, and promotional content. Most important is persuasiveness and engagement.",
WritingStyles.ACADEMIC => "Use a academic style like for essays, seminar papers, and academic writing. Most important is clarity and objectivity.",
WritingStyles.LEGAL => "Use a legal style like for legal texts, contracts, and official documents. Most important is precision and legal correctness. Use formal legal language.",
WritingStyles.CHANGELOG => "Use a changelog style like for release notes, version history, and software updates. Most important is clarity and conciseness. The changelog is structured as a Markdown list. Most list items start with one of the following verbs: Added, Changed, Deprecated, Removed, Fixed, Refactored, Improved, or Upgraded -- these verbs should also translated to the target language. Also, changelogs use past tense.",
_ => "Keep the style of the text as it is.",
};
@@ -1,4 +1,5 @@
@attribute [Route(Routes.ASSISTANT_SUMMARIZER)]
@using AIStudio.Settings.DataModel
@inherits AssistantBaseCore<AIStudio.Dialogs.Settings.SettingsDialogTextSummarizer>
@if (!this.SettingsManager.ConfigurationData.TextSummarizer.HideWebContentReader)
@@ -6,6 +7,11 @@
<ReadWebContent @bind-Content="@this.inputText" ProviderSettings="@this.providerSettings" @bind-AgentIsRunning="@this.isAgentRunning" Preselect="@(this.SettingsManager.ConfigurationData.TextSummarizer.PreselectOptions && this.SettingsManager.ConfigurationData.TextSummarizer.PreselectWebContentReader)" PreselectContentCleanerAgent="@(this.SettingsManager.ConfigurationData.TextSummarizer.PreselectOptions && this.SettingsManager.ConfigurationData.TextSummarizer.PreselectContentCleanerAgent)"/>
}
@if (PreviewFeatures.PRE_READ_PDF_2025.IsEnabled(this.SettingsManager))
{
<ReadPDFContent @bind-PDFContent="@this.inputText"/>
}
<MudTextField T="string" Disabled="@this.isAgentRunning" @bind-Text="@this.inputText" Validation="@this.ValidatingText" AdornmentIcon="@Icons.Material.Filled.DocumentScanner" Adornment="Adornment.Start" Label="@T("Your input")" Variant="Variant.Outlined" Lines="6" AutoGrow="@true" MaxLines="12" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<EnumSelection T="CommonLanguages" NameFunc="@(language => language.Name())" @bind-Value="@this.selectedTargetLanguage" Icon="@Icons.Material.Filled.Translate" Label="@T("Target language")" AllowOther="@true" @bind-OtherInput="@this.customTargetLanguage" OtherValue="CommonLanguages.OTHER" LabelOther="@T("Custom target language")" ValidateOther="@this.ValidateCustomLanguage" />
<EnumSelection T="Complexity" NameFunc="@(complexity => complexity.Name())" @bind-Value="@this.selectedComplexity" Icon="@Icons.Material.Filled.Layers" Label="@T("Target complexity")" AllowOther="@true" @bind-OtherInput="@this.expertInField" OtherValue="Complexity.SCIENTIFIC_LANGUAGE_OTHER_EXPERTS" LabelOther="@T("Your expertise")" ValidateOther="@this.ValidateExpertInField" />
@@ -2,18 +2,20 @@ namespace AIStudio.Assistants.TextSummarizer;
public static class ComplexityExtensions
{
private static string TB(string fallbackEN) => Tools.PluginSystem.I18N.I.T(fallbackEN, typeof(ComplexityExtensions).Namespace, nameof(ComplexityExtensions));
public static string Name(this Complexity complexity) => complexity switch
{
Complexity.NO_CHANGE => "No change in complexity",
Complexity.NO_CHANGE => TB("No change in complexity"),
Complexity.SIMPLE_LANGUAGE => "Simple language, e.g., for children",
Complexity.TEEN_LANGUAGE => "Teen language, e.g., for teenagers",
Complexity.EVERYDAY_LANGUAGE => "Everyday language, e.g., for adults",
Complexity.POPULAR_SCIENCE_LANGUAGE => "Popular science language, e.g., for people interested in science",
Complexity.SCIENTIFIC_LANGUAGE_FIELD_EXPERTS => "Scientific language for experts in this field",
Complexity.SCIENTIFIC_LANGUAGE_OTHER_EXPERTS => "Scientific language for experts from other fields (interdisciplinary)",
Complexity.SIMPLE_LANGUAGE => TB("Simple language, e.g., for children"),
Complexity.TEEN_LANGUAGE => TB("Teen language, e.g., for teenagers"),
Complexity.EVERYDAY_LANGUAGE => TB("Everyday language, e.g., for adults"),
Complexity.POPULAR_SCIENCE_LANGUAGE => TB("Popular science language, e.g., for people interested in science"),
Complexity.SCIENTIFIC_LANGUAGE_FIELD_EXPERTS => TB("Scientific language for experts in this field"),
Complexity.SCIENTIFIC_LANGUAGE_OTHER_EXPERTS => TB("Scientific language for experts from other fields (interdisciplinary)"),
_ => "No change in complexity",
_ => TB("No change in complexity"),
};
public static string Prompt(this Complexity complexity, string expertInField) => complexity switch
@@ -1,4 +1,5 @@
@attribute [Route(Routes.ASSISTANT_TRANSLATION)]
@using AIStudio.Settings.DataModel
@inherits AssistantBaseCore<AIStudio.Dialogs.Settings.SettingsDialogTranslation>
@if (!this.SettingsManager.ConfigurationData.Translation.HideWebContentReader)
@@ -6,6 +7,11 @@
<ReadWebContent @bind-Content="@this.inputText" ProviderSettings="@this.providerSettings" @bind-AgentIsRunning="@this.isAgentRunning" Preselect="@(this.SettingsManager.ConfigurationData.Translation.PreselectOptions && this.SettingsManager.ConfigurationData.Translation.PreselectWebContentReader)" PreselectContentCleanerAgent="@(this.SettingsManager.ConfigurationData.Translation.PreselectOptions && this.SettingsManager.ConfigurationData.Translation.PreselectContentCleanerAgent)"/>
}
@if (PreviewFeatures.PRE_READ_PDF_2025.IsEnabled(this.SettingsManager))
{
<ReadPDFContent @bind-PDFContent="@this.inputText"/>
}
<MudTextSwitch Label="@T("Live translation")" @bind-Value="@this.liveTranslation" LabelOn="@T("Live translation")" LabelOff="@T("No live translation")"/>
@if (this.liveTranslation)
{
@@ -13,6 +13,8 @@ public partial class Changelog
public static readonly Log[] LOGS =
[
new (218, "v0.9.43, build 218 (2025-05-11 17:22 UTC)", "v0.9.43.md"),
new (217, "v0.9.42, build 217 (2025-05-04 13:03 UTC)", "v0.9.42.md"),
new (216, "v0.9.41, build 216 (2025-04-27 14:18 UTC)", "v0.9.41.md"),
new (215, "v0.9.40, build 215 (2025-04-20 13:30 UTC)", "v0.9.40.md"),
new (214, "v0.9.39, build 214 (2025-04-07 17:39 UTC)", "v0.9.39.md"),
@@ -270,7 +270,9 @@ public partial class ChatComponent : MSGComponentBase, IAsyncDisposable
private bool CanThreadBeSaved => this.ChatThread is not null && this.ChatThread.Blocks.Count > 0;
private string TooltipAddChatToWorkspace => string.Format(T(@"Start new chat in workspace ""{0}"""), this.currentWorkspaceName);
private string TooltipAddChatToWorkspace => string.Format(T("""
Start new chat in workspace "{0}"
"""), this.currentWorkspaceName);
private string UserInputStyle => this.SettingsManager.ConfigurationData.LLMProviders.ShowProviderConfidence ? this.Provider.UsedLLMProvider.GetConfidence(this.SettingsManager).SetColorStyle(this.SettingsManager) : string.Empty;
@@ -291,6 +293,12 @@ public partial class ChatComponent : MSGComponentBase, IAsyncDisposable
// We select the first 10 words of the user input:
var words = firstUserInput.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var threadName = string.Join(' ', words.Take(10));
threadName = threadName.Trim();
// Remove all line breaks:
threadName = threadName.Replace("\r", string.Empty);
threadName = threadName.Replace("\n", " ");
threadName = threadName.Replace("\t", " ");
// If the thread name is empty, we use a default name:
if (string.IsNullOrWhiteSpace(threadName))
@@ -2,13 +2,15 @@ using System.Diagnostics.CodeAnalysis;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Tools.PluginSystem;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Components;
public partial class ConfigurationProviderSelection : MSGComponentBase
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(ConfigurationProviderSelection).Namespace, nameof(ConfigurationProviderSelection));
[Parameter]
public Func<string> SelectedValue { get; set; } = () => string.Empty;
@@ -25,7 +27,7 @@ public partial class ConfigurationProviderSelection : MSGComponentBase
public Func<bool> Disabled { get; set; } = () => false;
[Parameter]
public Func<string> HelpText { get; set; } = () => "Select a provider that is preselected.";
public Func<string> HelpText { get; set; } = () => TB("Select a provider that is preselected.");
[Parameter]
public Tools.Components Component { get; set; } = Tools.Components.NONE;
@@ -0,0 +1,4 @@
@inherits MSGComponentBase
<MudButton StartIcon="@Icons.Material.Filled.Description" OnClick="async () => await this.SelectFile()" Variant="Variant.Filled" Class="mb-3">
@T("Use PDF content as input")
</MudButton>
@@ -0,0 +1,31 @@
using AIStudio.Tools.Rust;
using AIStudio.Tools.Services;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Components;
public partial class ReadPDFContent : MSGComponentBase
{
[Parameter]
public string PDFContent { get; set; } = string.Empty;
[Parameter]
public EventCallback<string> PDFContentChanged { get; set; }
[Inject]
private RustService RustService { get; init; } = null!;
private async Task SelectFile()
{
var pdfFile = await this.RustService.SelectFile(T("Select PDF file"), FileTypeFilter.PDF);
if (pdfFile.UserCancelled)
return;
if(!File.Exists(pdfFile.SelectedFilePath))
return;
var pdfText = await this.RustService.GetPDFText(pdfFile.SelectedFilePath);
await this.PDFContentChanged.InvokeAsync(pdfText);
}
}
@@ -1,5 +1,5 @@
@inherits MSGComponentBase
<MudPaper Class="pa-3 mb-8 border-dashed border rounded-lg">
<MudPaper Class="pa-3 mb-3 border-dashed border rounded-lg">
<MudTextSwitch Label="@T("Read content from web?")" Disabled="@this.AgentIsRunning" @bind-Value="@this.showWebContentReader" LabelOn="@T("Show web content options")" LabelOff="@T("Hide web content options")" />
@if (this.showWebContentReader)
{
@@ -1,4 +1,5 @@
using AIStudio.Settings;
using AIStudio.Tools.Rust;
using AIStudio.Tools.Services;
using Microsoft.AspNetCore.Components;
@@ -22,6 +23,9 @@ public partial class SelectFile : ComponentBase
[Parameter]
public string FileDialogTitle { get; set; } = "Select File";
[Parameter]
public FileTypeFilter? Filter { get; set; }
[Parameter]
public Func<string, string?> Validation { get; set; } = _ => null;
@@ -55,7 +59,7 @@ public partial class SelectFile : ComponentBase
private async Task OpenFileDialog()
{
var response = await this.RustService.SelectFile(this.FileDialogTitle, string.IsNullOrWhiteSpace(this.File) ? null : this.File);
var response = await this.RustService.SelectFile(this.FileDialogTitle, this.Filter, string.IsNullOrWhiteSpace(this.File) ? null : this.File);
this.Logger.LogInformation($"The user selected the file '{response.SelectedFilePath}'.");
if (!response.UserCancelled)
@@ -6,11 +6,11 @@
@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.SettingsManager.ConfigurationData.App.LanguageBehavior = 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?")"/>
<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.SettingsManager.ConfigurationData.App.LanguagePluginId = 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.")"/>
}
}
@@ -9,4 +9,16 @@ public partial class SettingsPanelApp : SettingsPanelBase
this.SettingsManager.ConfigurationData.App.PreviewVisibility = previewVisibility;
this.SettingsManager.ConfigurationData.App.EnabledPreviewFeatures = previewVisibility.FilterPreviewFeatures(this.SettingsManager.ConfigurationData.App.EnabledPreviewFeatures);
}
private async Task UpdateLangBehaviour(LangBehavior behavior)
{
this.SettingsManager.ConfigurationData.App.LanguageBehavior = behavior;
await this.MessageBus.SendMessage<bool>(this, Event.PLUGINS_RELOADED);
}
private async Task UpdateManuallySelectedLanguage(Guid pluginId)
{
this.SettingsManager.ConfigurationData.App.LanguagePluginId = pluginId;
await this.MessageBus.SendMessage<bool>(this, Event.PLUGINS_RELOADED);
}
}
@@ -4,24 +4,17 @@
@if (PreviewFeatures.PRE_RAG_2024.IsEnabled(this.SettingsManager))
{
<ExpansionPanel HeaderIcon="@Icons.Material.Filled.IntegrationInstructions" HeaderText="Configure Embeddings">
<ExpansionPanel HeaderIcon="@Icons.Material.Filled.IntegrationInstructions" HeaderText="@T("Configure Embeddings")">
<PreviewPrototype/>
<MudText Typo="Typo.h4" Class="mb-3">
Configured Embeddings
@T("Configured Embeddings")
</MudText>
<MudJustifiedText Typo="Typo.body1" Class="mb-3">
Embeddings are a way to represent words, sentences, entire documents, or even images and videos as digital
fingerprints. Just like each person has a unique fingerprint, embedding models create unique digital patterns
that capture the meaning and characteristics of the content they analyze. When two things are similar in meaning
or content, their digital fingerprints will look very similar. For example, the fingerprints for 'happy' and
'joyful' would be more alike than those for 'happy' and 'sad'.
@T("Embeddings are a way to represent words, sentences, entire documents, or even images and videos as digital fingerprints. Just like each person has a unique fingerprint, embedding models create unique digital patterns that capture the meaning and characteristics of the content they analyze. When two things are similar in meaning or content, their digital fingerprints will look very similar. For example, the fingerprints for 'happy' and 'joyful' would be more alike than those for 'happy' and 'sad'.")
</MudJustifiedText>
<MudJustifiedText Typo="Typo.body1" Class="mb-3">
This helps AI Studio understand and compare things in a way that's similar to how humans do. When you're working on
something, AI Studio can automatically identify related documents and data by comparing their digital fingerprints.
For instance, if you're writing about customer service, AI Studio can instantly find other documents in your data that
discuss similar topics or experiences, even if they use different words.
@T("This helps AI Studio understand and compare things in a way that's similar to how humans do. When you're working on something, AI Studio can automatically identify related documents and data by comparing their digital fingerprints. For instance, if you're writing about customer service, AI Studio can instantly find other documents in your data that discuss similar topics or experiences, even if they use different words.")
</MudJustifiedText>
<MudTable Items="@this.SettingsManager.ConfigurationData.EmbeddingProviders" Hover="@true" Class="border-dashed border rounded-lg">
<ColGroup>
@@ -33,10 +26,10 @@
</ColGroup>
<HeaderContent>
<MudTh>#</MudTh>
<MudTh>Name</MudTh>
<MudTh>Provider</MudTh>
<MudTh>Model</MudTh>
<MudTh>Actions</MudTh>
<MudTh>@T("Name")</MudTh>
<MudTh>@T("Provider")</MudTh>
<MudTh>@T("Model")</MudTh>
<MudTh>@T("Actions")</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>@context.Num</MudTd>
@@ -47,13 +40,13 @@
<MudTd>
<MudStack Row="true" Class="mb-2 mt-2" Wrap="Wrap.Wrap">
<MudButton Variant="Variant.Filled" Color="Color.Info" StartIcon="@Icons.Material.Filled.OpenInBrowser" Href="@context.UsedLLMProvider.GetDashboardURL()" Target="_blank" Disabled="@(!context.UsedLLMProvider.HasDashboard())">
Open Dashboard
@T("Open Dashboard")
</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Info" StartIcon="@Icons.Material.Filled.Edit" OnClick="() => this.EditEmbeddingProvider(context)">
Edit
@T("Edit")
</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Error" StartIcon="@Icons.Material.Filled.Delete" OnClick="() => this.DeleteEmbeddingProvider(context)">
Delete
@T("Delete")
</MudButton>
</MudStack>
</MudTd>
@@ -62,11 +55,13 @@
@if (this.SettingsManager.ConfigurationData.EmbeddingProviders.Count == 0)
{
<MudText Typo="Typo.h6" Class="mt-3">No embeddings configured yet.</MudText>
<MudText Typo="Typo.h6" Class="mt-3">
@T("No embeddings configured yet.")
</MudText>
}
<MudButton Variant="Variant.Filled" Color="@Color.Primary" StartIcon="@Icons.Material.Filled.AddRoad" Class="mt-3 mb-6" OnClick="@this.AddEmbeddingProvider">
Add Embedding
@T("Add Embedding")
</MudButton>
</ExpansionPanel>
}
@@ -39,7 +39,7 @@ public partial class SettingsPanelEmbeddings : SettingsPanelBase
{ x => x.IsEditing, false },
};
var dialogReference = await this.DialogService.ShowAsync<EmbeddingProviderDialog>("Add Embedding Provider", dialogParameters, DialogOptions.FULLSCREEN);
var dialogReference = await this.DialogService.ShowAsync<EmbeddingProviderDialog>(T("Add Embedding Provider"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
return;
@@ -69,7 +69,7 @@ public partial class SettingsPanelEmbeddings : SettingsPanelBase
{ x => x.DataHost, embeddingProvider.Host },
};
var dialogReference = await this.DialogService.ShowAsync<EmbeddingProviderDialog>("Edit Embedding Provider", dialogParameters, DialogOptions.FULLSCREEN);
var dialogReference = await this.DialogService.ShowAsync<EmbeddingProviderDialog>(T("Edit Embedding Provider"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
return;
@@ -92,10 +92,10 @@ public partial class SettingsPanelEmbeddings : SettingsPanelBase
{
var dialogParameters = new DialogParameters
{
{ "Message", $"Are you sure you want to delete the embedding provider '{provider.Name}'?" },
{ "Message", string.Format(T("Are you sure you want to delete the embedding provider '{0}'?"), provider.Name) },
};
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>("Delete Embedding Provider", dialogParameters, DialogOptions.FULLSCREEN);
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>(T("Delete Embedding Provider"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
return;
@@ -0,0 +1,16 @@
<MudListItem T="string" Href="@this.URL" Target="_blank">
<AvatarContent>
<MudAvatar Variant="Variant.Filled" Size="Size.Large" Style="background-color: white;" Class="mr-6">
<MudImage Src="@this.ImageSrc"/>
</MudAvatar>
</AvatarContent>
<ChildContent>
<MudText Typo="Typo.h6" Inline="@true">
@this.Name
</MudText>
<MudText Typo="Typo.body1" Class="ml-3" Inline="@true">
@this.Acknowledgment
</MudText>
</ChildContent>
</MudListItem>
@@ -0,0 +1,21 @@
using Microsoft.AspNetCore.Components;
namespace AIStudio.Components;
public partial class Titan : ComponentBase
{
[Parameter]
public string Name { get; set; } = string.Empty;
[Parameter]
public string Acknowledgment { get; set; } = string.Empty;
[Parameter]
public string? URL { get; set; }
[Parameter]
public SupporterType Type { get; set; }
[Parameter]
public string? ImageSrc { get; set; }
}
@@ -1,15 +1,16 @@
@using AIStudio.Provider
@using AIStudio.Provider.SelfHosted
@inherits MSGComponentBase
<MudDialog>
<DialogContent>
<MudForm @ref="@this.form" @bind-IsValid="@this.dataIsValid" @bind-Errors="@this.dataIssues">
<MudStack Row="@true" AlignItems="AlignItems.Center">
@* ReSharper disable once CSharpWarnings::CS8974 *@
<MudSelect @bind-Value="@this.DataLLMProvider" Label="Provider" Class="mb-3" OpenIcon="@Icons.Material.Filled.AccountBalance" AdornmentColor="Color.Info" Adornment="Adornment.Start" Validation="@this.providerValidation.ValidatingProvider">
<MudSelect @bind-Value="@this.DataLLMProvider" Label="@T("Provider")" Class="mb-3" OpenIcon="@Icons.Material.Filled.AccountBalance" AdornmentColor="Color.Info" Adornment="Adornment.Start" Validation="@this.providerValidation.ValidatingProvider">
@foreach (LLMProviders provider in Enum.GetValues(typeof(LLMProviders)))
{
if (provider.ProvideEmbeddings())
if (provider.ProvideEmbeddings() || provider is LLMProviders.NONE)
{
<MudSelectItem Value="@provider">
@provider.ToName()
@@ -17,7 +18,9 @@
}
}
</MudSelect>
<MudButton Disabled="@(!this.DataLLMProvider.ShowRegisterButton())" Variant="Variant.Filled" Size="Size.Small" StartIcon="@Icons.Material.Filled.OpenInBrowser" Href="@this.DataLLMProvider.GetCreationURL()" Target="_blank">Create account</MudButton>
<MudButton Disabled="@(!this.DataLLMProvider.ShowRegisterButton())" Variant="Variant.Filled" Size="Size.Small" StartIcon="@Icons.Material.Filled.OpenInBrowser" Href="@this.DataLLMProvider.GetCreationURL()" Target="_blank">
@T("Create account")
</MudButton>
</MudStack>
@if (this.DataLLMProvider.IsAPIKeyNeeded(this.DataHost))
@@ -32,6 +35,7 @@
AdornmentIcon="@Icons.Material.Filled.VpnKey"
AdornmentColor="Color.Info"
InputType="InputType.Password"
Immediate="true"
Validation="@this.providerValidation.ValidatingAPIKey"/>
}
@@ -40,7 +44,7 @@
<MudTextField
T="string"
@bind-Text="@this.DataHostname"
Label="Hostname"
Label="@T("Hostname")"
Class="mb-3"
Adornment="Adornment.Start"
AdornmentIcon="@Icons.Material.Filled.Dns"
@@ -51,7 +55,7 @@
@if (this.DataLLMProvider.IsHostNeeded())
{
<MudSelect @bind-Value="@this.DataHost" Label="Host" Class="mb-3" OpenIcon="@Icons.Material.Filled.ExpandMore" AdornmentColor="Color.Info" Adornment="Adornment.Start" Validation="@this.providerValidation.ValidatingHost">
<MudSelect @bind-Value="@this.DataHost" Label="@T("Host")" Class="mb-3" OpenIcon="@Icons.Material.Filled.ExpandMore" AdornmentColor="Color.Info" Adornment="Adornment.Start" Validation="@this.providerValidation.ValidatingHost">
@foreach (Host host in Enum.GetValues(typeof(Host)))
{
if (host.AreEmbeddingsSupported())
@@ -64,39 +68,57 @@
</MudSelect>
}
<MudStack Row="@true" AlignItems="AlignItems.Center">
@if (this.DataLLMProvider.IsEmbeddingModelProvidedManually(this.DataHost))
{
<MudTextField
T="string"
@bind-Text="@this.dataManuallyModel"
Label="Model"
Class="mb-3"
Adornment="Adornment.Start"
AdornmentIcon="@Icons.Material.Filled.Dns"
AdornmentColor="Color.Info"
Validation="@this.ValidateManuallyModel"
UserAttributes="@SPELLCHECK_ATTRIBUTES"
HelperText="Currently, we cannot query the embedding models of self-hosted systems. Therefore, enter the model name manually."
/>
}
else
{
<MudButton Disabled="@(!this.DataLLMProvider.CanLoadModels(this.DataHost, this.dataAPIKey))" Variant="Variant.Filled" Size="Size.Small" StartIcon="@Icons.Material.Filled.Refresh" OnClick="this.ReloadModels">Load</MudButton>
<MudSelect Disabled="@this.IsNoneProvider" @bind-Value="@this.DataModel" Label="Model" Class="mb-3" OpenIcon="@Icons.Material.Filled.FaceRetouchingNatural" AdornmentColor="Color.Info" Adornment="Adornment.Start" Validation="@this.providerValidation.ValidatingModel">
@foreach (var model in this.availableModels)
<MudField FullWidth="true" Label="@T("Model selection")" Variant="Variant.Outlined" Class="mb-3">
<MudStack Row="@true" AlignItems="AlignItems.Center" StretchItems="StretchItems.End">
@if (this.DataLLMProvider.IsEmbeddingModelProvidedManually(this.DataHost))
{
<MudTextField
T="string"
@bind-Text="@this.dataManuallyModel"
Label="@T("Model")"
Class="mb-3"
Adornment="Adornment.Start"
AdornmentIcon="@Icons.Material.Filled.Dns"
AdornmentColor="Color.Info"
Validation="@this.ValidateManuallyModel"
UserAttributes="@SPELLCHECK_ATTRIBUTES"
HelperText="@T("Currently, we cannot query the embedding models of self-hosted systems. Therefore, enter the model name manually.")"
/>
}
else
{
<MudButton Disabled="@(!this.DataLLMProvider.CanLoadModels(this.DataHost, this.dataAPIKey))" Variant="Variant.Filled" Size="Size.Small" StartIcon="@Icons.Material.Filled.Refresh" OnClick="this.ReloadModels">
@T("Load")
</MudButton>
@if(this.availableModels.Count is 0)
{
<MudSelectItem Value="@model">@model</MudSelectItem>
<MudText Typo="Typo.body1">
@T("No models loaded or available.")
</MudText>
}
</MudSelect>
}
</MudStack>
else
{
<MudSelect Disabled="@this.IsNoneProvider" @bind-Value="@this.DataModel" Label="@T("Model")"
OpenIcon="@Icons.Material.Filled.FaceRetouchingNatural"
AdornmentColor="Color.Info" Adornment="Adornment.Start"
Validation="@this.providerValidation.ValidatingModel">
@foreach (var model in this.availableModels)
{
<MudSelectItem Value="@model">
@model
</MudSelectItem>
}
</MudSelect>
}
}
</MudStack>
</MudField>
@* ReSharper disable once CSharpWarnings::CS8974 *@
<MudTextField
T="string"
@bind-Text="@this.DataName"
Label="Instance Name"
Label="@T("Instance Name")"
Class="mb-3"
MaxLength="40"
Counter="40"
@@ -112,15 +134,17 @@
<Issues IssuesData="@this.dataIssues"/>
</DialogContent>
<DialogActions>
<MudButton OnClick="@this.Cancel" Variant="Variant.Filled">Cancel</MudButton>
<MudButton OnClick="@this.Cancel" Variant="Variant.Filled">
@T("Cancel")
</MudButton>
<MudButton OnClick="@this.Store" Variant="Variant.Filled" Color="Color.Primary">
@if(this.IsEditing)
{
@:Update
@T("Update")
}
else
{
@:Add
@T("Add")
}
</MudButton>
</DialogActions>
@@ -1,3 +1,4 @@
using AIStudio.Components;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Tools.Services;
@@ -9,7 +10,7 @@ using Host = AIStudio.Provider.SelfHosted.Host;
namespace AIStudio.Dialogs;
public partial class EmbeddingProviderDialog : ComponentBase, ISecretId
public partial class EmbeddingProviderDialog : MSGComponentBase, ISecretId
{
[CascadingParameter]
private IMudDialogInstance MudDialog { get; set; } = null!;
@@ -68,9 +69,6 @@ public partial class EmbeddingProviderDialog : ComponentBase, ISecretId
[Parameter]
public bool IsEditing { get; init; }
[Inject]
private SettingsManager SettingsManager { get; init; } = null!;
[Inject]
private ILogger<ProviderDialog> Logger { get; init; } = null!;
@@ -175,7 +173,7 @@ public partial class EmbeddingProviderDialog : ComponentBase, ISecretId
this.dataAPIKey = string.Empty;
if (this.DataLLMProvider is not LLMProviders.SELF_HOSTED)
{
this.dataAPIKeyStorageIssue = $"Failed to load the API key from the operating system. The message was: {requestedSecret.Issue}. You might ignore this message and provide the API key again.";
this.dataAPIKeyStorageIssue = string.Format(T("Failed to load the API key from the operating system. The message was: {0}. You might ignore this message and provide the API key again."), requestedSecret.Issue);
await this.form.Validate();
}
}
@@ -224,7 +222,7 @@ public partial class EmbeddingProviderDialog : ComponentBase, ISecretId
var storeResponse = await this.RustService.SetAPIKey(this, this.dataAPIKey);
if (!storeResponse.Success)
{
this.dataAPIKeyStorageIssue = $"Failed to store the API key in the operating system. The message was: {storeResponse.Issue}. Please try again.";
this.dataAPIKeyStorageIssue = string.Format(T("Failed to store the API key in the operating system. The message was: {0}. Please try again."), storeResponse.Issue);
await this.form.Validate();
return;
}
@@ -236,7 +234,7 @@ public partial class EmbeddingProviderDialog : ComponentBase, ISecretId
private string? ValidateManuallyModel(string manuallyModel)
{
if (this.DataLLMProvider is LLMProviders.SELF_HOSTED && string.IsNullOrWhiteSpace(manuallyModel))
return "Please enter an embedding model name.";
return T("Please enter an embedding model name.");
return null;
}
@@ -261,8 +259,8 @@ public partial class EmbeddingProviderDialog : ComponentBase, ISecretId
private string APIKeyText => this.DataLLMProvider switch
{
LLMProviders.SELF_HOSTED => "(Optional) API Key",
_ => "API Key",
LLMProviders.SELF_HOSTED => T("(Optional) API Key"),
_ => T("API Key"),
};
private bool IsNoneProvider => this.DataLLMProvider is LLMProviders.NONE;
@@ -79,7 +79,7 @@
@* ReSharper restore Asp.Entity *@
}
<MudField FullWidth="true" Label="Model selection" Variant="Variant.Outlined" Class="mb-3">
<MudField FullWidth="true" Label="@T("Model selection")" Variant="Variant.Outlined" Class="mb-3">
<MudStack Row="@true" AlignItems="AlignItems.Center" StretchItems="StretchItems.End">
@if (this.DataLLMProvider.IsLLMModelProvidedManually())
{
@@ -10,7 +10,7 @@
</TitleContent>
<DialogContent>
<MudPaper Class="pa-3 mb-8 border-dashed border rounded-lg">
<ConfigurationOption OptionDescription="Preselect grammar & spell checker options?" LabelOn="Grammar & spell checker options are preselected" LabelOff="No grammar & spell checker options are preselected" State="@(() => this.SettingsManager.ConfigurationData.GrammarSpelling.PreselectOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.GrammarSpelling.PreselectOptions = updatedState)" OptionHelp="When enabled, you can preselect the grammar & spell checker options. This is might be useful when you prefer a specific language or LLM model."/>
<ConfigurationOption OptionDescription="@T("Preselect grammar & spell checker options?")" LabelOn="@T("Grammar & spell checker options are preselected")" LabelOff="@T("No grammar & spell checker options are preselected")" State="@(() => this.SettingsManager.ConfigurationData.GrammarSpelling.PreselectOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.GrammarSpelling.PreselectOptions = updatedState)" OptionHelp="@T("When enabled, you can preselect the grammar & spell checker options. This is might be useful when you prefer a specific language or LLM model.")"/>
<ConfigurationSelect OptionDescription="@T("Preselect the target language")" Disabled="@(() => !this.SettingsManager.ConfigurationData.GrammarSpelling.PreselectOptions)" SelectedValue="@(() => this.SettingsManager.ConfigurationData.GrammarSpelling.PreselectedTargetLanguage)" Data="@ConfigurationSelectDataFactory.GetCommonLanguagesOptionalData()" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.GrammarSpelling.PreselectedTargetLanguage = selectedValue)" OptionHelp="@T("Which target language should be preselected?")"/>
@if (this.SettingsManager.ConfigurationData.GrammarSpelling.PreselectedTargetLanguage is CommonLanguages.OTHER)
{
@@ -10,13 +10,13 @@
</TitleContent>
<DialogContent>
<MudPaper Class="pa-3 mb-8 border-dashed border rounded-lg">
<ConfigurationOption OptionDescription="Preselect localization options?" LabelOn="Localization options are preselected" LabelOff="No localization options are preselected" State="@(() => this.SettingsManager.ConfigurationData.I18N.PreselectOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.I18N.PreselectOptions = updatedState)" OptionHelp="When enabled, you can preselect the localization options. This is might be useful when you prefer a specific language or LLM model."/>
<ConfigurationOption OptionDescription="@T("Preselect localization options?")" LabelOn="@T("Localization options are preselected")" LabelOff="@T("No localization options are preselected")" State="@(() => this.SettingsManager.ConfigurationData.I18N.PreselectOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.I18N.PreselectOptions = updatedState)" OptionHelp="@T("When enabled, you can preselect the localization options. This is might be useful when you prefer a specific language or LLM model.")"/>
<ConfigurationSelect OptionDescription="@T("Preselect the target language")" Disabled="@(() => !this.SettingsManager.ConfigurationData.I18N.PreselectOptions)" SelectedValue="@(() => this.SettingsManager.ConfigurationData.I18N.PreselectedTargetLanguage)" Data="@ConfigurationSelectDataFactory.GetCommonLanguagesOptionalData()" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.I18N.PreselectedTargetLanguage = selectedValue)" OptionHelp="@T("Which target language should be preselected?")"/>
@if (this.SettingsManager.ConfigurationData.I18N.PreselectedTargetLanguage is CommonLanguages.OTHER)
{
<ConfigurationText OptionDescription="@T("Preselect another target language")" Disabled="@(() => !this.SettingsManager.ConfigurationData.I18N.PreselectOptions)" Icon="@Icons.Material.Filled.Translate" Text="@(() => this.SettingsManager.ConfigurationData.I18N.PreselectOtherLanguage)" TextUpdate="@(updatedText => this.SettingsManager.ConfigurationData.I18N.PreselectOtherLanguage = updatedText)"/>
}
<ConfigurationSelect OptionDescription="Language plugin used for comparision" SelectedValue="@(() => this.SettingsManager.ConfigurationData.I18N.PreselectedLanguagePluginId)" Data="@ConfigurationSelectDataFactory.GetLanguagesData()" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.I18N.PreselectedLanguagePluginId = selectedValue)" OptionHelp="Select the language plugin used for comparision."/>
<ConfigurationSelect OptionDescription="@T("Language plugin used for comparision")" SelectedValue="@(() => this.SettingsManager.ConfigurationData.I18N.PreselectedLanguagePluginId)" Data="@ConfigurationSelectDataFactory.GetLanguagesData()" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.I18N.PreselectedLanguagePluginId = selectedValue)" OptionHelp="@T("Select the language plugin used for comparision.")"/>
<ConfigurationProviderSelection Component="Components.I18N_ASSISTANT" Data="@this.availableLLMProviders" Disabled="@(() => !this.SettingsManager.ConfigurationData.I18N.PreselectOptions)" SelectedValue="@(() => this.SettingsManager.ConfigurationData.I18N.PreselectedProvider)" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.I18N.PreselectedProvider = selectedValue)"/>
</MudPaper>
</DialogContent>
@@ -10,7 +10,7 @@
</TitleContent>
<DialogContent>
<MudPaper Class="pa-3 mb-8 border-dashed border rounded-lg">
<ConfigurationOption OptionDescription="Preselect rewrite & improve text options?" LabelOn="Rewrite & improve text options are preselected" LabelOff="No rewrite & improve text options are preselected" State="@(() => this.SettingsManager.ConfigurationData.RewriteImprove.PreselectOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.RewriteImprove.PreselectOptions = updatedState)" OptionHelp="When enabled, you can preselect the rewrite & improve text options. This is might be useful when you prefer a specific language or LLM model."/>
<ConfigurationOption OptionDescription="@T("Preselect rewrite & improve text options?")" LabelOn="@T("Rewrite & improve text options are preselected")" LabelOff="@T("No rewrite & improve text options are preselected")" State="@(() => this.SettingsManager.ConfigurationData.RewriteImprove.PreselectOptions)" StateUpdate="@(updatedState => this.SettingsManager.ConfigurationData.RewriteImprove.PreselectOptions = updatedState)" OptionHelp="@T("When enabled, you can preselect the rewrite & improve text options. This is might be useful when you prefer a specific language or LLM model.")"/>
<ConfigurationSelect OptionDescription="@T("Preselect the target language")" Disabled="@(() => !this.SettingsManager.ConfigurationData.RewriteImprove.PreselectOptions)" SelectedValue="@(() => this.SettingsManager.ConfigurationData.RewriteImprove.PreselectedTargetLanguage)" Data="@ConfigurationSelectDataFactory.GetCommonLanguagesOptionalData()" SelectionUpdate="@(selectedValue => this.SettingsManager.ConfigurationData.RewriteImprove.PreselectedTargetLanguage = selectedValue)" OptionHelp="@T("Which target language should be preselected?")"/>
@if (this.SettingsManager.ConfigurationData.RewriteImprove.PreselectedTargetLanguage is CommonLanguages.OTHER)
{
@@ -206,6 +206,10 @@ public partial class MainLayout : LayoutComponentBase, IMessageBusReceiver, ILan
break;
case Event.PLUGINS_RELOADED:
this.Lang = await this.SettingsManager.GetActiveLanguagePlugin();
I18N.Init(this.Lang);
this.LoadNavItems();
await this.InvokeAsync(this.StateHasChanged);
break;
}
@@ -47,11 +47,11 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="CodeBeam.MudBlazor.Extensions" Version="8.0.0" />
<PackageReference Include="CodeBeam.MudBlazor.Extensions" Version="8.2.0" />
<PackageReference Include="HtmlAgilityPack" Version="1.12.1" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="9.0.4" />
<PackageReference Include="MudBlazor" Version="8.5.1" />
<PackageReference Include="MudBlazor.Markdown" Version="8.5.1" />
<PackageReference Include="MudBlazor" Version="8.6.0" />
<PackageReference Include="MudBlazor.Markdown" Version="8.6.0" />
<PackageReference Include="ReverseMarkdown" Version="4.6.0" />
<PackageReference Include="LuaCSharp" Version="0.4.2" />
</ItemGroup>
@@ -80,6 +80,7 @@
<MetaTauriVersion>$([System.String]::Copy( $(Metadata) ).Split( ';' )[ 7 ])</MetaTauriVersion>
<MetaAppCommitHash>$([System.String]::Copy( $(Metadata) ).Split( ';' )[ 8 ])</MetaAppCommitHash>
<MetaArchitecture>$([System.String]::Copy( $(Metadata) ).Split( ';' )[ 9 ])</MetaArchitecture>
<MetaPdfiumVersion>$([System.String]::Copy( $(Metadata) ).Split( ';' )[ 10 ])</MetaPdfiumVersion>
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
@@ -104,6 +105,9 @@
<AssemblyAttribute Include="AIStudio.Tools.Metadata.MetaDataArchitecture">
<_Parameter1>$(MetaArchitecture)</_Parameter1>
</AssemblyAttribute>
<AssemblyAttribute Include="AIStudio.Tools.Metadata.MetaDataLibraries">
<_Parameter1>$(MetaPdfiumVersion)</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
</Target>
+2
View File
@@ -18,6 +18,7 @@
<MudListItem T="string" Icon="@Icons.Material.Outlined.Build" Text="@VersionDotnetSdk"/>
<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.Widgets" Text="@MudBlazorVersion"/>
<MudListItem T="string" Icon="@Icons.Material.Outlined.Memory" Text="@TauriVersion"/>
<MudListItem T="string" Icon="@Icons.Material.Outlined.Translate" Text="@this.OSLanguage"/>
@@ -111,6 +112,7 @@
<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="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.")"/>
<ThirdPartyComponent Name="pdfium-render" Developer="Alastair Carey, Dorian Rudolph & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/ajrcarey/pdfium-render/blob/master/LICENSE.md" RepositoryUrl="https://github.com/ajrcarey/pdfium-render" 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.")"/>
<ThirdPartyComponent Name="sys-locale" Developer="1Password Team, ComplexSpaces & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/1Password/sys-locale/blob/main/LICENSE-MIT" RepositoryUrl="https://github.com/1Password/sys-locale" UseCase="@T("This library is used to determine the language of the operating system. This is necessary to set the language of the user interface.")"/>
<ThirdPartyComponent Name="Lua-CSharp" Developer="Yusuke Nakada & Open Source Community" LicenseName="MIT" LicenseUrl="https://github.com/nuskey8/Lua-CSharp/blob/main/LICENSE" RepositoryUrl="https://github.com/nuskey8/Lua-CSharp" UseCase="@T("We use Lua as the language for plugins. Lua-CSharp lets Lua scripts communicate with AI Studio and vice versa. Thank you, Yusuke Nakada, for this great library.")" />
+4 -1
View File
@@ -21,7 +21,8 @@ public partial class About : MSGComponentBase
private static readonly Assembly ASSEMBLY = Assembly.GetExecutingAssembly();
private static readonly MetaDataAttribute META_DATA = ASSEMBLY.GetCustomAttribute<MetaDataAttribute>()!;
private static readonly MetaDataArchitecture META_DATA_ARCH = ASSEMBLY.GetCustomAttribute<MetaDataArchitecture>()!;
private static readonly MetaDataArchitectureAttribute META_DATA_ARCH = ASSEMBLY.GetCustomAttribute<MetaDataArchitectureAttribute>()!;
private static readonly MetaDataLibrariesAttribute META_DATA_LIBRARIES = ASSEMBLY.GetCustomAttribute<MetaDataLibrariesAttribute>()!;
private string osLanguage = string.Empty;
@@ -40,6 +41,8 @@ public partial class About : MSGComponentBase
private string VersionDotnetSdk => $"{T("Used .NET SDK")}: v{META_DATA.DotnetSdkVersion}";
private string BuildTime => $"{T("Build time")}: {META_DATA.BuildTime}";
private string VersionPdfium => $"{T("Used PDFium version")}: v{META_DATA_LIBRARIES.PdfiumVersion}";
private GetLogPathsResponse logPaths;
@@ -20,6 +20,11 @@
<MudText Typo="Typo.body1" Style="text-align: justify; hyphens: auto;" Class="mb-3">
@T("For companies, sponsoring MindWork AI Studio is not only a way to support innovation but also a valuable opportunity for public relations and marketing. Your company's name and logo will be featured prominently, showcasing your commitment to using cutting-edge AI tools and enhancing your reputation as an innovative enterprise.")
</MudText>
<MudList T="string" Class="mb-3">
<Titan Name="@T("German Aerospace Center (DLR)")" Type="SupporterType.ORGANIZATION" URL="https://www.dlr.de/" ImageSrc="svg/titans/DLR.svg" Acknowledgment="@T("We would like to thank the DLR for its courage in supporting MindWork AI Studio at an early stage. The DLR not only uses AI Studio in various projects but also supports its further development with personnel resources.")"/>
</MudList>
<MudButton Href="https://github.com/sponsors/MindWorkAI" StartIcon="@Icons.Material.Filled.Business" Variant="Variant.Filled" Target="_blank">
@T("Become our first Titan")
</MudButton>
+1
View File
@@ -111,6 +111,7 @@ internal sealed class Program
config.SnackbarConfiguration.SnackbarVariant = Variant.Outlined;
});
builder.Services.AddMemoryCache(); // Needed for the Markdown library
builder.Services.AddMudMarkdownServices();
builder.Services.AddSingleton(new MudTheme());
builder.Services.AddSingleton(MessageBus.INSTANCE);
@@ -139,9 +139,79 @@ public sealed class ProviderAlibabaCloud(ILogger logger) : BaseProvider("https:/
return this.LoadModels(["text-embedding-"], token, apiKeyProvisional).ContinueWith(t => t.Result.Concat(additionalModels).OrderBy(x => x.Id).AsEnumerable(), token);
}
#endregion
/// <inheritdoc />
public override IReadOnlyCollection<Capability> GetModelCapabilities(Model model)
{
var modelName = model.Id.ToLowerInvariant().AsSpan();
// Qwen models:
if (modelName.StartsWith("qwen"))
{
// Check for omni models:
if (modelName.IndexOf("omni") is not -1)
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.AUDIO_INPUT, Capability.SPEECH_INPUT,
Capability.VIDEO_INPUT,
Capability.TEXT_OUTPUT, Capability.SPEECH_OUTPUT
];
// Check for Qwen 3:
if(modelName.StartsWith("qwen3"))
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
Capability.OPTIONAL_REASONING, Capability.FUNCTION_CALLING
];
if(modelName.IndexOf("-vl-") is not -1)
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
];
}
// QwQ models:
if (modelName.StartsWith("qwq"))
{
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
Capability.ALWAYS_REASONING, Capability.FUNCTION_CALLING
];
}
// QVQ models:
if (modelName.StartsWith("qvq"))
{
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
Capability.ALWAYS_REASONING
];
}
// Default to text input and output:
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING
];
}
#endregion
private async Task<IEnumerable<Model>> LoadModels(string[] prefixes, CancellationToken token, string? apiKeyProvisional = null)
{
@@ -110,6 +110,33 @@ public sealed class ProviderAnthropic(ILogger logger) : BaseProvider("https://ap
return Task.FromResult(Enumerable.Empty<Model>());
}
public override IReadOnlyCollection<Capability> GetModelCapabilities(Model model)
{
var modelName = model.Id.ToLowerInvariant().AsSpan();
// Claude 3.7 is able to do reasoning:
if(modelName.StartsWith("claude-3-7"))
return [
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
Capability.OPTIONAL_REASONING, Capability.FUNCTION_CALLING];
// All other 3.x models are able to process text and images as input:
if(modelName.StartsWith("claude-3-"))
return [
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING];
// Any other model is able to process text only:
return [
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING];
}
#endregion
private async Task<IEnumerable<Model>> LoadModels(CancellationToken token, string? apiKeyProvisional = null)
+16 -10
View File
@@ -4,6 +4,7 @@ using System.Text.Json;
using AIStudio.Chat;
using AIStudio.Settings;
using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Services;
namespace AIStudio.Provider;
@@ -13,6 +14,8 @@ namespace AIStudio.Provider;
/// </summary>
public abstract class BaseProvider : IProvider, ISecretId
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(BaseProvider).Namespace, nameof(BaseProvider));
/// <summary>
/// The HTTP client to use it for all requests.
/// </summary>
@@ -73,6 +76,9 @@ public abstract class BaseProvider : IProvider, ISecretId
/// <inheritdoc />
public abstract Task<IEnumerable<Model>> GetEmbeddingModels(string? apiKeyProvisional = null, CancellationToken token = default);
/// <inheritdoc />
public abstract IReadOnlyCollection<Capability> GetModelCapabilities(Model model);
#endregion
@@ -119,7 +125,7 @@ public abstract class BaseProvider : IProvider, ISecretId
if (nextResponse.StatusCode is HttpStatusCode.Forbidden)
{
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.Block, $"Tried to communicate with the LLM provider '{this.InstanceName}'. You might not be able to use this provider from your location. The provider message is: '{nextResponse.ReasonPhrase}'"));
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.Block, string.Format(TB("Tried to communicate with the LLM provider '{0}'. You might not be able to use this provider from your location. The provider message is: '{1}'"), this.InstanceName, nextResponse.ReasonPhrase)));
this.logger.LogError($"Failed request with status code {nextResponse.StatusCode} (message = '{nextResponse.ReasonPhrase}').");
errorMessage = nextResponse.ReasonPhrase;
break;
@@ -127,7 +133,7 @@ public abstract class BaseProvider : IProvider, ISecretId
if(nextResponse.StatusCode is HttpStatusCode.BadRequest)
{
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.CloudOff, $"Tried to communicate with the LLM provider '{this.InstanceName}'. The required message format might be changed. The provider message is: '{nextResponse.ReasonPhrase}'"));
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.CloudOff, string.Format(TB("Tried to communicate with the LLM provider '{0}'. The required message format might be changed. The provider message is: '{1}'"), this.InstanceName, nextResponse.ReasonPhrase)));
this.logger.LogError($"Failed request with status code {nextResponse.StatusCode} (message = '{nextResponse.ReasonPhrase}').");
errorMessage = nextResponse.ReasonPhrase;
break;
@@ -135,7 +141,7 @@ public abstract class BaseProvider : IProvider, ISecretId
if(nextResponse.StatusCode is HttpStatusCode.NotFound)
{
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.CloudOff, $"Tried to communicate with the LLM provider '{this.InstanceName}'. Something was not found. The provider message is: '{nextResponse.ReasonPhrase}'"));
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.CloudOff, string.Format(TB("Tried to communicate with the LLM provider '{0}'. Something was not found. The provider message is: '{1}'"), this.InstanceName, nextResponse.ReasonPhrase)));
this.logger.LogError($"Failed request with status code {nextResponse.StatusCode} (message = '{nextResponse.ReasonPhrase}').");
errorMessage = nextResponse.ReasonPhrase;
break;
@@ -143,7 +149,7 @@ public abstract class BaseProvider : IProvider, ISecretId
if(nextResponse.StatusCode is HttpStatusCode.Unauthorized)
{
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.Key, $"Tried to communicate with the LLM provider '{this.InstanceName}'. The API key might be invalid. The provider message is: '{nextResponse.ReasonPhrase}'"));
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.Key, string.Format(TB("Tried to communicate with the LLM provider '{0}'. The API key might be invalid. The provider message is: '{1}'"), this.InstanceName, nextResponse.ReasonPhrase)));
this.logger.LogError($"Failed request with status code {nextResponse.StatusCode} (message = '{nextResponse.ReasonPhrase}').");
errorMessage = nextResponse.ReasonPhrase;
break;
@@ -151,7 +157,7 @@ public abstract class BaseProvider : IProvider, ISecretId
if(nextResponse.StatusCode is HttpStatusCode.InternalServerError)
{
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.CloudOff, $"Tried to communicate with the LLM provider '{this.InstanceName}'. The server might be down or having issues. The provider message is: '{nextResponse.ReasonPhrase}'"));
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.CloudOff, string.Format(TB("Tried to communicate with the LLM provider '{0}'. The server might be down or having issues. The provider message is: '{1}'"), this.InstanceName, nextResponse.ReasonPhrase)));
this.logger.LogError($"Failed request with status code {nextResponse.StatusCode} (message = '{nextResponse.ReasonPhrase}').");
errorMessage = nextResponse.ReasonPhrase;
break;
@@ -159,7 +165,7 @@ public abstract class BaseProvider : IProvider, ISecretId
if(nextResponse.StatusCode is HttpStatusCode.ServiceUnavailable)
{
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.CloudOff, $"Tried to communicate with the LLM provider '{this.InstanceName}'. The provider is overloaded. The message is: '{nextResponse.ReasonPhrase}'"));
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.CloudOff, string.Format(TB("Tried to communicate with the LLM provider '{0}'. The provider is overloaded. The message is: '{1}'"), this.InstanceName, nextResponse.ReasonPhrase)));
this.logger.LogError($"Failed request with status code {nextResponse.StatusCode} (message = '{nextResponse.ReasonPhrase}').");
errorMessage = nextResponse.ReasonPhrase;
break;
@@ -176,7 +182,7 @@ public abstract class BaseProvider : IProvider, ISecretId
if(retry >= MAX_RETRIES || !string.IsNullOrWhiteSpace(errorMessage))
{
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.CloudOff, $"Tried to communicate with the LLM provider '{this.InstanceName}'. Even after {MAX_RETRIES} retries, there were some problems with the request. The provider message is: '{errorMessage}'"));
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.CloudOff, string.Format(TB("Tried to communicate with the LLM provider '{0}'. Even after {1} retries, there were some problems with the request. The provider message is: '{2}'"), this.InstanceName, MAX_RETRIES, errorMessage)));
return new HttpRateLimitedStreamResult(false, true, errorMessage ?? $"Failed after {MAX_RETRIES} retries; no provider message available", response);
}
@@ -204,7 +210,7 @@ public abstract class BaseProvider : IProvider, ISecretId
}
catch(Exception e)
{
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.Stream, $"Tried to communicate with the LLM provider '{this.InstanceName}'. There were some problems with the request. The provider message is: '{e.Message}'"));
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.Stream, string.Format(TB("Tried to communicate with the LLM provider '{0}'. There were some problems with the request. The provider message is: '{1}'"), this.InstanceName, e.Message)));
this.logger.LogError($"Failed to stream chat completion from {providerName} '{this.InstanceName}': {e.Message}");
}
@@ -221,7 +227,7 @@ public abstract class BaseProvider : IProvider, ISecretId
}
catch (Exception e)
{
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.Stream, $"Tried to stream the LLM provider '{this.InstanceName}' answer. There were some problems with the stream. The message is: '{e.Message}'"));
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.Stream, string.Format(TB("Tried to stream the LLM provider '{0}' answer. There were some problems with the stream. The message is: '{1}'"), this.InstanceName, e.Message)));
this.logger.LogWarning($"Failed to read the end-of-stream state from {providerName} '{this.InstanceName}': {e.Message}");
break;
}
@@ -242,7 +248,7 @@ public abstract class BaseProvider : IProvider, ISecretId
}
catch (Exception e)
{
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.Stream, $"Tried to stream the LLM provider '{this.InstanceName}' answer. Was not able to read the stream. The message is: '{e.Message}'"));
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.Stream, string.Format(TB("Tried to stream the LLM provider '{0}' answer. Was not able to read the stream. The message is: '{1}'"), this.InstanceName, e.Message)));
this.logger.LogError($"Failed to read the stream from {providerName} '{this.InstanceName}': {e.Message}");
break;
}
@@ -0,0 +1,150 @@
namespace AIStudio.Provider;
public static class CapabilitiesOpenSource
{
public static IReadOnlyCollection<Capability> GetCapabilities(Model model)
{
var modelName = model.Id.ToLowerInvariant().AsSpan();
//
// Checking for names in the case of open source models is a hard task.
// Let's assume we want to check for the llama 3.1 405b model.
//
// Here is a not complete list of how providers name this model:
// - Fireworks: accounts/fireworks/models/llama-v3p1-405b-instruct
// - Hugging Face -> Nebius AI Studio: meta-llama/Meta-Llama-3.1-405B-Instruct
// - Groq: llama-3.1-405b-instruct
// - LM Studio: llama-3.1-405b-instruct
// - Helmholtz Blablador: 1 - Llama3 405 the best general model
// - GWDG: Llama 3.1 405B Instruct
//
//
// Meta llama models:
//
if (modelName.IndexOf("llama") is not -1)
{
if (modelName.IndexOf("llama4") is not -1 ||
modelName.IndexOf("llama 4") is not -1 ||
modelName.IndexOf("llama-4") is not -1 ||
modelName.IndexOf("llama-v4") is not -1)
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING,
];
// The old vision models cannot do function calling:
if (modelName.IndexOf("vision") is not -1)
return [Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT, Capability.TEXT_OUTPUT];
//
// All models >= 3.1 are able to do function calling:
//
if (modelName.IndexOf("llama3.") is not -1 ||
modelName.IndexOf("llama 3.") is not -1 ||
modelName.IndexOf("llama-3.") is not -1 ||
modelName.IndexOf("llama-v3p") is not -1)
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING,
];
// All other llama models can only do text input and output:
return [Capability.TEXT_INPUT, Capability.TEXT_OUTPUT];
}
//
// DeepSeek models:
//
if (modelName.IndexOf("deepseek") is not -1)
{
if(modelName.IndexOf("deepseek-r1") is not -1 ||
modelName.IndexOf("deepseek r1") is not -1)
return [Capability.TEXT_INPUT, Capability.TEXT_OUTPUT, Capability.ALWAYS_REASONING];
return [Capability.TEXT_INPUT, Capability.TEXT_OUTPUT];
}
//
// Qwen models:
//
if (modelName.IndexOf("qwen") is not -1 || modelName.IndexOf("qwq") is not -1)
{
if (modelName.IndexOf("qwq") is not -1)
return [Capability.TEXT_INPUT, Capability.TEXT_OUTPUT, Capability.ALWAYS_REASONING];
return [Capability.TEXT_INPUT, Capability.TEXT_OUTPUT];
}
//
// Mistral models:
//
if (modelName.IndexOf("mistral") is not -1 ||
modelName.IndexOf("pixtral") is not -1)
{
if(modelName.IndexOf("pixtral") is not -1)
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING
];
if (modelName.IndexOf("3.1") is not -1)
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING
];
// Default:
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING
];
}
//
// Grok models:
//
if (modelName.IndexOf("grok") is not -1)
{
if(modelName.IndexOf("-vision-") is not -1)
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
];
if(modelName.StartsWith("grok-3-mini"))
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
Capability.ALWAYS_REASONING, Capability.FUNCTION_CALLING,
];
if(modelName.StartsWith("grok-3"))
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING,
];
}
// Default:
return [Capability.TEXT_INPUT, Capability.TEXT_OUTPUT];
}
}
@@ -0,0 +1,97 @@
namespace AIStudio.Provider;
/// <summary>
/// Represents the capabilities of an AI model.
/// </summary>
public enum Capability
{
/// <summary>
/// No capabilities specified.
/// </summary>
NONE,
/// <summary>
/// We don't know what the AI model can do.
/// </summary>
UNKNOWN,
/// <summary>
/// The AI model can perform text input.
/// </summary>
TEXT_INPUT,
/// <summary>
/// The AI model can perform audio input, such as music or sound.
/// </summary>
AUDIO_INPUT,
/// <summary>
/// The AI model can perform one image input, such as one photo or drawing.
/// </summary>
SINGLE_IMAGE_INPUT,
/// <summary>
/// The AI model can perform multiple images as input, such as multiple photos or drawings.
/// </summary>
MULTIPLE_IMAGE_INPUT,
/// <summary>
/// The AI model can perform speech input.
/// </summary>
SPEECH_INPUT,
/// <summary>
/// The AI model can perform video input, such as video files or streams.
/// </summary>
VIDEO_INPUT,
/// <summary>
/// The AI model can generate text output.
/// </summary>
TEXT_OUTPUT,
/// <summary>
/// The AI model can generate audio output, such as music or sound.
/// </summary>
AUDIO_OUTPUT,
/// <summary>
/// The AI model can generate image output, such as photos or drawings.
/// </summary>
IMAGE_OUTPUT,
/// <summary>
/// The AI model can generate speech output.
/// </summary>
SPEECH_OUTPUT,
/// <summary>
/// The AI model can generate video output.
/// </summary>
VIDEO_OUTPUT,
/// <summary>
/// The AI model can perform reasoning tasks.
/// </summary>
OPTIONAL_REASONING,
/// <summary>
/// The AI model always performs reasoning.
/// </summary>
ALWAYS_REASONING,
/// <summary>
/// The AI model can embed information or data.
/// </summary>
EMBEDDING,
/// <summary>
/// The AI model can perform in real-time.
/// </summary>
REALTIME,
/// <summary>
/// The AI model can perform function calling, such as invoking APIs or executing functions.
/// </summary>
FUNCTION_CALLING,
}
+10 -7
View File
@@ -1,9 +1,12 @@
using AIStudio.Settings;
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Provider;
public sealed record Confidence
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(Confidence).Namespace, nameof(Confidence));
public ConfidenceLevel Level { get; private init; } = ConfidenceLevel.UNKNOWN;
public string Region { get; private init; } = string.Empty;
@@ -29,42 +32,42 @@ public sealed record Confidence
public static readonly Confidence NONE = new()
{
Level = ConfidenceLevel.NONE,
Description = "No provider selected. Please select a provider to get see its confidence level.",
Description = TB("No provider selected. Please select a provider to get see its confidence level."),
};
public static readonly Confidence USA_HUB = new()
{
Level = ConfidenceLevel.UNKNOWN,
Description = "The provider operates its service from the USA and is subject to **U.S. jurisdiction**. In case of suspicion, authorities in the USA can access your data. Please inform yourself about the use of your data. We do not know if your data is safe.",
Description = TB("The provider operates its service from the USA and is subject to **U.S. jurisdiction**. In case of suspicion, authorities in the USA can access your data. Please inform yourself about the use of your data. We do not know if your data is safe."),
};
public static readonly Confidence UNKNOWN = new()
{
Level = ConfidenceLevel.UNKNOWN,
Description = "The trust level of this provider **has not yet** been thoroughly **investigated and evaluated**. We do not know if your data is safe.",
Description = TB("The trust level of this provider **has not yet** been thoroughly **investigated and evaluated**. We do not know if your data is safe."),
};
public static readonly Confidence USA_NO_TRAINING = new()
{
Level = ConfidenceLevel.MODERATE,
Description = "The provider operates its service from the USA and is subject to **US jurisdiction**. In case of suspicion, authorities in the USA can access your data. However, **your data is not used for training** purposes.",
Description = TB("The provider operates its service from the USA and is subject to **US jurisdiction**. In case of suspicion, authorities in the USA can access your data. However, **your data is not used for training** purposes."),
};
public static readonly Confidence CHINA_NO_TRAINING = new()
{
Level = ConfidenceLevel.MODERATE,
Description = "The provider operates its service from China. In case of suspicion, authorities in the respective countries of operation may access your data. However, **your data is not used for training** purposes.",
Description = TB("The provider operates its service from China. In case of suspicion, authorities in the respective countries of operation may access your data. However, **your data is not used for training** purposes."),
};
public static readonly Confidence GDPR_NO_TRAINING = new()
{
Level = ConfidenceLevel.MEDIUM,
Description = "The provider is located in the EU and is subject to the **GDPR** (General Data Protection Regulation). Additionally, the provider states that **your data is not used for training**.",
Description = TB("The provider is located in the EU and is subject to the **GDPR** (General Data Protection Regulation). Additionally, the provider states that **your data is not used for training**."),
};
public static readonly Confidence SELF_HOSTED = new()
{
Level = ConfidenceLevel.HIGH,
Description = "You or your organization operate the LLM locally or within your trusted network. In terms of data processing and security, this is the best possible way.",
Description = TB("You or your organization operate the LLM locally or within your trusted network. In terms of data processing and security, this is the best possible way."),
};
}
@@ -1,21 +1,24 @@
using AIStudio.Settings;
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Provider;
public static class ConfidenceLevelExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(ConfidenceLevelExtensions).Namespace, nameof(ConfidenceLevelExtensions));
public static string GetName(this ConfidenceLevel level) => level switch
{
ConfidenceLevel.NONE => "No provider selected",
ConfidenceLevel.NONE => TB("No provider selected"),
ConfidenceLevel.UNTRUSTED => "Untrusted",
ConfidenceLevel.VERY_LOW => "Very Low",
ConfidenceLevel.LOW => "Low",
ConfidenceLevel.MODERATE => "Moderate",
ConfidenceLevel.MEDIUM => "Medium",
ConfidenceLevel.HIGH => "High",
ConfidenceLevel.UNTRUSTED => TB("Untrusted"),
ConfidenceLevel.VERY_LOW => TB("Very Low"),
ConfidenceLevel.LOW => TB("Low"),
ConfidenceLevel.MODERATE => TB("Moderate"),
ConfidenceLevel.MEDIUM => TB("Medium"),
ConfidenceLevel.HIGH => TB("High"),
_ => "Unknown confidence level",
_ => TB("Unknown confidence level"),
};
public static string GetColor(this ConfidenceLevel level, SettingsManager settingsManager) => (level, settingsManager.IsDarkMode) switch
@@ -105,6 +105,27 @@ public sealed class ProviderDeepSeek(ILogger logger) : BaseProvider("https://api
{
return Task.FromResult(Enumerable.Empty<Model>());
}
public override IReadOnlyCollection<Capability> GetModelCapabilities(Model model)
{
var modelName = model.Id.ToLowerInvariant().AsSpan();
if(modelName.IndexOf("reasoner") is not -1)
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
Capability.ALWAYS_REASONING,
];
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
];
}
#endregion
@@ -106,6 +106,8 @@ public class ProviderFireworks(ILogger logger) : BaseProvider("https://api.firew
{
return Task.FromResult(Enumerable.Empty<Model>());
}
public override IReadOnlyCollection<Capability> GetModelCapabilities(Model model) => CapabilitiesOpenSource.GetCapabilities(model);
#endregion
}
@@ -107,6 +107,8 @@ public sealed class ProviderGWDG(ILogger logger) : BaseProvider("https://chat-ai
var models = await this.LoadModels(token, apiKeyProvisional);
return models.Where(model => model.Id.StartsWith("e5-", StringComparison.InvariantCultureIgnoreCase));
}
public override IReadOnlyCollection<Capability> GetModelCapabilities(Model model) => CapabilitiesOpenSource.GetCapabilities(model);
#endregion
@@ -98,7 +98,7 @@ public class ProviderGoogle(ILogger logger) : BaseProvider("https://generativela
return [];
return modelResponse.Models.Where(model =>
model.Name.StartsWith("models/gemini-", StringComparison.OrdinalIgnoreCase))
model.Name.StartsWith("models/gemini-", StringComparison.OrdinalIgnoreCase) && !model.Name.Contains("embed"))
.Select(n => new Provider.Model(n.Name.Replace("models/", string.Empty), n.DisplayName));
}
@@ -115,10 +115,93 @@ public class ProviderGoogle(ILogger logger) : BaseProvider("https://generativela
return [];
return modelResponse.Models.Where(model =>
model.Name.StartsWith("models/text-embedding-", StringComparison.InvariantCultureIgnoreCase))
model.Name.StartsWith("models/text-embedding-", StringComparison.OrdinalIgnoreCase) ||
model.Name.StartsWith("models/gemini-embed", StringComparison.OrdinalIgnoreCase))
.Select(n => new Provider.Model(n.Name.Replace("models/", string.Empty), n.DisplayName));
}
public override IReadOnlyCollection<Capability> GetModelCapabilities(Provider.Model model)
{
var modelName = model.Id.ToLowerInvariant().AsSpan();
if (modelName.IndexOf("gemini-") is not -1)
{
// Reasoning models:
if (modelName.IndexOf("gemini-2.5") is not -1)
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT, Capability.AUDIO_INPUT,
Capability.SPEECH_INPUT, Capability.VIDEO_INPUT,
Capability.TEXT_OUTPUT,
Capability.ALWAYS_REASONING, Capability.FUNCTION_CALLING,
];
// Image generation:
if(modelName.IndexOf("-2.0-flash-preview-image-") is not -1)
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT, Capability.AUDIO_INPUT,
Capability.SPEECH_INPUT, Capability.VIDEO_INPUT,
Capability.TEXT_OUTPUT, Capability.IMAGE_OUTPUT,
];
// Realtime model:
if(modelName.IndexOf("-2.0-flash-live-") is not -1)
return
[
Capability.TEXT_INPUT, Capability.AUDIO_INPUT, Capability.SPEECH_INPUT,
Capability.VIDEO_INPUT,
Capability.TEXT_OUTPUT, Capability.SPEECH_OUTPUT,
Capability.FUNCTION_CALLING,
];
// The 2.0 flash models cannot call functions:
if(modelName.IndexOf("-2.0-flash-") is not -1)
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT, Capability.AUDIO_INPUT,
Capability.SPEECH_INPUT, Capability.VIDEO_INPUT,
Capability.TEXT_OUTPUT,
];
// The old 1.0 pro vision model:
if(modelName.IndexOf("pro-vision") is not -1)
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
];
// Default to all other Gemini models:
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT, Capability.AUDIO_INPUT,
Capability.SPEECH_INPUT, Capability.VIDEO_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING,
];
}
// Default for all other models:
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING,
];
}
#endregion
private async Task<ModelsResponse> LoadModels(CancellationToken token, string? apiKeyProvisional = null)
@@ -109,6 +109,8 @@ public class ProviderGroq(ILogger logger) : BaseProvider("https://api.groq.com/o
{
return Task.FromResult(Enumerable.Empty<Model>());
}
public override IReadOnlyCollection<Capability> GetModelCapabilities(Model model) => CapabilitiesOpenSource.GetCapabilities(model);
#endregion
@@ -111,6 +111,8 @@ public sealed class ProviderHelmholtz(ILogger logger) : BaseProvider("https://ap
model.Id.StartsWith("text-", StringComparison.InvariantCultureIgnoreCase) ||
model.Id.Contains("gritlm", StringComparison.InvariantCultureIgnoreCase));
}
public override IReadOnlyCollection<Capability> GetModelCapabilities(Model model) => CapabilitiesOpenSource.GetCapabilities(model);
#endregion
@@ -110,6 +110,8 @@ public sealed class ProviderHuggingFace : BaseProvider
{
return Task.FromResult(Enumerable.Empty<Model>());
}
public override IReadOnlyCollection<Capability> GetModelCapabilities(Model model) => CapabilitiesOpenSource.GetCapabilities(model);
#endregion
}
@@ -63,4 +63,11 @@ public interface IProvider
/// <param name="token">The cancellation token.</param>
/// <returns>The list of embedding models.</returns>
public Task<IEnumerable<Model>> GetEmbeddingModels(string? apiKeyProvisional = null, CancellationToken token = default);
/// <summary>
/// Get the capabilities of a model.
/// </summary>
/// <param name="model">The model to get the capabilities for.</param>
/// <returns>The capabilities of the model.</returns>
public IReadOnlyCollection<Capability> GetModelCapabilities(Model model);
}
@@ -12,6 +12,7 @@ using AIStudio.Provider.OpenAI;
using AIStudio.Provider.SelfHosted;
using AIStudio.Provider.X;
using AIStudio.Settings;
using AIStudio.Tools.PluginSystem;
using Host = AIStudio.Provider.SelfHosted.Host;
@@ -19,6 +20,8 @@ namespace AIStudio.Provider;
public static class LLMProvidersExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(LLMProvidersExtensions).Namespace, nameof(LLMProvidersExtensions));
/// <summary>
/// Returns the human-readable name of the provider.
/// </summary>
@@ -26,7 +29,7 @@ public static class LLMProvidersExtensions
/// <returns>The human-readable name of the provider.</returns>
public static string ToName(this LLMProviders llmProvider) => llmProvider switch
{
LLMProviders.NONE => "No provider selected",
LLMProviders.NONE => TB("No provider selected"),
LLMProviders.OPEN_AI => "OpenAI",
LLMProviders.ANTHROPIC => "Anthropic",
@@ -40,12 +43,12 @@ public static class LLMProvidersExtensions
LLMProviders.FIREWORKS => "Fireworks.ai",
LLMProviders.HUGGINGFACE => "Hugging Face",
LLMProviders.SELF_HOSTED => "Self-hosted",
LLMProviders.SELF_HOSTED => TB("Self-hosted"),
LLMProviders.HELMHOLTZ => "Helmholtz Blablador",
LLMProviders.GWDG => "GWDG SAIA",
_ => "Unknown",
_ => TB("Unknown"),
};
/// <summary>
@@ -121,7 +121,53 @@ public sealed class ProviderMistral(ILogger logger) : BaseProvider("https://api.
{
return Task.FromResult(Enumerable.Empty<Provider.Model>());
}
public override IReadOnlyCollection<Capability> GetModelCapabilities(Provider.Model model)
{
var modelName = model.Id.ToLowerInvariant().AsSpan();
// Pixtral models are able to do process images:
if (modelName.IndexOf("pixtral") is not -1)
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING,
];
// Mistral medium:
if (modelName.IndexOf("mistral-medium-") is not -1)
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING,
];
// Mistral small:
if (modelName.IndexOf("mistral-small-") is not -1)
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING,
];
// Mistral saba:
if (modelName.IndexOf("mistral-saba-") is not -1)
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
];
// Default:
return CapabilitiesOpenSource.GetCapabilities(model);
}
#endregion
private async Task<ModelsResponse> LoadModelList(string? apiKeyProvisional, CancellationToken token)
+5 -1
View File
@@ -1,3 +1,5 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Provider;
/// <summary>
@@ -7,6 +9,8 @@ namespace AIStudio.Provider;
/// <param name="DisplayName">The model's display name.</param>
public readonly record struct Model(string Id, string? DisplayName)
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(Model).Namespace, nameof(Model));
#region Overrides of ValueType
public override string ToString()
@@ -17,7 +21,7 @@ public readonly record struct Model(string Id, string? DisplayName)
if(!string.IsNullOrWhiteSpace(this.Id))
return this.Id;
return "no model selected";
return TB("no model selected");
}
#endregion
@@ -31,5 +31,7 @@ public class NoProvider : IProvider
yield break;
}
public IReadOnlyCollection<Capability> GetModelCapabilities(Model model) => [ Capability.NONE ];
#endregion
}
@@ -127,7 +127,8 @@ public sealed class ProviderOpenAI(ILogger logger) : BaseProvider("https://api.o
!model.Id.Contains("realtime", StringComparison.OrdinalIgnoreCase) &&
!model.Id.Contains("audio", StringComparison.OrdinalIgnoreCase) &&
!model.Id.Contains("tts", StringComparison.OrdinalIgnoreCase) &&
!model.Id.Contains("transcribe", StringComparison.OrdinalIgnoreCase));
!model.Id.Contains("transcribe", StringComparison.OrdinalIgnoreCase) &&
!model.Id.Contains("o1-pro", StringComparison.OrdinalIgnoreCase));
}
/// <inheritdoc />
@@ -141,7 +142,70 @@ public sealed class ProviderOpenAI(ILogger logger) : BaseProvider("https://api.o
{
return this.LoadModels(["text-embedding-"], token, apiKeyProvisional);
}
public override IReadOnlyCollection<Capability> GetModelCapabilities(Model model)
{
var modelName = model.Id.ToLowerInvariant().AsSpan();
if (modelName.StartsWith("o1-mini"))
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
Capability.ALWAYS_REASONING,
];
if (modelName.StartsWith("o3-mini"))
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
Capability.ALWAYS_REASONING, Capability.FUNCTION_CALLING
];
if (modelName.StartsWith("o4-mini") || modelName.StartsWith("o1") || modelName.StartsWith("o3"))
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
Capability.ALWAYS_REASONING, Capability.FUNCTION_CALLING
];
if(modelName.StartsWith("gpt-3.5"))
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
];
if(modelName.StartsWith("gpt-4-turbo"))
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING
];
if(modelName is "gpt-4" || modelName.StartsWith("gpt-4-"))
return
[
Capability.TEXT_INPUT,
Capability.TEXT_OUTPUT,
];
return
[
Capability.TEXT_INPUT, Capability.MULTIPLE_IMAGE_INPUT,
Capability.TEXT_OUTPUT,
Capability.FUNCTION_CALLING,
];
}
#endregion
private async Task<IEnumerable<Model>> LoadModels(string[] prefixes, CancellationToken token, string? apiKeyProvisional = null)
@@ -87,8 +87,7 @@ public sealed class ProviderSelfHosted(ILogger logger, Host host, string hostnam
yield break;
}
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
public override async Task<IEnumerable<Provider.Model>> GetTextModels(string? apiKeyProvisional = null, CancellationToken token = default)
{
try
@@ -139,7 +138,9 @@ public sealed class ProviderSelfHosted(ILogger logger, Host host, string hostnam
return [];
}
}
public override IReadOnlyCollection<Capability> GetModelCapabilities(Provider.Model model) => CapabilitiesOpenSource.GetCapabilities(model);
#endregion
private async Task<IEnumerable<Provider.Model>> LoadModels(string[] ignorePhrases, string[] filterPhrases, CancellationToken token, string? apiKeyProvisional = null)
@@ -110,6 +110,8 @@ public sealed class ProviderX(ILogger logger) : BaseProvider("https://api.x.ai/v
{
return Task.FromResult<IEnumerable<Model>>([]);
}
public override IReadOnlyCollection<Capability> GetModelCapabilities(Model model) => CapabilitiesOpenSource.GetCapabilities(model);
#endregion
@@ -26,6 +26,8 @@ public readonly record struct ConfigurationSelectData<T>(string Name, T Value);
/// </summary>
public static class ConfigurationSelectDataFactory
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(ConfigurationSelectDataFactory).Namespace, nameof(ConfigurationSelectDataFactory));
public static IEnumerable<ConfigurationSelectData<LangBehavior>> GetLangBehaviorData()
{
foreach (var behavior in Enum.GetValues<LangBehavior>())
@@ -43,65 +45,65 @@ public static class ConfigurationSelectDataFactory
public static IEnumerable<ConfigurationSelectData<LoadingChatProviderBehavior>> GetLoadingChatProviderBehavior()
{
yield return new("When possible, use the LLM provider which was used for each chat in the first place", LoadingChatProviderBehavior.USE_CHAT_PROVIDER_IF_AVAILABLE);
yield return new("Use the latest LLM provider, which was used before; use the default chat provider initially", LoadingChatProviderBehavior.ALWAYS_USE_LATEST_CHAT_PROVIDER);
yield return new("Always use the default chat provider when loading chats", LoadingChatProviderBehavior.ALWAYS_USE_DEFAULT_CHAT_PROVIDER);
yield return new(TB("When possible, use the LLM provider which was used for each chat in the first place"), LoadingChatProviderBehavior.USE_CHAT_PROVIDER_IF_AVAILABLE);
yield return new(TB("Use the latest LLM provider, which was used before; use the default chat provider initially"), LoadingChatProviderBehavior.ALWAYS_USE_LATEST_CHAT_PROVIDER);
yield return new(TB("Always use the default chat provider when loading chats"), LoadingChatProviderBehavior.ALWAYS_USE_DEFAULT_CHAT_PROVIDER);
}
public static IEnumerable<ConfigurationSelectData<AddChatProviderBehavior>> GetAddChatProviderBehavior()
{
yield return new("Use the latest LLM provider, which was used before; use the default chat provider initially", AddChatProviderBehavior.ADDED_CHATS_USE_LATEST_PROVIDER);
yield return new("Always use the default chat provider for new chats", AddChatProviderBehavior.ADDED_CHATS_USE_DEFAULT_PROVIDER);
yield return new(TB("Use the latest LLM provider, which was used before; use the default chat provider initially"), AddChatProviderBehavior.ADDED_CHATS_USE_LATEST_PROVIDER);
yield return new(TB("Always use the default chat provider for new chats"), AddChatProviderBehavior.ADDED_CHATS_USE_DEFAULT_PROVIDER);
}
public static IEnumerable<ConfigurationSelectData<SendBehavior>> GetSendBehaviorData()
{
yield return new("No key is sending the input", SendBehavior.NO_KEY_IS_SENDING);
yield return new("Modifier key + enter is sending the input", SendBehavior.MODIFER_ENTER_IS_SENDING);
yield return new("Enter is sending the input", SendBehavior.ENTER_IS_SENDING);
yield return new(TB("No key is sending the input"), SendBehavior.NO_KEY_IS_SENDING);
yield return new(TB("Modifier key + enter is sending the input"), SendBehavior.MODIFER_ENTER_IS_SENDING);
yield return new(TB("Enter is sending the input"), SendBehavior.ENTER_IS_SENDING);
}
public static IEnumerable<ConfigurationSelectData<UpdateBehavior>> GetUpdateBehaviorData()
{
yield return new("No automatic update checks", UpdateBehavior.NO_CHECK);
yield return new("Once at startup", UpdateBehavior.ONCE_STARTUP);
yield return new("Check every hour", UpdateBehavior.HOURLY);
yield return new("Check every day", UpdateBehavior.DAILY);
yield return new ("Check every week", UpdateBehavior.WEEKLY);
yield return new(TB("No automatic update checks"), UpdateBehavior.NO_CHECK);
yield return new(TB("Once at startup"), UpdateBehavior.ONCE_STARTUP);
yield return new(TB("Check every hour"), UpdateBehavior.HOURLY);
yield return new(TB("Check every day"), UpdateBehavior.DAILY);
yield return new (TB("Check every week"), UpdateBehavior.WEEKLY);
}
public static IEnumerable<ConfigurationSelectData<WorkspaceStorageBehavior>> GetWorkspaceStorageBehaviorData()
{
yield return new("Disable workspaces", WorkspaceStorageBehavior.DISABLE_WORKSPACES);
yield return new("Store chats automatically", WorkspaceStorageBehavior.STORE_CHATS_AUTOMATICALLY);
yield return new("Store chats manually", WorkspaceStorageBehavior.STORE_CHATS_MANUALLY);
yield return new(TB("Disable workspaces"), WorkspaceStorageBehavior.DISABLE_WORKSPACES);
yield return new(TB("Store chats automatically"), WorkspaceStorageBehavior.STORE_CHATS_AUTOMATICALLY);
yield return new(TB("Store chats manually"), WorkspaceStorageBehavior.STORE_CHATS_MANUALLY);
}
public static IEnumerable<ConfigurationSelectData<WorkspaceStorageTemporaryMaintenancePolicy>> GetWorkspaceStorageTemporaryMaintenancePolicyData()
{
yield return new("No automatic maintenance for temporary chats", WorkspaceStorageTemporaryMaintenancePolicy.NO_AUTOMATIC_MAINTENANCE);
yield return new("Delete temporary chats older than 7 days", WorkspaceStorageTemporaryMaintenancePolicy.DELETE_OLDER_THAN_7_DAYS);
yield return new("Delete temporary chats older than 30 days", WorkspaceStorageTemporaryMaintenancePolicy.DELETE_OLDER_THAN_30_DAYS);
yield return new("Delete temporary chats older than 90 days", WorkspaceStorageTemporaryMaintenancePolicy.DELETE_OLDER_THAN_90_DAYS);
yield return new("Delete temporary chats older than 180 days", WorkspaceStorageTemporaryMaintenancePolicy.DELETE_OLDER_THAN_180_DAYS);
yield return new("Delete temporary chats older than 1 year", WorkspaceStorageTemporaryMaintenancePolicy.DELETE_OLDER_THAN_365_DAYS);
yield return new(TB("No automatic maintenance for disappearing chats; old chats will never be deleted"), WorkspaceStorageTemporaryMaintenancePolicy.NO_AUTOMATIC_MAINTENANCE);
yield return new(TB("Delete disappearing chats older than 7 days"), WorkspaceStorageTemporaryMaintenancePolicy.DELETE_OLDER_THAN_7_DAYS);
yield return new(TB("Delete disappearing chats older than 30 days"), WorkspaceStorageTemporaryMaintenancePolicy.DELETE_OLDER_THAN_30_DAYS);
yield return new(TB("Delete disappearing chats older than 90 days"), WorkspaceStorageTemporaryMaintenancePolicy.DELETE_OLDER_THAN_90_DAYS);
yield return new(TB("Delete disappearing chats older than 180 days"), WorkspaceStorageTemporaryMaintenancePolicy.DELETE_OLDER_THAN_180_DAYS);
yield return new(TB("Delete disappearing chats older than 1 year"), WorkspaceStorageTemporaryMaintenancePolicy.DELETE_OLDER_THAN_365_DAYS);
}
public static IEnumerable<ConfigurationSelectData<WorkspaceDisplayBehavior>> GetWorkspaceDisplayBehaviorData()
{
yield return new("Toggle the overlay: the chat uses all the space, workspaces are temporarily shown", WorkspaceDisplayBehavior.TOGGLE_OVERLAY);
yield return new("Toggle the sidebar: show the workspaces next to the chat when desired", WorkspaceDisplayBehavior.TOGGLE_SIDEBAR);
yield return new("Sidebar is always visible: show the workspaces next to the chat all the time", WorkspaceDisplayBehavior.SIDEBAR_ALWAYS_VISIBLE);
yield return new(TB("Toggle the overlay: the chat uses all the space, workspaces are temporarily shown"), WorkspaceDisplayBehavior.TOGGLE_OVERLAY);
yield return new(TB("Toggle the sidebar: show the workspaces next to the chat when desired"), WorkspaceDisplayBehavior.TOGGLE_SIDEBAR);
yield return new(TB("Sidebar is always visible: show the workspaces next to the chat all the time"), WorkspaceDisplayBehavior.SIDEBAR_ALWAYS_VISIBLE);
}
public static IEnumerable<ConfigurationSelectData<PreviewVisibility>> GetPreviewVisibility()
{
yield return new("All preview features are hidden", PreviewVisibility.NONE);
yield return new("Also show features ready for release; these should be stable", PreviewVisibility.RELEASE_CANDIDATE);
yield return new("Also show features in beta: these are almost ready for release; expect some bugs", PreviewVisibility.BETA);
yield return new("Also show features in alpha: these are in development; expect bugs and missing features", PreviewVisibility.ALPHA);
yield return new("Show also prototype features: these are works in progress; expect bugs and missing features", PreviewVisibility.PROTOTYPE);
yield return new("Show also experimental features: these are experimental; expect bugs, missing features, many changes", PreviewVisibility.EXPERIMENTAL);
yield return new(TB("All preview features are hidden"), PreviewVisibility.NONE);
yield return new(TB("Also show features ready for release; these should be stable"), PreviewVisibility.RELEASE_CANDIDATE);
yield return new(TB("Also show features in beta: these are almost ready for release; expect some bugs"), PreviewVisibility.BETA);
yield return new(TB("Also show features in alpha: these are in development; expect bugs and missing features"), PreviewVisibility.ALPHA);
yield return new(TB("Show also prototype features: these are works in progress; expect bugs and missing features"), PreviewVisibility.PROTOTYPE);
yield return new(TB("Show also experimental features: these are experimental; expect bugs, missing features, many changes"), PreviewVisibility.EXPERIMENTAL);
}
public static IEnumerable<ConfigurationSelectData<PreviewFeatures>> GetPreviewFeaturesData(SettingsManager settingsManager)
@@ -118,10 +120,10 @@ public static class ConfigurationSelectDataFactory
public static IEnumerable<ConfigurationSelectData<NavBehavior>> GetNavBehaviorData()
{
yield return new("Navigation expands on mouse hover", NavBehavior.EXPAND_ON_HOVER);
yield return new("Navigation never expands, but there are tooltips", NavBehavior.NEVER_EXPAND_USE_TOOLTIPS);
yield return new("Navigation never expands, no tooltips", NavBehavior.NEVER_EXPAND_NO_TOOLTIPS);
yield return new("Always expand navigation", NavBehavior.ALWAYS_EXPAND);
yield return new(TB("Navigation expands on mouse hover"), NavBehavior.EXPAND_ON_HOVER);
yield return new(TB("Navigation never expands, but there are tooltips"), NavBehavior.NEVER_EXPAND_USE_TOOLTIPS);
yield return new(TB("Navigation never expands, no tooltips"), NavBehavior.NEVER_EXPAND_NO_TOOLTIPS);
yield return new(TB("Always expand navigation"), NavBehavior.ALWAYS_EXPAND);
}
public static IEnumerable<ConfigurationSelectData<IconSources>> GetIconSourcesData()
@@ -140,7 +142,7 @@ public static class ConfigurationSelectDataFactory
{
foreach (var language in Enum.GetValues<CommonLanguages>())
if(language is CommonLanguages.AS_IS)
yield return new("Not yet specified", language);
yield return new(TB("Not yet specified"), language);
else
yield return new(language.Name(), language);
}
@@ -149,7 +151,7 @@ public static class ConfigurationSelectDataFactory
{
foreach (var language in Enum.GetValues<CommonLanguages>())
if(language is CommonLanguages.AS_IS)
yield return new("Do not specify the language", language);
yield return new(TB("Do not specify the language"), language);
else
yield return new(language.Name(), language);
}
@@ -211,7 +213,7 @@ public static class ConfigurationSelectDataFactory
foreach (var level in Enum.GetValues<ConfidenceLevel>())
{
if(level is ConfidenceLevel.NONE)
yield return new("No minimum confidence level chosen", level);
yield return new(TB("No minimum confidence level chosen"), level);
if(level < minimumLevel)
continue;
@@ -1,25 +1,29 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Settings.DataModel;
public static class DataSourceSecurityExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(DataSourceSecurityExtensions).Namespace, nameof(DataSourceSecurityExtensions));
public static string ToSelectionText(this DataSourceSecurity security) => security switch
{
DataSourceSecurity.NOT_SPECIFIED => "Please select a security policy",
DataSourceSecurity.NOT_SPECIFIED => TB("Please select a security policy"),
DataSourceSecurity.ALLOW_ANY => "This data source can be used with any LLM provider. Your data may be sent to a cloud-based provider.",
DataSourceSecurity.SELF_HOSTED => "This data source can only be used with a self-hosted LLM provider. Your data will not be sent to any cloud-based provider.",
DataSourceSecurity.ALLOW_ANY => TB("This data source can be used with any LLM provider. Your data may be sent to a cloud-based provider."),
DataSourceSecurity.SELF_HOSTED => TB("This data source can only be used with a self-hosted LLM provider. Your data will not be sent to any cloud-based provider."),
_ => "Unknown security policy"
_ => TB("Unknown security policy")
};
public static string ToInfoText(this DataSourceSecurity security) => security switch
{
DataSourceSecurity.NOT_SPECIFIED => "The security of the data source is not specified yet. You cannot use this data source until you specify a security policy.",
DataSourceSecurity.NOT_SPECIFIED => TB("The security of the data source is not specified yet. You cannot use this data source until you specify a security policy."),
DataSourceSecurity.ALLOW_ANY => "This data source can be used with any LLM provider. Your data may be sent to a cloud-based provider.",
DataSourceSecurity.SELF_HOSTED => "This data source can only be used with a self-hosted LLM provider. Your data will not be sent to any cloud-based provider.",
DataSourceSecurity.ALLOW_ANY => TB("This data source can be used with any LLM provider. Your data may be sent to a cloud-based provider."),
DataSourceSecurity.SELF_HOSTED => TB("This data source can only be used with a self-hosted LLM provider. Your data will not be sent to any cloud-based provider."),
_ => "Unknown security policy"
_ => TB("Unknown security policy")
};
public static TextColor GetColor(this DataSourceSecurity security) => security switch
@@ -1,3 +1,5 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Settings.DataModel;
/// <summary>
@@ -5,6 +7,8 @@ namespace AIStudio.Settings.DataModel;
/// </summary>
public static class DataSourceTypeExtension
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(DataSourceTypeExtension).Namespace, nameof(DataSourceTypeExtension));
/// <summary>
/// Get the display name of the data source type.
/// </summary>
@@ -12,10 +16,10 @@ public static class DataSourceTypeExtension
/// <returns>The display name of the data source type.</returns>
public static string GetDisplayName(this DataSourceType type) => type switch
{
DataSourceType.LOCAL_FILE => "Local File",
DataSourceType.LOCAL_DIRECTORY => "Local Directory",
DataSourceType.ERI_V1 => "External ERI Server (v1)",
DataSourceType.LOCAL_FILE => TB("Local File"),
DataSourceType.LOCAL_DIRECTORY => TB("Local Directory"),
DataSourceType.ERI_V1 => TB("External ERI Server (v1)"),
_ => "None",
_ => TB("None"),
};
}
@@ -0,0 +1,16 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Settings.DataModel;
public static class LangBehaviorExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(LangBehaviorExtensions).Namespace, nameof(LangBehaviorExtensions));
public static string Name(this LangBehavior langBehavior) => langBehavior switch
{
LangBehavior.AUTO => TB("Choose the language automatically, based on your system language."),
LangBehavior.MANUAL => TB("Choose the language manually."),
_ => TB("Unknown option")
};
}
@@ -1,12 +0,0 @@
namespace AIStudio.Settings.DataModel;
public static class LangBehaviorExtensions
{
public static string Name(this LangBehavior langBehavior) => langBehavior switch
{
LangBehavior.AUTO => "Choose the language automatically, based on your system language.",
LangBehavior.MANUAL => "Choose the language manually.",
_ => "Unknown option"
};
}
@@ -10,4 +10,5 @@ public enum PreviewFeatures
PRE_RAG_2024,
PRE_PLUGINS_2025,
PRE_READ_PDF_2025,
}
@@ -1,14 +1,20 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Settings.DataModel;
public static class PreviewFeaturesExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(PreviewFeaturesExtensions).Namespace, nameof(PreviewFeaturesExtensions));
public static string GetPreviewDescription(this PreviewFeatures feature) => feature switch
{
PreviewFeatures.PRE_WRITER_MODE_2024 => "Writer Mode: Experiments about how to write long texts using AI",
PreviewFeatures.PRE_RAG_2024 => "RAG: Preview of our RAG implementation where you can refer your files or integrate enterprise data within your company",
PreviewFeatures.PRE_PLUGINS_2025 => "Plugins: Preview of our plugin system where you can extend the functionality of the app",
PreviewFeatures.PRE_WRITER_MODE_2024 => TB("Writer Mode: Experiments about how to write long texts using AI"),
PreviewFeatures.PRE_RAG_2024 => TB("RAG: Preview of our RAG implementation where you can refer your files or integrate enterprise data within your company"),
_ => "Unknown preview feature"
PreviewFeatures.PRE_PLUGINS_2025 => TB("Plugins: Preview of our plugin system where you can extend the functionality of the app"),
PreviewFeatures.PRE_READ_PDF_2025 => TB("Read PDF: Preview of our PDF reading system where you can read and extract text from PDF files"),
_ => TB("Unknown preview feature")
};
public static bool IsEnabled(this PreviewFeatures feature, SettingsManager settingsManager) => settingsManager.ConfigurationData.App.EnabledPreviewFeatures.Contains(feature);
@@ -19,6 +19,7 @@ public static class PreviewVisibilityExtensions
if (visibility >= PreviewVisibility.PROTOTYPE)
{
features.Add(PreviewFeatures.PRE_READ_PDF_2025);
features.Add(PreviewFeatures.PRE_RAG_2024);
}
@@ -1,12 +1,16 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Settings.DataModel;
public static class SendToChatDataSourceBehaviorExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(SendToChatDataSourceBehaviorExtensions).Namespace, nameof(SendToChatDataSourceBehaviorExtensions));
public static string Description(this SendToChatDataSourceBehavior behavior) => behavior switch
{
SendToChatDataSourceBehavior.NO_DATA_SOURCES => "Use no data sources, when sending an assistant result to a chat",
SendToChatDataSourceBehavior.APPLY_STANDARD_CHAT_DATA_SOURCE_OPTIONS => "Apply standard chat data source options, when sending an assistant result to a chat",
SendToChatDataSourceBehavior.NO_DATA_SOURCES => TB("Use no data sources, when sending an assistant result to a chat"),
SendToChatDataSourceBehavior.APPLY_STANDARD_CHAT_DATA_SOURCE_OPTIONS => TB("Apply standard chat data source options, when sending an assistant result to a chat"),
_ => "Unknown behavior",
_ => TB("Unknown behavior"),
};
}
@@ -1,13 +1,17 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Settings.DataModel;
public static class ThemesExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(ThemesExtensions).Namespace, nameof(ThemesExtensions));
public static string GetName(this Themes theme) => theme switch
{
Themes.SYSTEM => "Synchronized with the operating system settings",
Themes.LIGHT => "Always use light theme",
Themes.DARK => "Always use dark theme",
Themes.SYSTEM => TB("Synchronized with the operating system settings"),
Themes.LIGHT => TB("Always use light theme"),
Themes.DARK => TB("Always use dark theme"),
_ => "Unknown setting",
_ => TB("Unknown setting"),
};
}
+5 -1
View File
@@ -1,10 +1,14 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Settings;
public readonly record struct Profile(uint Num, string Id, string Name, string NeedToKnow, string Actions)
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(Profile).Namespace, nameof(Profile));
public static readonly Profile NO_PROFILE = new()
{
Name = "Use no profile",
Name = TB("Use no profile"),
NeedToKnow = string.Empty,
Actions = string.Empty,
Id = Guid.Empty.ToString(),
@@ -13,7 +13,7 @@ namespace AIStudio.Settings;
/// <summary>
/// The settings manager.
/// </summary>
public sealed class SettingsManager(ILogger<SettingsManager> logger, RustService rustService)
public sealed class SettingsManager
{
private const string SETTINGS_FILENAME = "settings.json";
@@ -23,9 +23,19 @@ public sealed class SettingsManager(ILogger<SettingsManager> logger, RustService
Converters = { new TolerantEnumConverter() },
};
private readonly ILogger<SettingsManager> logger = logger;
private readonly RustService rustService = rustService;
private readonly ILogger<SettingsManager> logger;
private readonly RustService rustService;
/// <summary>
/// The settings manager.
/// </summary>
public SettingsManager(ILogger<SettingsManager> logger, RustService rustService)
{
this.logger = logger;
this.rustService = rustService;
this.logger.LogInformation("Settings manager created.");
}
/// <summary>
/// The directory where the configuration files are stored.
/// </summary>
@@ -1,16 +1,19 @@
using AIStudio.Tools.ERIClient.DataModel;
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Tools;
public static class AuthMethodsV1Extensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(AuthMethodsV1Extensions).Namespace, nameof(AuthMethodsV1Extensions));
public static string DisplayName(this AuthMethod authMethod) => authMethod switch
{
AuthMethod.NONE => "None",
AuthMethod.USERNAME_PASSWORD => "Username & Password",
AuthMethod.KERBEROS => "SSO (Kerberos)",
AuthMethod.TOKEN => "Access Token",
AuthMethod.NONE => TB("None"),
AuthMethod.USERNAME_PASSWORD => TB("Username & Password"),
AuthMethod.KERBEROS => TB("SSO (Kerberos)"),
AuthMethod.TOKEN => TB("Access Token"),
_ => "Unknown authentication method",
_ => TB("Unknown authentication method"),
};
}
@@ -1,23 +1,27 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Tools;
public static class CommonLanguageExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(CommonLanguageExtensions).Namespace, nameof(CommonLanguageExtensions));
public static string Name(this CommonLanguages language) => language switch
{
CommonLanguages.AS_IS => "Do not change the language",
CommonLanguages.AS_IS => TB("Do not change the language"),
CommonLanguages.EN_US => "English (US)",
CommonLanguages.EN_GB => "English (UK)",
CommonLanguages.ZH_CN => "Chinese (Simplified)",
CommonLanguages.HI_IN => "Hindi (India)",
CommonLanguages.ES_ES => "Spanish (Spain)",
CommonLanguages.FR_FR => "French (France)",
CommonLanguages.DE_DE => "German (Germany)",
CommonLanguages.DE_AT => "German (Austria)",
CommonLanguages.DE_CH => "German (Switzerland)",
CommonLanguages.JA_JP => "Japanese (Japan)",
CommonLanguages.EN_US => TB("English (US)"),
CommonLanguages.EN_GB => TB("English (UK)"),
CommonLanguages.ZH_CN => TB("Chinese (Simplified)"),
CommonLanguages.HI_IN => TB("Hindi (India)"),
CommonLanguages.ES_ES => TB("Spanish (Spain)"),
CommonLanguages.FR_FR => TB("French (France)"),
CommonLanguages.DE_DE => TB("German (Germany)"),
CommonLanguages.DE_AT => TB("German (Austria)"),
CommonLanguages.DE_CH => TB("German (Switzerland)"),
CommonLanguages.JA_JP => TB("Japanese (Japan)"),
_ => "Other",
_ => TB("Other"),
};
public static string ToIETFTag(this CommonLanguages language) => language switch
@@ -56,7 +60,7 @@ public static class CommonLanguageExtensions
public static string NameSelecting(this CommonLanguages language)
{
if(language is CommonLanguages.AS_IS)
return "Please select the target language";
return TB("Please select the target language");
return language.Name();
}
@@ -64,7 +68,7 @@ public static class CommonLanguageExtensions
public static string NameSelectingOptional(this CommonLanguages language)
{
if(language is CommonLanguages.AS_IS)
return "Do not specify the language";
return TB("Do not specify the language");
return language.Name();
}
@@ -2,11 +2,14 @@ using System.Diagnostics.CodeAnalysis;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Tools;
public static class ComponentsExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(ComponentsExtensions).Namespace, nameof(ComponentsExtensions));
public static bool AllowSendTo(this Components component) => component switch
{
Components.NONE => false,
@@ -26,22 +29,22 @@ public static class ComponentsExtensions
public static string Name(this Components component) => component switch
{
Components.GRAMMAR_SPELLING_ASSISTANT => "Grammar & Spelling Assistant",
Components.TEXT_SUMMARIZER_ASSISTANT => "Text Summarizer Assistant",
Components.ICON_FINDER_ASSISTANT => "Icon Finder Assistant",
Components.TRANSLATION_ASSISTANT => "Translation Assistant",
Components.REWRITE_ASSISTANT => "Rewrite Assistant",
Components.AGENDA_ASSISTANT => "Agenda Assistant",
Components.CODING_ASSISTANT => "Coding Assistant",
Components.EMAIL_ASSISTANT => "E-Mail Assistant",
Components.LEGAL_CHECK_ASSISTANT => "Legal Check Assistant",
Components.SYNONYMS_ASSISTANT => "Synonym Assistant",
Components.MY_TASKS_ASSISTANT => "My Tasks Assistant",
Components.JOB_POSTING_ASSISTANT => "Job Posting Assistant",
Components.ERI_ASSISTANT => "ERI Server",
Components.I18N_ASSISTANT => "Localization Assistant",
Components.GRAMMAR_SPELLING_ASSISTANT => TB("Grammar & Spelling Assistant"),
Components.TEXT_SUMMARIZER_ASSISTANT => TB("Text Summarizer Assistant"),
Components.ICON_FINDER_ASSISTANT => TB("Icon Finder Assistant"),
Components.TRANSLATION_ASSISTANT => TB("Translation Assistant"),
Components.REWRITE_ASSISTANT => TB("Rewrite Assistant"),
Components.AGENDA_ASSISTANT => TB("Agenda Assistant"),
Components.CODING_ASSISTANT => TB("Coding Assistant"),
Components.EMAIL_ASSISTANT => TB("E-Mail Assistant"),
Components.LEGAL_CHECK_ASSISTANT => TB("Legal Check Assistant"),
Components.SYNONYMS_ASSISTANT => TB("Synonym Assistant"),
Components.MY_TASKS_ASSISTANT => TB("My Tasks Assistant"),
Components.JOB_POSTING_ASSISTANT => TB("Job Posting Assistant"),
Components.ERI_ASSISTANT => TB("ERI Server"),
Components.I18N_ASSISTANT => TB("Localization Assistant"),
Components.CHAT => "New Chat",
Components.CHAT => TB("New Chat"),
_ => Enum.GetName(typeof(Components), component)!,
};
@@ -1,18 +1,22 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Tools;
public static class ConfidenceSchemesExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(ConfidenceSchemesExtensions).Namespace, nameof(ConfidenceSchemesExtensions));
public static string GetListDescription(this ConfidenceSchemes scheme) => scheme switch
{
ConfidenceSchemes.TRUST_ALL => "Trust all LLM providers",
ConfidenceSchemes.TRUST_USA_EUROPE => "Trust LLM providers from the USA and Europe",
ConfidenceSchemes.TRUST_USA => "Trust LLM providers from the USA",
ConfidenceSchemes.TRUST_EUROPE => "Trust LLM providers from Europe",
ConfidenceSchemes.TRUST_ASIA => "Trust LLM providers from Asia",
ConfidenceSchemes.LOCAL_TRUST_ONLY => "Trust only local LLM providers",
ConfidenceSchemes.TRUST_ALL => TB("Trust all LLM providers"),
ConfidenceSchemes.TRUST_USA_EUROPE => TB("Trust LLM providers from the USA and Europe"),
ConfidenceSchemes.TRUST_USA => TB("Trust LLM providers from the USA"),
ConfidenceSchemes.TRUST_EUROPE => TB("Trust LLM providers from Europe"),
ConfidenceSchemes.TRUST_ASIA => TB("Trust LLM providers from Asia"),
ConfidenceSchemes.LOCAL_TRUST_ONLY => TB("Trust only local LLM providers"),
ConfidenceSchemes.CUSTOM => "Configure your own confidence scheme",
ConfidenceSchemes.CUSTOM => TB("Configure your own confidence scheme"),
_ => "Unknown confidence scheme"
_ => TB("Unknown confidence scheme"),
};
}
@@ -1,13 +1,17 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Tools.ERIClient.DataModel;
public static class ProviderTypeExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(ProviderTypeExtensions).Namespace, nameof(ProviderTypeExtensions));
public static string Explain(this ProviderType providerType) => providerType switch
{
ProviderType.NONE => "The related data is not allowed to be sent to any LLM provider. This means that this data source cannot be used at the moment.",
ProviderType.ANY => "The related data can be sent to any provider, regardless of where it is hosted (cloud or self-hosted).",
ProviderType.SELF_HOSTED => "The related data can be sent to a provider that is hosted by the same organization, either on-premises or locally. Cloud-based providers are not allowed.",
ProviderType.NONE => TB("The related data is not allowed to be sent to any LLM provider. This means that this data source cannot be used at the moment."),
ProviderType.ANY => TB("The related data can be sent to any provider, regardless of where it is hosted (cloud or self-hosted)."),
ProviderType.SELF_HOSTED => TB("The related data can be sent to a provider that is hosted by the same organization, either on-premises or locally. Cloud-based providers are not allowed."),
_ => "Unknown configuration. This data source cannot be used at the moment.",
_ => TB("Unknown configuration. This data source cannot be used at the moment."),
};
}
@@ -3,12 +3,15 @@ using System.Text.Json;
using AIStudio.Settings;
using AIStudio.Tools.ERIClient.DataModel;
using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Services;
namespace AIStudio.Tools.ERIClient;
public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource), IERIClient
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(ERIClientV1).Namespace, nameof(ERIClientV1));
#region Implementation of IERIClient
public async Task<APIResponse<List<AuthScheme>>> GetAuthMethodsAsync(CancellationToken cancellationToken = default)
@@ -21,7 +24,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to retrieve the authentication methods: there was an issue communicating with the ERI server. Code: {response.StatusCode}, Reason: {response.ReasonPhrase}"
Message = string.Format(TB("Failed to retrieve the authentication methods: there was an issue communicating with the ERI server. Code: {0}, Reason: {1}"), response.StatusCode, response.ReasonPhrase)
};
}
@@ -31,7 +34,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to retrieve the authentication methods: the ERI server did not return a valid response."
Message = TB("Failed to retrieve the authentication methods: the ERI server did not return a valid response.")
};
}
@@ -46,7 +49,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to retrieve the authentication methods: the request was canceled either by the user or due to a timeout."
Message = TB("Failed to retrieve the authentication methods: the request was canceled either by the user or due to a timeout.")
};
}
catch (Exception e)
@@ -54,7 +57,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to retrieve the authentication methods due to an exception: {e.Message}"
Message = string.Format(TB("Failed to retrieve the authentication methods due to an exception: {0}"), e.Message)
};
}
}
@@ -76,7 +79,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to authenticate with the ERI server. Code: {noneAuthResponse.StatusCode}, Reason: {noneAuthResponse.ReasonPhrase}"
Message = string.Format(TB("Failed to authenticate with the ERI server. Code: {0}, Reason: {1}"), noneAuthResponse.StatusCode, noneAuthResponse.ReasonPhrase)
};
}
@@ -86,7 +89,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to authenticate with the ERI server: the response was invalid."
Message = TB("Failed to authenticate with the ERI server: the response was invalid.")
};
}
@@ -108,7 +111,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to retrieve the password."
Message = TB("Failed to retrieve the password.")
};
}
@@ -130,7 +133,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to authenticate with the ERI server. Code: {usernamePasswordAuthResponse.StatusCode}, Reason: {usernamePasswordAuthResponse.ReasonPhrase}"
Message = string.Format(TB("Failed to authenticate with the ERI server. Code: {0}, Reason: {1}"), usernamePasswordAuthResponse.StatusCode, usernamePasswordAuthResponse.ReasonPhrase)
};
}
@@ -140,7 +143,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to authenticate with the server: the response was invalid."
Message = TB("Failed to authenticate with the server: the response was invalid.")
};
}
@@ -162,7 +165,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to retrieve the access token."
Message = TB("Failed to retrieve the access token.")
};
}
@@ -181,7 +184,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to authenticate with the ERI server. Code: {tokenAuthResponse.StatusCode}, Reason: {tokenAuthResponse.ReasonPhrase}"
Message = string.Format(TB("Failed to authenticate with the ERI server. Code: {0}, Reason: {1}"), tokenAuthResponse.StatusCode, tokenAuthResponse.ReasonPhrase)
};
}
@@ -191,7 +194,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to authenticate with the ERI server: the response was invalid."
Message = TB("Failed to authenticate with the ERI server: the response was invalid.")
};
}
@@ -208,7 +211,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "The authentication method is not supported yet."
Message = TB("The authentication method is not supported yet.")
};
}
}
@@ -217,7 +220,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to authenticate with the ERI server: the request was canceled either by the user or due to a timeout."
Message = TB("Failed to authenticate with the ERI server: the request was canceled either by the user or due to a timeout.")
};
}
catch (Exception e)
@@ -225,7 +228,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to authenticate with the ERI server due to an exception: {e.Message}"
Message = string.Format(TB("Failed to authenticate with the ERI server due to an exception: {0}"), e.Message)
};
}
}
@@ -243,7 +246,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to retrieve the data source information: there was an issue communicating with the ERI server. Code: {response.StatusCode}, Reason: {response.ReasonPhrase}"
Message = string.Format(TB("Failed to retrieve the data source information: there was an issue communicating with the ERI server. Code: {0}, Reason: {1}"), response.StatusCode, response.ReasonPhrase)
};
}
@@ -253,7 +256,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to retrieve the data source information: the ERI server did not return a valid response."
Message = TB("Failed to retrieve the data source information: the ERI server did not return a valid response.")
};
}
@@ -268,7 +271,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to retrieve the data source information: the request was canceled either by the user or due to a timeout."
Message = TB("Failed to retrieve the data source information: the request was canceled either by the user or due to a timeout.")
};
}
catch (Exception e)
@@ -276,7 +279,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to retrieve the data source information due to an exception: {e.Message}"
Message = string.Format(TB("Failed to retrieve the data source information due to an exception: {0}"), e.Message)
};
}
}
@@ -294,7 +297,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to retrieve the embedding information: there was an issue communicating with the ERI server. Code: {response.StatusCode}, Reason: {response.ReasonPhrase}"
Message = string.Format(TB("Failed to retrieve the embedding information: there was an issue communicating with the ERI server. Code: {0}, Reason: {1}"), response.StatusCode, response.ReasonPhrase)
};
}
@@ -304,7 +307,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to retrieve the embedding information: the ERI server did not return a valid response."
Message = TB("Failed to retrieve the embedding information: the ERI server did not return a valid response.")
};
}
@@ -319,7 +322,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to retrieve the embedding information: the request was canceled either by the user or due to a timeout."
Message = TB("Failed to retrieve the embedding information: the request was canceled either by the user or due to a timeout.")
};
}
catch (Exception e)
@@ -327,7 +330,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to retrieve the embedding information due to an exception: {e.Message}"
Message = string.Format(TB("Failed to retrieve the embedding information due to an exception: {0}"), e.Message)
};
}
}
@@ -345,7 +348,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to retrieve the retrieval information: there was an issue communicating with the ERI server. Code: {response.StatusCode}, Reason: {response.ReasonPhrase}"
Message = string.Format(TB("Failed to retrieve the retrieval information: there was an issue communicating with the ERI server. Code: {0}, Reason: {1}"), response.StatusCode, response.ReasonPhrase)
};
}
@@ -355,7 +358,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to retrieve the retrieval information: the ERI server did not return a valid response."
Message = TB("Failed to retrieve the retrieval information: the ERI server did not return a valid response.")
};
}
@@ -370,7 +373,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to retrieve the retrieval information: the request was canceled either by the user or due to a timeout."
Message = TB("Failed to retrieve the retrieval information: the request was canceled either by the user or due to a timeout.")
};
}
catch (Exception e)
@@ -378,7 +381,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to retrieve the retrieval information due to an exception: {e.Message}"
Message = string.Format(TB("Failed to retrieve the retrieval information due to an exception: {0}"), e.Message)
};
}
}
@@ -399,7 +402,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to execute the retrieval request: there was an issue communicating with the ERI server. Code: {response.StatusCode}, Reason: {response.ReasonPhrase}"
Message = string.Format(TB("Failed to execute the retrieval request: there was an issue communicating with the ERI server. Code: {0}, Reason: {1}"), response.StatusCode, response.ReasonPhrase)
};
}
@@ -409,7 +412,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to execute the retrieval request: the ERI server did not return a valid response."
Message = TB("Failed to execute the retrieval request: the ERI server did not return a valid response.")
};
}
@@ -424,7 +427,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to execute the retrieval request: the request was canceled either by the user or due to a timeout."
Message = TB("Failed to execute the retrieval request: the request was canceled either by the user or due to a timeout.")
};
}
catch (Exception e)
@@ -432,7 +435,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to execute the retrieval request due to an exception: {e.Message}"
Message = string.Format(TB("Failed to execute the retrieval request due to an exception: {0}"), e.Message)
};
}
}
@@ -450,7 +453,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to retrieve the security requirements: there was an issue communicating with the ERI server. Code: {response.StatusCode}, Reason: {response.ReasonPhrase}"
Message = string.Format(TB("Failed to retrieve the security requirements: there was an issue communicating with the ERI server. Code: {0}, Reason: {1}"), response.StatusCode, response.ReasonPhrase)
};
}
@@ -460,7 +463,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to retrieve the security requirements: the ERI server did not return a valid response."
Message = TB("Failed to retrieve the security requirements: the ERI server did not return a valid response.")
};
}
@@ -475,7 +478,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = "Failed to retrieve the security requirements: the request was canceled either by the user or due to a timeout."
Message = TB("Failed to retrieve the security requirements: the request was canceled either by the user or due to a timeout.")
};
}
catch (Exception e)
@@ -483,7 +486,7 @@ public class ERIClientV1(IERIDataSource dataSource) : ERIClientBase(dataSource),
return new()
{
Successful = false,
Message = $"Failed to retrieve the security requirements due to an exception: {e.Message}"
Message = string.Format(TB("Failed to retrieve the security requirements due to an exception: {0}"), e.Message)
};
}
}
@@ -2,7 +2,7 @@
namespace AIStudio.Tools.Metadata;
[AttributeUsage(AttributeTargets.Assembly)]
public class MetaDataArchitecture(string architecture) : Attribute
public class MetaDataArchitectureAttribute(string architecture) : Attribute
{
public string Architecture => architecture;
}
@@ -0,0 +1,6 @@
namespace AIStudio.Tools.Metadata;
public class MetaDataLibrariesAttribute(string pdfiumVersion) : Attribute
{
public string PdfiumVersion => pdfiumVersion;
}
@@ -0,0 +1,36 @@
namespace AIStudio.Tools.PluginSystem;
public class I18N : ILang
{
public static readonly I18N I = new();
private static readonly ILogger<I18N> LOG = Program.LOGGER_FACTORY.CreateLogger<I18N>();
private ILanguagePlugin? language = PluginFactory.BaseLanguage;
private I18N()
{
}
public static void Init(ILanguagePlugin language) => I.language = language;
#region Implementation of ILang
public string T(string fallbackEN)
{
LOG.LogWarning("Using I18N.I.T without namespace and type is probably wrong, because the I18N key collection process of the build system will not find those keys.");
if(this.language is not null)
return this.GetText(this.language, fallbackEN);
return fallbackEN;
}
public string T(string fallbackEN, string? typeNamespace, string? typeName)
{
if(this.language is not null)
return this.GetText(this.language, fallbackEN, typeNamespace, typeName);
return fallbackEN;
}
#endregion
}
@@ -12,8 +12,8 @@ public static class ILangExtensions
typeName ??= type.Name;
typeNamespace ??= type.Namespace!;
// When the type's name ends with `1 or 2`, etc. (i.e., generic classes), remove it:
if(typeName.Contains("`"))
// When the type's name ends with `1 or `2, etc. (i.e., generic classes), remove it:
if(typeName.Contains('`'))
typeName = typeName[..typeName.IndexOf('`')];
var ns = $"{typeNamespace}::{typeName}".ToUpperInvariant().Replace(".", "::");
@@ -8,6 +8,8 @@ namespace AIStudio.Tools.PluginSystem;
/// </summary>
public abstract partial class PluginBase : IPluginMetadata
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(PluginBase).Namespace, nameof(PluginBase));
private readonly IReadOnlyCollection<string> baseIssues;
protected readonly LuaState state;
@@ -155,21 +157,21 @@ public abstract partial class PluginBase : IPluginMetadata
{
if (!this.state.Environment["ID"].TryRead<string>(out var idText))
{
message = "The field ID does not exist or is not a valid string.";
message = TB("The field ID does not exist or is not a valid string.");
id = Guid.Empty;
return false;
}
if (!Guid.TryParse(idText, out id))
{
message = "The field ID is not a valid GUID / UUID. The ID must be formatted in the 8-4-4-4-12 format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX).";
message = TB("The field ID is not a valid GUID / UUID. The ID must be formatted in the 8-4-4-4-12 format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX).");
id = Guid.Empty;
return false;
}
if(id == Guid.Empty)
{
message = "The field ID is empty. The ID must be formatted in the 8-4-4-4-12 format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX).";
message = TB("The field ID is empty. The ID must be formatted in the 8-4-4-4-12 format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX).");
return false;
}
@@ -187,14 +189,14 @@ public abstract partial class PluginBase : IPluginMetadata
{
if (!this.state.Environment["NAME"].TryRead(out name))
{
message = "The field NAME does not exist or is not a valid string.";
message = TB("The field NAME does not exist or is not a valid string.");
name = string.Empty;
return false;
}
if(string.IsNullOrWhiteSpace(name))
{
message = "The field NAME is empty. The name must be a non-empty string.";
message = TB("The field NAME is empty. The name must be a non-empty string.");
return false;
}
@@ -212,14 +214,14 @@ public abstract partial class PluginBase : IPluginMetadata
{
if (!this.state.Environment["DESCRIPTION"].TryRead(out description))
{
message = "The field DESCRIPTION does not exist or is not a valid string.";
message = TB("The field DESCRIPTION does not exist or is not a valid string.");
description = string.Empty;
return false;
}
if(string.IsNullOrWhiteSpace(description))
{
message = "The field DESCRIPTION is empty. The description must be a non-empty string.";
message = TB("The field DESCRIPTION is empty. The description must be a non-empty string.");
return false;
}
@@ -237,21 +239,21 @@ public abstract partial class PluginBase : IPluginMetadata
{
if (!this.state.Environment["VERSION"].TryRead<string>(out var versionText))
{
message = "The field VERSION does not exist or is not a valid string.";
message = TB("The field VERSION does not exist or is not a valid string.");
version = PluginVersion.NONE;
return false;
}
if (!PluginVersion.TryParse(versionText, out version))
{
message = "The field VERSION is not a valid version number. The version number must be formatted as string in the major.minor.patch format (X.X.X).";
message = TB("The field VERSION is not a valid version number. The version number must be formatted as string in the major.minor.patch format (X.X.X).");
version = PluginVersion.NONE;
return false;
}
if(version == PluginVersion.NONE)
{
message = "The field VERSION is empty. The version number must be formatted as string in the major.minor.patch format (X.X.X).";
message = TB("The field VERSION is empty. The version number must be formatted as string in the major.minor.patch format (X.X.X).");
return false;
}
@@ -270,7 +272,7 @@ public abstract partial class PluginBase : IPluginMetadata
if (!this.state.Environment["AUTHORS"].TryRead<LuaTable>(out var authorsTable))
{
authors = [];
message = "The table AUTHORS does not exist or is using an invalid syntax.";
message = TB("The table AUTHORS does not exist or is using an invalid syntax.");
return false;
}
@@ -282,7 +284,7 @@ public abstract partial class PluginBase : IPluginMetadata
authors = authorList.ToArray();
if(authorList.Count == 0)
{
message = "The table AUTHORS is empty. At least one author must be specified.";
message = TB("The table AUTHORS is empty. At least one author must be specified.");
return false;
}
@@ -301,13 +303,13 @@ public abstract partial class PluginBase : IPluginMetadata
if (!this.state.Environment["SUPPORT_CONTACT"].TryRead(out contact))
{
contact = string.Empty;
message = "The field SUPPORT_CONTACT does not exist or is not a valid string.";
message = TB("The field SUPPORT_CONTACT does not exist or is not a valid string.");
return false;
}
if(string.IsNullOrWhiteSpace(contact))
{
message = "The field SUPPORT_CONTACT is empty. The support contact must be a non-empty string.";
message = TB("The field SUPPORT_CONTACT is empty. The support contact must be a non-empty string.");
return false;
}
@@ -326,14 +328,14 @@ public abstract partial class PluginBase : IPluginMetadata
if (!this.state.Environment["SOURCE_URL"].TryRead(out url))
{
url = string.Empty;
message = "The field SOURCE_URL does not exist or is not a valid string.";
message = TB("The field SOURCE_URL does not exist or is not a valid string.");
return false;
}
if (!url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) && !url.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
{
url = string.Empty;
message = "The field SOURCE_URL is not a valid URL. The URL must start with 'http://' or 'https://'.";
message = TB("The field SOURCE_URL is not a valid URL. The URL must start with 'http://' or 'https://'.");
return false;
}
@@ -352,7 +354,7 @@ public abstract partial class PluginBase : IPluginMetadata
if (!this.state.Environment["CATEGORIES"].TryRead<LuaTable>(out var categoriesTable))
{
categories = [];
message = "The table CATEGORIES does not exist or is using an invalid syntax.";
message = TB("The table CATEGORIES does not exist or is using an invalid syntax.");
return false;
}
@@ -365,7 +367,7 @@ public abstract partial class PluginBase : IPluginMetadata
categories = categoryList.ToArray();
if(categoryList.Count == 0)
{
message = $"The table CATEGORIES is empty. At least one category is necessary. Valid categories are: {CommonTools.GetAllEnumValues(PluginCategory.NONE)}.";
message = string.Format(TB("The table CATEGORIES is empty. At least one category is necessary. Valid categories are: {0}."), CommonTools.GetAllEnumValues(PluginCategory.NONE));
return false;
}
@@ -384,7 +386,7 @@ public abstract partial class PluginBase : IPluginMetadata
if (!this.state.Environment["TARGET_GROUPS"].TryRead<LuaTable>(out var targetGroupsTable))
{
targetGroups = [];
message = "The table TARGET_GROUPS does not exist or is using an invalid syntax.";
message = TB("The table TARGET_GROUPS does not exist or is using an invalid syntax.");
return false;
}
@@ -397,7 +399,7 @@ public abstract partial class PluginBase : IPluginMetadata
targetGroups = targetGroupList.ToArray();
if(targetGroups.Length == 0)
{
message = "The table TARGET_GROUPS is empty or is not a valid table of strings. Valid target groups are: {CommonTools.GetAllEnumValues(PluginTargetGroup.NONE)}.";
message = string.Format(TB("The table TARGET_GROUPS is empty or is not a valid table of strings. Valid target groups are: {0}."), CommonTools.GetAllEnumValues(PluginTargetGroup.NONE));
return false;
}
@@ -416,7 +418,7 @@ public abstract partial class PluginBase : IPluginMetadata
if (!this.state.Environment["IS_MAINTAINED"].TryRead(out isMaintained))
{
isMaintained = false;
message = "The field IS_MAINTAINED does not exist or is not a valid boolean.";
message = TB("The field IS_MAINTAINED does not exist or is not a valid boolean.");
return false;
}
@@ -435,7 +437,7 @@ public abstract partial class PluginBase : IPluginMetadata
if (!this.state.Environment["DEPRECATION_MESSAGE"].TryRead(out deprecationMessage))
{
deprecationMessage = string.Empty;
message = "The field DEPRECATION_MESSAGE does not exist, is not a valid string. This message is optional: use an empty string to indicate that the plugin is not deprecated.";
message = TB("The field DEPRECATION_MESSAGE does not exist, is not a valid string. This message is optional: use an empty string to indicate that the plugin is not deprecated.");
return false;
}
@@ -453,7 +455,7 @@ public abstract partial class PluginBase : IPluginMetadata
{
if (!this.state.Environment["UI_TEXT_CONTENT"].TryRead<LuaTable>(out var textTable))
{
message = "The UI_TEXT_CONTENT table does not exist or is not a valid table.";
message = TB("The UI_TEXT_CONTENT table does not exist or is not a valid table.");
pluginContent = [];
return false;
}
@@ -2,37 +2,39 @@ namespace AIStudio.Tools.PluginSystem;
public static class PluginCategoryExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(PluginCategoryExtensions).Namespace, nameof(PluginCategoryExtensions));
public static string GetName(this PluginCategory type) => type switch
{
PluginCategory.NONE => "None",
PluginCategory.CORE => "AI Studio Core",
PluginCategory.NONE => TB("None"),
PluginCategory.CORE => TB("AI Studio Core"),
PluginCategory.BUSINESS => "Business",
PluginCategory.INDUSTRY => "Industry",
PluginCategory.UTILITY => "Utility",
PluginCategory.SOFTWARE_DEVELOPMENT => "Software Development",
PluginCategory.GAMING => "Gaming",
PluginCategory.EDUCATION => "Education",
PluginCategory.ENTERTAINMENT => "Entertainment",
PluginCategory.SOCIAL => "Social",
PluginCategory.SHOPPING => "Shopping",
PluginCategory.TRAVEL => "Travel",
PluginCategory.HEALTH => "Health",
PluginCategory.FITNESS => "Fitness",
PluginCategory.FOOD => "Food",
PluginCategory.PARTY => "Party",
PluginCategory.SPORTS => "Sports",
PluginCategory.NEWS => "News",
PluginCategory.WEATHER => "Weather",
PluginCategory.MUSIC => "Music",
PluginCategory.POLITICAL => "Political",
PluginCategory.SCIENCE => "Science",
PluginCategory.TECHNOLOGY => "Technology",
PluginCategory.ART => "Art",
PluginCategory.FICTION => "Fiction",
PluginCategory.WRITING => "Writing",
PluginCategory.CONTENT_CREATION => "Content Creation",
PluginCategory.BUSINESS => TB("Business"),
PluginCategory.INDUSTRY => TB("Industry"),
PluginCategory.UTILITY => TB("Utility"),
PluginCategory.SOFTWARE_DEVELOPMENT => TB("Software Development"),
PluginCategory.GAMING => TB("Gaming"),
PluginCategory.EDUCATION => TB("Education"),
PluginCategory.ENTERTAINMENT => TB("Entertainment"),
PluginCategory.SOCIAL => TB("Social"),
PluginCategory.SHOPPING => TB("Shopping"),
PluginCategory.TRAVEL => TB("Travel"),
PluginCategory.HEALTH => TB("Health"),
PluginCategory.FITNESS => TB("Fitness"),
PluginCategory.FOOD => TB("Food"),
PluginCategory.PARTY => TB("Party"),
PluginCategory.SPORTS => TB("Sports"),
PluginCategory.NEWS => TB("News"),
PluginCategory.WEATHER => TB("Weather"),
PluginCategory.MUSIC => TB("Music"),
PluginCategory.POLITICAL => TB("Political"),
PluginCategory.SCIENCE => TB("Science"),
PluginCategory.TECHNOLOGY => TB("Technology"),
PluginCategory.ART => TB("Art"),
PluginCategory.FICTION => TB("Fiction"),
PluginCategory.WRITING => TB("Writing"),
PluginCategory.CONTENT_CREATION => TB("Content Creation"),
_ => "Unknown plugin category",
_ => TB("Unknown plugin category"),
};
}
@@ -16,7 +16,27 @@ public static partial class PluginFactory
return;
}
// A plugin update might remove some resources. Even worse, a plugin
// might have changed its name, etc. Thus, we delete the internal
// plugin directories before copying the new resources:
LOG.LogInformation("Try to delete the internal plugins directory for maintenance.");
if (Directory.Exists(INTERNAL_PLUGINS_ROOT))
{
try
{
Directory.Delete(INTERNAL_PLUGINS_ROOT, true);
LOG.LogInformation("Successfully deleted the internal plugins directory for maintenance.");
}
catch (Exception e)
{
LOG.LogError($"Could not delete the internal plugins directory for maintenance: {INTERNAL_PLUGINS_ROOT}. Error: {e}");
}
}
LOG.LogInformation("Start ensuring internal plugins.");
if(!Directory.Exists(INTERNAL_PLUGINS_ROOT))
Directory.CreateDirectory(INTERNAL_PLUGINS_ROOT);
foreach (var plugin in Enum.GetValues<InternalPlugin>())
{
LOG.LogInformation($"Ensure plugin: {plugin}");
@@ -4,6 +4,7 @@ namespace AIStudio.Tools.PluginSystem;
public sealed class PluginLanguage : PluginBase, ILanguagePlugin
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(PluginLanguage).Namespace, nameof(PluginLanguage));
private static readonly ILogger<PluginLanguage> LOGGER = Program.LOGGER_FACTORY.CreateLogger<PluginLanguage>();
private readonly Dictionary<string, string> content = [];
@@ -53,28 +54,28 @@ public sealed class PluginLanguage : PluginBase, ILanguagePlugin
{
if (!this.state.Environment["IETF_TAG"].TryRead(out readLangCultureTag))
{
message = "The field IETF_TAG does not exist or is not a valid string.";
message = TB("The field IETF_TAG does not exist or is not a valid string.");
readLangCultureTag = string.Empty;
return false;
}
if (string.IsNullOrWhiteSpace(readLangCultureTag))
{
message = "The field IETF_TAG is empty. Use a valid IETF tag like 'en-US'. The first part is the language, the second part is the country code.";
message = TB("The field IETF_TAG is empty. Use a valid IETF tag like 'en-US'. The first part is the language, the second part is the country code.");
readLangCultureTag = string.Empty;
return false;
}
if (readLangCultureTag.Length != 5)
{
message = "The field IETF_TAG is not a valid IETF tag. Use a valid IETF tag like 'en-US'. The first part is the language, the second part is the country code.";
message = TB("The field IETF_TAG is not a valid IETF tag. Use a valid IETF tag like 'en-US'. The first part is the language, the second part is the country code.");
readLangCultureTag = string.Empty;
return false;
}
if (readLangCultureTag[2] != '-')
{
message = "The field IETF_TAG is not a valid IETF tag. Use a valid IETF tag like 'en-US'. The first part is the language, the second part is the country code.";
message = TB("The field IETF_TAG is not a valid IETF tag. Use a valid IETF tag like 'en-US'. The first part is the language, the second part is the country code.");
readLangCultureTag = string.Empty;
return false;
}
@@ -83,7 +84,7 @@ public sealed class PluginLanguage : PluginBase, ILanguagePlugin
for (var i = 0; i < 2; i++)
if (!char.IsLower(readLangCultureTag[i]))
{
message = "The field IETF_TAG is not a valid IETF tag. Use a valid IETF tag like 'en-US'. The first part is the language, the second part is the country code.";
message = TB("The field IETF_TAG is not a valid IETF tag. Use a valid IETF tag like 'en-US'. The first part is the language, the second part is the country code.");
readLangCultureTag = string.Empty;
return false;
}
@@ -92,7 +93,7 @@ public sealed class PluginLanguage : PluginBase, ILanguagePlugin
for (var i = 3; i < 5; i++)
if (!char.IsUpper(readLangCultureTag[i]))
{
message = "The field IETF_TAG is not a valid IETF tag. Use a valid IETF tag like 'en-US'. The first part is the language, the second part is the country code.";
message = TB("The field IETF_TAG is not a valid IETF tag. Use a valid IETF tag like 'en-US'. The first part is the language, the second part is the country code.");
readLangCultureTag = string.Empty;
return false;
}
@@ -105,14 +106,14 @@ public sealed class PluginLanguage : PluginBase, ILanguagePlugin
{
if (!this.state.Environment["LANG_NAME"].TryRead(out readLangName))
{
message = "The field LANG_NAME does not exist or is not a valid string.";
message = TB("The field LANG_NAME does not exist or is not a valid string.");
readLangName = string.Empty;
return false;
}
if (string.IsNullOrWhiteSpace(readLangName))
{
message = "The field LANG_NAME is empty. Use a valid language name.";
message = TB("The field LANG_NAME is empty. Use a valid language name.");
readLangName = string.Empty;
return false;
}
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more