Compare commits

...
Author SHA1 Message Date
Thorsten Sommer ae8ae4da06 Added the upgrade of Qdrant Edge to the changelog 2026-11-24 20:30:06 +01:00
Thorsten Sommer c1d67482e3 Removed the patch of permutation_iterator 2026-11-24 19:32:47 +01:00
Thorsten Sommer 6ebcc28755 Upgraded Qdrant Edge to v0.9.0 2026-11-24 19:31:36 +01:00
Thorsten Sommer 9b4d07552d Added a check for the characters of ERI usernames, tokens, and passwords (#1228) 2026-11-24 18:47:44 +01:00
Thorsten Sommer e5a7f5423f Added a check for characters which an API key cannot contain (#1227) 2026-11-24 17:20:13 +01:00
Peer HogeterpandThorsten Sommer c72a1948b3 Fixed signing in to mailboxes with characters beyond ASCII in the username or password (#1224)
Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
2026-11-24 15:53:19 +01:00
Thorsten Sommer f6a4348820 Upgraded MailKit and MimeKit to v5.0 (#1226) 2026-11-24 08:35:36 +01:00
Thorsten Sommer d121ec3b47 Moved the Flatpak sync to the GNOME 51 runtime (#1225) 2026-11-23 18:42:08 +01:00
Thorsten Sommer 6154f65e78 Raised the minimum Rust version to the toolchain the Flatpak now builds with (#1223) 2026-11-23 15:43:20 +01:00
Thorsten Sommer 6e94a93c70 Added the dashes after dotnet run to every call of the build script (#1222) 2026-11-23 11:07:50 +01:00
Thorsten Sommer b6d614d96a Pinned the .NET runtime to the version in metadata.txt (#1221) 2026-11-23 10:30:50 +01:00
Thorsten Sommer 37e6161ccc Added a build command for local Flatpak builds (#1220) 2026-11-23 09:46:12 +01:00
Thorsten Sommer 2772612c00 Upgraded Tauri to v2.12.7 and the Rust dependencies (#1219) 2026-11-22 20:56:12 +01:00
Thorsten Sommer f96025529a Upgraded to Rust v1.100.0 and .NET v10.0.15 (#1218) 2026-11-21 21:29:55 +01:00
Thorsten Sommer 78f5066bfd Fixed the retrieval context validation keeping unhelpful passages (#1217) 2026-11-21 20:50:25 +01:00
Thorsten Sommer 808b95b15d Added a shared method for keeping assistant plugin audits (#1216) 2026-11-21 20:16:05 +01:00
Thorsten Sommer c50a93cd17 Moved the background agents to AI operations (#1215) 2026-11-21 19:47:10 +01:00
j-erlerandThorsten Sommer 8a4a26503b Added context compression (#1198)
Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
2026-11-21 14:16:04 +01:00
j-erlerandThorsten Sommer 28b88580a9 Added status texts for prompt processing and reasoning to the chat (#1205)
Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
2026-11-21 09:43:31 +01:00
Thorsten Sommer 6cdb0bc551 Moved goals and roles before knowledge in the BeyondFacts Lab (#1214) 2026-11-20 19:33:04 +01:00
Thorsten Sommer 761ec7001d Fixed missing fonts and icons in release builds (#1213) 2026-11-20 15:25:49 +01:00
j-erlerandThorsten Sommer ca7413d84c Fixed a misleading tool calling error after a stopped or interrupted answer (#1202)
Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
2026-11-20 14:46:27 +01:00
Thorsten Sommer fb8f51dec4 Fixed text fields which kept showing an issue while you typed (#1212) 2026-11-20 12:47:40 +01:00
Thorsten Sommer 1db0f85898 Improved the assistants page with categories for assistant plugins (#1211) 2026-11-20 11:47:59 +01:00
Thorsten Sommer ef059ffd15 Added simulated participants to the BeyondFacts Lab (#1208) 2026-11-16 14:07:28 +01:00
Thorsten Sommer 92d0ff68f4 Added the research on individual participants to the BeyondFacts Lab (#1207) 2026-11-15 15:39:34 +01:00
Thorsten Sommer 3ca4b3878b Added the value card sort to the BeyondFacts Lab (#1206) 2026-11-15 13:06:06 +01:00
Thorsten Sommer 1361b984eb Added guidelines from the organization to the BeyondFacts Lab (#1204) 2026-11-15 11:40:15 +01:00
Thorsten Sommer cb54ad297d Moved the chats of the BeyondFacts Lab to the embedded chat of assistants (#1203) 2026-11-15 10:32:46 +01:00
Thorsten Sommer dc97db256e Improved how AI Studio saves its files (#1201) 2026-11-14 21:16:40 +01:00
Dominic NeuburgandThorsten Sommer b7255694cd Added the Model Comparison assistant for blind comparisons of two models (#1009)
Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
2026-11-14 14:11:34 +01:00
Carsten BauerandThorsten Sommer 12f26445ba Fixed the Pdfium install on a fresh clone without runtime/target (#1195)
Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
2026-11-13 10:34:30 +01:00
Thorsten Sommer c9a376f742 Added the choice between formal and informal address to the whole app (#1200) 2026-11-13 10:16:56 +01:00
Peer HogeterpandThorsten Sommer 382db4b8d0 Improved how the AI remembers its earlier tool calls (#1185)
Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
2026-11-12 19:57:28 +01:00
Thorsten Sommer 0885862150 Added sharing a BeyondFacts Lab session with the research team (#1196) 2026-11-12 15:02:00 +01:00
Thorsten Sommer a1b493cb13 Fixed plugin values which depended on the region settings of the computer (#1194) 2026-11-12 08:57:50 +01:00
Thorsten Sommer 65d50de033 Added an analyzer which keeps line breaks LF on every system (#1193) 2026-11-11 19:30:00 +01:00
Thorsten Sommer b1c1f13993 Fixed line endings in the reflection folder and tests on Windows (#1192) 2026-11-11 17:15:12 +01:00
Thorsten Sommer 6f187f1bd8 Renamed the extension classes of interfaces to drop the I prefix (#1190) 2026-11-11 16:17:45 +01:00
Thorsten Sommer d8ef328e6e Updated the screenshots in the README (#1188) 2026-11-11 15:32:03 +01:00
Thorsten Sommer 7ef26cd5c8 Changed all icons of AI Studio to Lucide (#1187) 2026-11-11 14:20:49 +01:00
Thorsten Sommer 9a676101f7 Added research on the web to the BeyondFacts Lab (#1186) 2026-11-10 18:17:44 +01:00
Thorsten Sommer e5c0931a60 Added results and exports to the BeyondFacts Lab (#1184) 2026-11-10 13:54:10 +01:00
Thorsten Sommer 8e1a66cb24 Fixed a crash when switching steps in the BeyondFacts Lab (#1183) 2026-11-10 12:18:51 +01:00
Thorsten Sommer a9579dd282 Added confirmed work states to the BeyondFacts Lab (#1182) 2026-11-10 11:27:51 +01:00
Thorsten Sommer 6d0052ecdf Added prompt overrides for testing the BeyondFacts Lab (#1181) 2026-11-10 08:57:36 +01:00
Thorsten Sommer 9f2280bed7 Added material to the BeyondFacts Lab (#1180) 2026-11-09 20:00:01 +01:00
Thorsten Sommer 22d94eb8fd Added an introduction and an onboarding chat to the BeyondFacts Lab (#1178) 2026-11-09 12:42:59 +01:00
Thorsten Sommer 79e0c80031 Added the guided chat to the BeyondFacts Lab (#1177) 2026-11-09 09:55:01 +01:00
Thorsten Sommer e77645f44c Added the informal address to the BeyondFacts Lab (#1176) 2026-11-08 21:10:51 +01:00
Thorsten Sommer b6c3fbb5db Added the BeyondFacts Lab as a prototype (#1175) 2026-11-08 19:49:46 +01:00
Thorsten Sommer db8dae1cf6 Updated README for v26.11.1 (#1174) 2026-11-08 15:53:45 +01:00
1395 changed files with 101249 additions and 9562 deletions

No files matched your search

+6 -2
View File
@@ -11,7 +11,11 @@ media/**/*.pptx filter=lfs diff=lfs merge=lfs -text
media/**/*.png filter=lfs diff=lfs merge=lfs -text
media/**/*.ico filter=lfs diff=lfs merge=lfs -text
media/**/*.icns filter=lfs diff=lfs merge=lfs -text
*.woff2 filter=lfs diff=lfs merge=lfs -text
*.afpub filter=lfs diff=lfs merge=lfs -text
*.afdesign filter=lfs diff=lfs merge=lfs -text
*.afphoto filter=lfs diff=lfs merge=lfs -text
*.afphoto filter=lfs diff=lfs merge=lfs -text
# Files which the app or the runtime ships never go into Git LFS: the pipeline and the Flatpak check
# out without LFS, so a release would ship the pointer instead of the file. WebRootFilesTests checks
# the files the app embeds.
*.woff2 binary
+1 -1
View File
@@ -19,7 +19,7 @@ once it is done: that is our signal to take over. The automated check waits unti
## How did you test it?
<!-- For example: ran `dotnet run verify`, ran the app locally, and tried out … -->
<!-- For example: ran `dotnet run -- verify`, ran the app locally, and tried out … -->
## Wiki
+6 -4
View File
@@ -47,14 +47,14 @@ env:
FLATPAK_YQ_SHA256: 0c2b24e645b57d8e7c0566d18643a6d4f5580feeea3878127354a46f2a1e4598
FLATPAK_UV_VERSION: 0.11.28
FLATPAK_UV_SHA256: e490a6464492183c5d4534a5527fb4440f7f2bb2f228162ad7e4afe076dc0224
FLATPAK_FREEDESKTOP_VERSION: "25.08"
FLATPAK_FREEDESKTOP_VERSION: "26.08"
SSIGN_VERSION: 0.1.7
SSIGN_SHA256: 4ee5389a74ddbeb67e18fe8c8b963734ca13de7b24beffbe430c3f427ecc5e40
# The Tauri CLI which bundles the app, exactly this version on every platform. Keep it at the minor
# version of the tauri crate in runtime/Cargo.toml. The version also names the cache of the CLI, so
# changing it installs the new CLI once on each platform and caches it from then on:
TAURI_CLI_VERSION: "2.12.4"
TAURI_CLI_VERSION: "2.12.6"
jobs:
determine_run_mode:
@@ -362,6 +362,8 @@ jobs:
"$tools_dir/uv" --version
"$tools_dir/yq" --version
# The build command "flatpak" of app/Build repeats this step for local test builds, in
# app/Build/Flatpak/build-in-container.sh. Whoever changes one of them changes the other one as well.
- name: Update Flatpak release sources
working-directory: flatpak
env:
@@ -793,7 +795,7 @@ jobs:
- name: Read the toolchain versions from the metadata
run: |
# The .NET SDK version. The format is '10.0.403 (commit 5a2162bea6)',
# The .NET SDK version. The format is '10.0.404 (commit 2ab2854867)',
# so we extract the version number alone:
dotnet_sdk_version=$(sed -n '4p' metadata.txt | sed 's/[^0-9.]*\([0-9.]*\).*/\1/')
@@ -906,7 +908,7 @@ jobs:
- name: Run the quality gate
run: |
cd "app/Build"
dotnet run verify
dotnet run -- verify
build_main:
name: Build app (${{ matrix.dotnet_runtime }})
+9 -7
View File
@@ -36,6 +36,7 @@ Therefore, before you plan, read, or change anything in one of these areas, read
| a release, or crediting a contributor in a changelog entry or after a merge | `app/Build/AGENTS.md` |
| anything under `app/MindWork AI Studio/Tools/PluginSystem/`, or a new capability of configuration plugins | `app/MindWork AI Studio/Tools/PluginSystem/AGENTS.md` |
| anything under `app/MindWork AI Studio/Tools/ToolCallingSystem/` | `app/MindWork AI Studio/Tools/ToolCallingSystem/AGENTS.md` |
| anything under `app/MindWork AI Studio/AIOperations/` or `app/Tests/AIOperations/`, or a new task which AI Studio hands to a model on its own | `app/MindWork AI Studio/AIOperations/AGENTS.md` |
| anything under `app/MindWork AI Studio/Models/` or `app/Tests/Models/` | `app/MindWork AI Studio/Models/AGENTS.md` |
| anything under `app/MindWork AI Studio/Tools/Services/Indexing/`, or `DataSourceEmbeddingService` | `app/MindWork AI Studio/Tools/Services/Indexing/AGENTS.md` |
| anything under `app/MindWork AI Studio/Tools/Databases/` | `app/MindWork AI Studio/Tools/Databases/AGENTS.md` |
@@ -98,7 +99,7 @@ MindWork AI Studio is a cross-platform desktop application for interacting with
### Build
```bash
cd app/Build
dotnet run build
dotnet run -- build
```
This builds the .NET app as a Tauri "sidecar" binary, which is required even for development.
@@ -108,7 +109,7 @@ instead; see "Cloud sessions" below.
Agents must not start builds through their own shell: agent shells run sandboxed, and `.NET` builds
hit a known sandbox issue there, typically surfacing as `CSSM_ModuleLoad()` or other sandbox-related
failures (for reference: https://github.com/openai/codex/issues/4915). This applies to `dotnet run build`,
failures (for reference: https://github.com/openai/codex/issues/4915). This applies to `dotnet run -- build`,
`dotnet build`, `cargo build`, and similar commands.
Instead, use the JetBrains IDE MCP servers. They execute in the IDE process, which runs outside the
@@ -129,8 +130,8 @@ triggering a new build.
terminal, because they are more than a solution build:
```
mcp__rider__execute_terminal_command command: "cd app/Build && dotnet run build"
mcp__rider__execute_terminal_command command: "cd app/Build && dotnet run collect-i18n"
mcp__rider__execute_terminal_command command: "cd app/Build && dotnet run -- build"
mcp__rider__execute_terminal_command command: "cd app/Build && dotnet run -- collect-i18n"
```
**Rust builds** work the same way through the matching `rustrover` tools.
@@ -139,7 +140,7 @@ Notes:
- The IDE may ask the user to confirm a terminal command. Wait for the result instead of retrying the
command in the agent shell.
- When the IDE is not running or its MCP server is unavailable, fall back to asking the user to run
`cd app/Build && dotnet run build` locally, and wait for their feedback before diagnosing issues or
`cd app/Build && dotnet run -- build` locally, and wait for their feedback before diagnosing issues or
making follow-up changes.
- Treat the build output, error messages, or success confirmation as the source of truth for further
troubleshooting, no matter whether it came from the MCP server or from the user.
@@ -168,12 +169,12 @@ again yourself when `metadata.txt` changes during the session, e.g., after a mer
**Building and testing** happen in the shell:
- The quality gate, the same as in the pipeline: `cd app/Build && dotnet run verify`. It compiles both
- The quality gate, the same as in the pipeline: `cd app/Build && dotnet run -- verify`. It compiles both
the .NET app and the Rust runtime on its way. Narrower checks: `dotnet build "app/MindWork AI Studio.slnx"`,
`dotnet test` in `app/Tests`, and `cargo test` or `cargo clippy --all-targets -- -D warnings` in `runtime/`.
- A cold build of the Rust runtime takes several minutes: run the gate and cargo in the background, or
give them the longest timeout available.
- Skip `dotnet run build`: it needs the Tauri CLI, which is not installed, and the app it produces
- Skip `dotnet run -- build`: it needs the Tauri CLI, which is not installed, and the app it produces
cannot start without a display.
**Committing and pushing** is your job here:
@@ -198,6 +199,7 @@ again yourself when `metadata.txt` changes during the session, e.g., after a mer
- **No automated formatting for Rust or .NET files** - Never run automated formatters on Rust files (`.rs`) or .NET files (`.cs`, `.razor`, `.csproj`, etc.). Only make the minimal manual formatting changes required for the specific edit.
- **Spaces in paths** - Always quote paths with spaces in bash commands
- **Compatibility shims** - Temporary fallback or read-repair code must be documented in `documentation/compatibility-shims/` with an introduced date, remove-after date, code references, and removal checklist. Add a short code comment near the shim that references the document and remove-after date. Check this folder before adding similar fallback logic, and do not extend expired shims without explicit maintainer direction. Do not use this process for permanent settings schema migrations; those belong in `app/MindWork AI Studio/Settings/SettingsMigrations.cs`.
- **Text beyond ASCII** - Users of AI Studio write in many languages and scripts, so never assume that a text is ASCII, nor that it fits one particular code page. Wherever text leaves or enters the app as bytes, e.g., passwords and usernames, file and folder names, mail folders and headers, URLs, CSV, command lines, and network protocols, check which encoding the other side expects. In UTF-8, a character beyond ASCII takes two to four bytes; a code page such as Windows-1252, Windows-1254, or Shift-JIS takes other bytes and lacks most characters of other scripts, e.g., Windows-1252 has no `ş` and no `ẞ`. Use the `Encoding` of .NET with an exception fallback, never one which silently replaces a missing character with `?`. Check the Unicode normalization as well: the same `ä` arrives as one code point (NFC) or as `a` with a combining diaeresis (NFD), e.g., in file names from macOS. Include characters of several scripts in the tests of such code, e.g., `ä ß € é ø ş ł ж 日本 한`, and a decomposed `ä`.
## Wiki
+1 -1
View File
@@ -27,7 +27,7 @@ As of October 2026, we recommend one of these setups, or a newer model of the sa
The repository contains an [AGENTS.md](AGENTS.md), which your agent reads on its own. It describes the architecture, our conventions, and how to build and test AI Studio, and it is binding for every agent working on the code.
Before you open a pull request, run [the quality gate](documentation/Build.md#the-quality-gate) with `dotnet run verify`, then [run the app locally](documentation/Build.md#run-the-app-locally-with-all-your-changes) and try out what you changed.
Before you open a pull request, run [the quality gate](documentation/Build.md#the-quality-gate) with `dotnet run -- verify`, then [run the app locally](documentation/Build.md#run-the-app-locally-with-all-your-changes) and try out what you changed.
Contributions written without AI assistance are welcome as well, as long as they meet the same standard.
+4 -4
View File
@@ -11,6 +11,7 @@ Are you new here? [Read here](#what-is-ai-studio) what AI Studio is.
</h3>
</summary>
- v26.11.1: Added the Mathematics tools as a prototype, so the AI calculates exactly and works with formulas right on your computer; added OneNote sections as a document type for chats, assistants, and local data sources; the chat now shows formulas from LaTeX code blocks, lets you copy and save them, and highlights code blocks itself; added a way to see the complete system prompt of a chat and an overview of all files you sent in it; added a setting for the size of the interface on each of your screens; you can now keep your own prompt guide in the Prompt Optimizer, and IT departments can roll out theirs; Semantic Search and the mail search no longer leave out matches; our installation and enterprise IT guides now live in the wiki; upgraded to .NET 10; and many, many more features, changes, and fixes.
- v26.10.1: Added your mailboxes as a data source in the prototype preview, so the AI can search and read your e-mails from any IMAP provider; added backups of all your data in a single file, for example, to move to a new computer; added the SWOT Analysis Assistant, and the Slide Assistant now creates PowerPoint files in the design of your own template; added a "Send to" menu to every chat message, so you can continue with an assistant or in a new chat; you can now import providers, chat templates, and more that a colleague exported, and chat templates can bring their own provider, profile, and workspace; added support for Mistral Large 4; AI Studio is now signed for macOS and Windows, so macOS opens it like any other app and Windows shows who published it; expanded enterprise IT support with prohibited providers, a prompt for your personal API key on the start page, and organization-wide management of mailboxes, backups, and imports; and many, many more features, changes, and fixes.
- v26.9.1: Added local RAG as a beta feature, so the AI can answer from the documents in your own folders and files; added Semantic Search, so a model searches your data sources itself whenever a question calls for it; added tools that AI models can use on their own, starting with Web Search, Read Web Page, and Search Confluence, available in chats, assistants, batch runs, document analysis policies, chat templates, and assistant plugins; added a token count below the message field and knowledge about each model's context window; added support for OpenAI's GPT-6 Astra, Sol, and Luna, and model plugins for organizations that run their own models; you can now copy an entire chat or roll it back to an earlier answer; and expanded enterprise IT support with organization-wide management of tools and of how data sources are searched.
- v26.8.2: Added protection against prompt injection, so hidden instructions in documents, web pages, and retrieved content are removed before a model reads them; added IONOS' AI Model Hub and LiteLLM as providers, along with speech-to-text and embeddings for Hugging Face, Helmholtz Blablador, GroqCloud, and GWDG SAIA; added knowledge about the latest AI models like Claude Opus 5 & Sonnet 5, Gemini 3.6 & 3.7, and Grok 4, and corrected the abilities shown for many models across all providers; added provider logos throughout the app; AI answers can now be exported as Word, OpenDocument, LaTeX, Markdown, or a webpage, with tables saved separately as spreadsheets; greatly reduced memory usage when working with large documents; and expanded enterprise rollouts to cover every kind of plugin.
@@ -22,14 +23,13 @@ Are you new here? [Read here](#what-is-ai-studio) what AI Studio is.
- v26.5.5: Released voice recording and transcription for all users; added support for multiple chats running at the same time, export options for profiles, chat templates, and ERI data sources, organization-managed ERI servers, and configurable request timeouts; upgraded the native runtime to Tauri v2.
- v26.4.1: Added support for the latest AI models, assistant plugins, a slide planner assistant, a prompt optimization assistant, math rendering in chats, and a configurable start page; released the document analysis assistant and improved enterprise deployment, chat performance, file attachments, and reliability across voice recording, logging, and provider validation.
- v26.2.2: Added Qdrant as a building block for our local RAG preview, added an embedding test option to validate embedding providers, and improved enterprise and configuration plugins with preselected providers, additive preview features, support for multiple configurations, and more reliable synchronization.
- v26.1.1: Added the option to attach files, including images, to chat templates; added support for source code file attachments in chats and document analysis; added a preview feature for recording your own voice for transcription; fixed various bugs in provider dialogs and profile selection.
</details>
## What is AI Studio?
![MindWork AI Studio - Home](documentation/AI_Studio_main.png)
![MindWork AI Studio - Assistants](documentation/mindworks_assistants_complete_4px.png)
![MindWork AI Studio - Home](documentation/Home.png)
![MindWork AI Studio - Assistants](documentation/Assistants.png)
MindWork AI Studio is a free desktop app for macOS, Windows, and Linux. It provides a unified user interface for interaction with Large Language Models (LLM). AI Studio also offers so-called assistants, where prompting is not necessary. You can think of AI Studio like an email program: you bring your own API key for the LLM of your choice and can then use these AI systems with AI Studio. Whether you want to use Google Gemini, OpenAI GPT-6, or even your own local AI models.
@@ -56,7 +56,7 @@ MindWork AI Studio is a free desktop app for macOS, Windows, and Linux. It provi
- Self-hosted models using [llama.cpp](https://github.com/ggerganov/llama.cpp), [ollama](https://github.com/ollama/ollama), [LM Studio](https://lmstudio.ai/), [vLLM](https://github.com/vllm-project/vllm), and [llmman](https://github.com/llmmanorg/llmman)
- [Groq](https://groq.com/)
- [Fireworks](https://fireworks.ai/)
- For scientists and employees of research institutions, we also support [Helmholtz](https://helmholtz.cloud/services/?serviceID=d7d5c597-a2f6-4bd1-b71e-4d6499d98570) and [GWDG](https://gwdg.de/services/application-services/ai-services/) AI services. These are available through federated logins like eduGAIN to all 18 Helmholtz Centers, the Max Planck Society, most German, and many international universities.
- For scientists and employees of research institutions, we also support [Helmholtz](https://helmholtz.cloud/services/?serviceID=d7d5c597-a2f6-4bd1-b71e-4d6499d98570) and [GWDG](https://gwdg.de/services/application-services/ai-services/) AI services. These are available through federated logins like eduGAIN to all 18 Helmholtz Centers, the Max Planck Society, and most German and many international universities.
- **Assistants**: You just want to quickly translate a text? AI Studio has so-called assistants for such and other tasks. No prompting is necessary when working with these assistants.
- **Tools**: AI models can use tools on their own, such as Web Search, Read Web Page, or Search Confluence. When you ask something a model cannot answer from what it knows, it looks it up and answers with the sources it used. You decide which tools a model may use, and you can watch it work.
- **Your own data**: The AI can answer from your own documents. Add folders and files from your computer, or your organization's data through [ERI](https://github.com/MindWorkAI/ERI), as data sources, and the AI searches them whenever a question calls for it and names the passages it used. AI Studio keeps the index on your computer, and you choose the embedding provider, including one you host yourself. As a prototype, the AI can also search and read your mailboxes. Both are preview features, which you enable in the app settings first.
+1 -1
View File
@@ -1,6 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Collect I18N content" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="dotnet run collect-i18n" />
<option name="SCRIPT_TEXT" value="dotnet run -- collect-i18n" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="$PROJECT_DIR$/Build" />
<option name="SCRIPT_OPTIONS" value="" />
+33 -6
View File
@@ -15,9 +15,9 @@ Key structure:
- **Chat/** - Chat functionality and message handling
- **Assistants/** - Pre-configured assistants (translation, summarization, coding, etc.)
- `AssistantBase.razor` - Base component for all assistants
- **Agents/** - contains all agents, e.g., for data source selection, context validation, etc.
- `AgentDataSourceSelection.cs` - Selects appropriate data sources for queries
- `AgentRetrievalContextValidation.cs` - Validates retrieved context relevance
- **AIOperations/** - tasks which AI Studio hands to a model on its own, one request in and one result out,
e.g., the data source selection and the retrieval context validation of the classic RAG process; see the
area guide `AIOperations/AGENTS.md`
- **Tools/PluginSystem/** - Lua-based plugin system
- **Tools/Services/** - Core background services (settings, message bus, data sources, updates)
- **Tools/Rust/** - .NET wrapper for Rust API calls
@@ -29,15 +29,17 @@ Key structure:
- **Naming conventions** - Constants, enum members, and `static readonly` fields use `UPPER_SNAKE_CASE` such as `MY_CONSTANT`.
- **Extension members** - Declare extension methods in an `extension` block of their static class, one block per receiver, never with a `this` parameter: MWAIS0016 refuses the classic form. The `<param>` of the receiver, and of a generic block its `<typeparam>`, belongs on the block, not on its members. A member which only looks something up about its receiver, such as a name, an icon, a flag, a prompt, or an address, is an extension property, named without `Get` or `To`: `format.FileExtension`, `host.IsChatSupported`. It stays a method when it takes parameters, builds something new such as a list or a model profile, parses, scans a collection, or converts into another type, as `GetModelProfile`, `CompactCount`, and `ToSources` do. Check first that the receiver has no instance member of the same name, which would hide the extension. A helper which belongs to the type rather than to one of its values is a static member of the block and is reached through the type: `RID.Current`, `FileExportFormat.TryFromCodeFenceLanguage`. Never name one `Parse` or `TryParse`: C# finds those of `Enum` first.
- **Line breaks** - Every text AI Studio builds ends its lines with LF, on every system: use `AppendLineLF` of `SharedTools.Text` instead of `StringBuilder.AppendLine`, and `'\n'` instead of `Environment.NewLine`. Both of them write CR LF on Windows, where no pipeline runs the tests; MWAIS0018 refuses them, and its code fix offers the replacement. Where a format needs CR LF, write it on purpose, as `CsvWriter.ROW_END` does. A raw string literal and a file which comes with the app keep the line endings of the checkout, CR LF on Windows with `core.autocrlf`: a test which compares such a text with what the app built normalizes it first, e.g. with `ReplaceLineEndings("\n")`.
- **Message Bus** - Singleton event bus for cross-component communication inside the .NET app
- **Prompt injection reports** - The user hears once per action about what the filter removed, as soon as that action ends. Content which belongs to an action carries its scope from `PromptInjectionGuardService.BeginAction` down to where it is read or filtered; whatever is filtered without a scope is reported right away. Pass the scope as a parameter, never through a field or an `AsyncLocal`: the service serves the whole app, and the message bus delivers to other receivers in the execution context of whoever sends.
- **Paths in stored data** - A stored path to a file which AI Studio keeps below the data directory, such as a transcript or a tokenizer copy, is relative to that directory, so that a backup or a copy of the data directory works on another computer, under another user name, or on another OS. Mark such a property with `[JsonConverter(typeof(DataDirectoryRelativePathConverter))]`, for a positional record parameter with `[property: ...]`; in memory, the path stays absolute. Better still, derive the path from IDs and store none, as `VisualBriefingStore` does. Paths to files of the user stay absolute. Chats stored before v26.10.1 are migrated by a compatibility shim, see `documentation/compatibility-shims/2026-10-relative-data-paths.md`.
- **New files and folders in the data or configuration directory** - Whoever adds a file or folder directly to the data or configuration directory, or below `plugins/` or `databases/` one which needs a decision of its own, lists it in `DataBackupContents.ENTRIES`: as part of a backup, or with the reason a backup leaves it out. A backup takes along only what is listed as included, and a restore replaces only that. An entry included in a backup also goes into `REPLACEABLE_ELEMENTS` in `runtime/src/data_restore.rs`; otherwise the runtime refuses to restore it. The folder panel on the information page shows the list to users who back up these folders with a tool of their own.
- **Sending content on** - Content which leaves one place for another, such as the result of an assistant sent to another assistant or a text sent into the chat, travels as a `TextLaunchPayload` through `AssistantLaunchService`, together with the restrictions of where it was written (`ChatRestrictions`, see `ChatThread.CaptureRestrictions`). Never hand over a bare string: the destination would let any provider or tool see content which its source kept from them. Build the payload with `AssistantLaunchService.CreateTextPayloadAsync`, which filters what an AI wrote for prompt injections before it reaches the next model as a message of the user. An assistant which allows sending to it overrides `AssistantBase.ApplyTextLaunchPayload`, and `SendToReceiverTests` checks that every one does; the restrictions themselves are applied centrally in `AssistantBase`.
- **JSON in model answers** - Read the JSON part of a model answer with `ModelAnswerJson`, never with a scanner of your own. It skips the prose and code fences around the JSON but checks nothing, so broken JSON reaches the deserializer unchanged and its message can go back to the model.
- **JSON contracts** - The contracts of all JSON which AI Studio reads or writes are generated while compiling. Each kind of options names the `JsonSerializerContext` which knows its types, with `GenerationMode = Metadata`, as its `TypeInfoResolver` and ends with `.AsReadOnly()`; only `VisualBriefingJson.Canonical` leaves that out, see MWAIS0010. A new JSON type goes into the context of the options it is read or written with, and into `JsonTestRoots` in `app/Tests/Serialization/`, whose contract, defaults, and coverage tests then check it. Give JSON types `set` instead of `init`, because the source generator of .NET 10 drops the initializer of an `init` property which the JSON leaves out, and write a record or a `JsonObject` instead of an anonymous type. Never call System.Text.Json without options, nor with `JsonSerializerOptions.Default`, `.Web`, or a `DefaultJsonTypeInfoResolver`: each of them builds the contracts by reflection, whose code a published build may lack. MWAIS0015 refuses them while compiling, `JsonOptionsResolverTests` checks the resolvers of all options of the app, and the trim smoke test of `dotnet run verify` builds the contract of every type of their contexts in a trimmed build. Reflection itself stays switched on, because Blazor Server needs it for JSON of its own, see `Trimming.props`.
- **JSON contracts** - The contracts of all JSON which AI Studio reads or writes are generated while compiling. Each kind of options names the `JsonSerializerContext` which knows its types, with `GenerationMode = Metadata`, as its `TypeInfoResolver` and ends with `.AsReadOnly()`; only `VisualBriefingJson.Canonical` leaves that out, see MWAIS0010. A new JSON type goes into the context of the options it is read or written with, and into `JsonTestRoots` in `app/Tests/Serialization/`, whose contract, defaults, and coverage tests then check it. Give JSON types `set` instead of `init`, because the source generator of .NET 10 drops the initializer of an `init` property which the JSON leaves out, and write a record or a `JsonObject` instead of an anonymous type. Never call System.Text.Json without options, nor with `JsonSerializerOptions.Default`, `.Web`, or a `DefaultJsonTypeInfoResolver`: each of them builds the contracts by reflection, whose code a published build may lack. MWAIS0015 refuses them while compiling, `JsonOptionsResolverTests` checks the resolvers of all options of the app, and the trim smoke test of `dotnet run -- verify` builds the contract of every type of their contexts in a trimmed build. Reflection itself stays switched on, because Blazor Server needs it for JSON of its own, see `Trimming.props`.
- **Long menus** - MudBlazor keeps a `MudSelect` inside the window by itself, but never a `MudMenu`: a menu taller than the window runs past its edge, and its lower entries cannot be reached. Give every `MudMenu` whose entries come from data, such as the assistants or the profiles, `MaxHeight="@MenuDefaults.MAX_HEIGHT"`, so that it scrolls.
- **Growing popovers** - Since version 9, MudBlazor places an open popover again whenever its content changes size. Content which unfolds later, such as a `MudCollapse` or an `ExpansionPanel` inside a `MudPopover`, therefore stays inside the window and needs no code of its own.
- **Validated text fields** - Without `Immediate` or a `DebounceInterval`, a `MudTextField` passes its text on only when the user leaves it, so an issue stays visible while the user types the text which resolves it. Give every `MudTextField` with a `Validation` which takes typing `DebounceInterval="@TextFieldDefaults.VALIDATION_DEBOUNCE_MILLISECONDS"` and bind its `Value`, not its `Text`: bound by its text, the field also delays the texts its parent sets, e.g., by a reset, and checks them although nobody touched it. `Immediate="@true"` works as well, but renders the parent with every keystroke. `ValidatedTextFieldTests` checks this rule.
- **Encryption** - Initialized before Rust service is marked ready
- **Access to the app server** - Only the app window gets into the Blazor server. `AppAccessMiddleware` runs first in `Program.cs`, right after the host filter, and refuses every request without the session cookie of the window or with an origin other than the app's own. Add no exception for any path, not even for static files: `AppAccessPipelineTests` checks the order in `Program.cs`. Since nothing but the window holds the cookie, the app never sends a request to its own server: read files below `wwwroot/` through `WebRootFiles`. The system browser gets no cookie either, so never open a URL of the app server there; offer a save dialog through `RustService` instead, as the ERI Server assistant does for its specification. `runtime/AGENTS.md` describes the runtime side.
- **Debug environment** - Reads `startup.env` file with IPC credentials
@@ -72,6 +74,31 @@ The app's texts are localized in two steps, and the developer always does the fi
**Moving a `TB()` text into another class gives it a new I18N key**, so its translation is made anew during
the next localization run.
**A text with several lines**, such as a notice in Markdown, is one raw string literal right after the
parenthesis: `TB("""`, the indented lines of the text, and `""")` on a line of its own. The collector reads
every literal as the compiler does, with its escape sequences and without the indentation of a raw literal,
and the translations keep the line breaks. A text which is not one literal, such as an interpolated string
or a concatenation, gets no translation; the collector warns about it.
**A text which addresses the reader**, with "you" or by asking them to do something in a sentence, uses `TA()`
instead of `T()` or `TB()`, and so does a label with "your", such as "Your name"; other labels, buttons, titles,
and examples stay with those. A thank-you on the supporters page addresses the supporter, not the reader, and
stays with `T()`. `AddressedTextsTests` checks the rule: a text with "you", or one whose German translation says
"Sie" inside a sentence, needs `TA()`. A static class gets a `TA()` of its own next to its `TB()`:
`private static string TA(string fallbackEN) => I18N.I.TA(fallbackEN, typeof(X).Namespace, nameof(X));`, in a
component, which inherits `TA()`, as `private new static string TA(...)`. A base class whose texts the collector
files under its own name, such as `AssistantBase`, uses
`private new string TA(string fallbackEN) => this.TA(fallbackEN, typeof(X).Namespace, nameof(X));`.
The collector files such a text under two keys: the usual one, translated with the formal address, such as "Sie"
in German, and the same key ending in `::INFORMAL`, translated with the informal address, such as "du". The
localization assistant writes the informal variant from the formal translation and changes only the form of
address, in German with "du" and "dein" in lowercase; whoever corrects a formal translation in the review
corrects its informal variant alike. In US English, it gives every informal variant the words of the formal text
of the plugin, so that English offers no choice; the test checks that as well. Which one the app shows follows `I18N.I.AddressForm`; when the language in use lacks the informal variant, it shows the
formal one. The option "Form of address" of the app settings decides, `DataApp.AddressForm`, see `Program.cs`;
the settings show it only in a language with both forms. A change sends `Event.ADDRESS_FORM_CHANGED`, which
every component handles by rendering again.
## Plugin System
**Location:** `app/MindWork AI Studio/Plugins/`
@@ -116,8 +143,8 @@ knowledge.
RAG is available as a beta preview feature. Architecture:
- **External Retrieval Interface (ERI)** - Contract for integrating external data sources
- **Data Sources** - Local files and external data via ERI servers
- **Two ways to search** - By default, the chat model searches the data sources itself through the tool `semantic_search`, whenever a question calls for it. The classic process (`AISrcSelWithRetCtxVal`) searches them with every message instead, when the user chose so per chat (`DataSourceOptions.RetrievalMode`) or whenever the tool cannot be offered. `ToolRegistry.GetEffectiveRetrievalModeAsync` decides between the two; pass its answer to `DataSourceService`, because the agents only count as providers that see the data when they actually run. Both ways decide where a chat may still send data once their passages reached it through `DataSourceRequirements.Of`, never with a check of their own: a way which demands less leaves the other one open. See "Searching Data Sources" in `documentation/Tools.md`.
- **Agents** - AI agents select data sources and validate retrieval quality, in the classic process only
- **Two ways to search** - By default, the chat model searches the data sources itself through the tool `semantic_search`, whenever a question calls for it. The classic process (`AISrcSelWithRetCtxVal`) searches them with every message instead, when the user chose so per chat (`DataSourceOptions.RetrievalMode`) or whenever the tool cannot be offered. `ToolRegistry.GetEffectiveRetrievalModeAsync` decides between the two; pass its answer to `DataSourceService`, because the AI operations of the classic process only count as providers that see the data when they actually run. Both ways decide where a chat may still send data once their passages reached it through `DataSourceRequirements.Of`, never with a check of their own: a way which demands less leaves the other one open. See "Searching Data Sources" in `documentation/Tools.md`.
- **AI operations** - select data sources and validate retrieval quality, in the classic process only; see `AIOperations/AGENTS.md`
- **Embedding providers** - Support for various embedding models
- **Vector database** - Qdrant Edge, embedded in the Rust runtime; see "Databases" below
- **Index database** - SQLite, holding the file fingerprints and the chunk texts for full-text search; see "Databases" below
+9 -1
View File
@@ -12,7 +12,7 @@ changelog entries.
`gh pr list -R MindWorkAI/AI-Studio --state merged --limit 1000 --search "merged:>=<YYYY-MM-DD>" --json author --jq '[.[].author.login] | unique | .[]'`,
with the date of the last release tag from `git log -1 --format=%cs <last release tag>`; skip bots
3. Commit changelog
4. Run from `app/Build`: `dotnet run release --action <build|month|year>`
4. Run from `app/Build`: `dotnet run -- release --action <build|month|year>`
5. Create PR with version bump and changes
6. After PR merge, maintainer creates git tag: `vX.Y.Z`
7. GitHub Actions builds release binaries for all platforms
@@ -43,6 +43,14 @@ order of the list is chronological only. Bug reports
alone and commissioned work outside this repository get no entry on the supporters page; the changelog may
still thank them.
**Ideas, expertise, and concepts.** A person whose idea, expertise, or concept shapes a part of AI Studio,
such as the researcher who designed an assistant and wrote its content, gets an entry in the list "Ideas,
Expertise, and Concepts" on the supporters page, also without any contribution to this repository. The maintainer decides who counts, and the person agrees
to be named. Their entry gives their full name, since they may have no GitHub account, and links to a page
of their own if they have one:
`<Supporter Name="<first name> <last name>" Type="SupporterType.INDIVIDUAL" URL="<their page>" Acknowledgment="@T("…")"/>`,
or without `URL`. The list is sorted by when the idea, expertise, or concept came to AI Studio.
The credit choice in the pull request template is binding:
- **"Credit me with my GitHub username only":** use the GitHub username alone. No real name, neither in
+1 -1
View File
@@ -11,7 +11,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.CommandLine" Version="2.0.14" />
<PackageReference Include="System.CommandLine" Version="2.0.15" />
</ItemGroup>
<ItemGroup>
+9 -109
View File
@@ -6,39 +6,6 @@ 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_TAG1 = """
")
""";
private const string END_TAG2 = """
",
""";
private static readonly (string Tag, int Length)[] START_TAGS =
[
(START_TAG1, START_TAG1.Length),
(START_TAG2, START_TAG2.Length),
(START_TAG3, START_TAG3.Length)
];
private static readonly string[] END_TAGS =
[
END_TAG1,
END_TAG2
];
/// <summary>
/// Defines the command "collect-i18n".
/// </summary>
@@ -82,7 +49,7 @@ public sealed partial class CollectI18NKeysCommand
continue;
var content = await File.ReadAllTextAsync(filePath, Encoding.UTF8);
var matches = this.FindAllTextTags(content, filePath, warnings);
var matches = I18NSourceScanner.FindTexts(content, filePath, warnings);
if (matches.Count == 0)
continue;
@@ -98,9 +65,14 @@ public sealed partial class CollectI18NKeysCommand
var langNamespace = $"{ns}.{name}".ToUpperInvariant();
foreach (var match in matches)
{
// The key in the format A.B.C.D.T{hash}:
var key = $"UI_TEXT_CONTENT.{langNamespace}.T{match.ToFNV32()}";
allI18NContent.TryAdd(key, match);
// The key in the format A.B.C.D.T{hash}, with the hash the app computes at runtime:
var key = $"UI_TEXT_CONTENT.{langNamespace}.T{I18NKeyHash.Of(match.Text)}";
var text = I18NKeyHash.NormalizeLineEndings(match.Text);
allI18NContent.TryAdd(key, text);
// A text of TA() addresses the reader, so it gets a second key for the informal address:
if (match.HasAddressVariants)
allI18NContent.TryAdd(I18NAddressVariant.InformalKeyOf(key), text);
}
}
@@ -181,78 +153,6 @@ public sealed partial class CollectI18NKeysCommand
return sb.ToString();
}
private List<string> FindAllTextTags(ReadOnlySpan<char> fileContent, string filePath, List<string> warnings)
{
(int Index, int Len) FindNextStart(ReadOnlySpan<char> content)
{
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);
}
int FindNextEnd(ReadOnlySpan<char> content)
{
var bestIndex = -1;
foreach (var tag in END_TAGS)
{
var index = content.IndexOf(tag);
if (index != -1 && (bestIndex == -1 || index < bestIndex))
bestIndex = index;
}
return bestIndex;
}
var matches = new List<string>();
var startIdx = FindNextStart(fileContent);
var content = fileContent;
while (startIdx.Index > -1)
{
//
// In some cases, after the initial " there follow more " characters.
// We need to skip them:
//
content = content[(startIdx.Index + startIdx.Len)..];
while(content[0] == '"')
content = content[1..];
var endIdx = FindNextEnd(content);
if (endIdx == -1)
break;
var match = content[..endIdx];
while (match[^1] == '"')
match = match[..^1];
var text = match.ToString();
//
// We read the raw source text, whereas the app hashes the unescaped string at
// runtime. Thus, any escape sequence makes both hashes differ, so that the text
// never finds its translation. Since we cannot detect this at runtime, we warn
// about it here:
//
if(text.Contains('\\'))
warnings.Add($"- Warning: The text '{text}' in the file '{filePath}' contains an escape sequence. Its key does not match the key the app looks up at runtime, so this text stays untranslated. Please use a raw string literal instead.");
matches.Add(text);
startIdx = FindNextStart(content);
}
return matches;
}
private bool IsSupportedSourceFile(string filePath) =>
filePath.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) ||
filePath.EndsWith(".razor", StringComparison.OrdinalIgnoreCase);
+12
View File
@@ -0,0 +1,12 @@
namespace Build.Commands;
/// <summary>
/// The CPU architectures for which the Flatpak of AI Studio is built.
/// </summary>
public enum FlatpakArchitecture
{
NONE,
AARCH64,
X86_64,
}
@@ -0,0 +1,53 @@
namespace Build.Commands;
public static class FlatpakArchitectureExtensions
{
/// <param name="architecture">The CPU architecture of the Flatpak.</param>
extension(FlatpakArchitecture architecture)
{
/// <summary>
/// The name of the architecture in Flatpak and on Linux, as uname -m reports it.
/// </summary>
public string FlatpakName => architecture switch
{
FlatpakArchitecture.AARCH64 => "aarch64",
FlatpakArchitecture.X86_64 => "x86_64",
_ => string.Empty,
};
/// <summary>
/// The platform of a Docker image which runs on this architecture.
/// </summary>
public string DockerPlatform => architecture switch
{
FlatpakArchitecture.AARCH64 => "linux/arm64",
FlatpakArchitecture.X86_64 => "linux/amd64",
_ => string.Empty,
};
/// <summary>
/// The file name of the bundle of AI Studio, the same as the CI of the Flatpak repository gives it.
/// </summary>
public string AppBundleName => $"MindWork AI Studio_{architecture.FlatpakName}.flatpak";
/// <summary>
/// The file name of the bundle of the Pandoc plugin, the same as the CI of the Flatpak repository gives it.
/// </summary>
public string PandocBundleName => $"MindWork AI Studio Plugin Pandoc_{architecture.FlatpakName}.flatpak";
/// <summary>
/// Finds the architecture for a name, as Flatpak, Linux, or Docker write it.
/// </summary>
/// <param name="name">The name, e.g., aarch64, arm64, x86_64, or amd64.</param>
/// <returns>The architecture, or NONE for an unknown name.</returns>
public static FlatpakArchitecture FromName(string name) => name.Trim().ToLowerInvariant() switch
{
"aarch64" or "arm64" => FlatpakArchitecture.AARCH64,
"x86_64" or "amd64" => FlatpakArchitecture.X86_64,
_ => FlatpakArchitecture.NONE,
};
}
}
+817
View File
@@ -0,0 +1,817 @@
using System.Diagnostics;
using System.Formats.Tar;
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.RegularExpressions;
using Build.Tools;
namespace Build.Commands;
/// <summary>
/// Builds the Flatpak of AI Studio and its Pandoc plugin in Docker, the way the CI of the Flatpak repository does.
/// </summary>
/// <remarks>
/// Neither macOS nor Windows has flatpak-builder. Docker brings the CI image of the Flatpak repository instead, so the
/// build runs alike on every host with Docker, be it Docker Desktop, OrbStack, or Docker on Linux. Files go in and out
/// by docker cp only, never through a bind mount, whose paths and file permissions differ between these hosts. The
/// build lives in a container and a volume of its own, which the command removes at the end, also after a failure or
/// Ctrl+C. The script Flatpak/build-in-container.sh does the work inside the container.
/// </remarks>
public sealed partial class FlatpakCommand
{
private const string AI_STUDIO_REPOSITORY = "https://github.com/MindWorkAI/AI-Studio";
private const string FLATPAK_REPOSITORY = "https://github.com/MindWorkAI/Flatpak";
private const string MAIN_BRANCH = "refs/heads/main";
private const string DOCKER_LABEL = "org.mindworkai.build=flatpak";
private const string CONTAINER_SCRIPT_DIRECTORY = "Flatpak";
private const string CONTAINER_SCRIPT_NAME = "build-in-container.sh";
private const string CONTAINER_INPUT_DIRECTORY = "input";
private const string CONTAINER_CHECKOUT_DIRECTORY = "ai-studio";
private const string CONTAINER_BUILD_DIRECTORY = "/build";
private const string CONTAINER_OUTPUT_DIRECTORY = "/out";
/// <summary>
/// The exit code after Ctrl+C, as shells report a process which SIGINT ended.
/// </summary>
private const int CANCELLED_EXIT_CODE = 130;
private const UnixFileMode EXECUTABLE_MODE =UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute;
private static readonly TimeSpan CONNECT_TIMEOUT = TimeSpan.FromSeconds(30);
private static readonly TimeSpan REQUEST_TIMEOUT = TimeSpan.FromSeconds(60);
//
// Without a handler of its own, HttpClient waits for a connection without any limit, see Pdfium.cs:
//
private static readonly HttpClient CLIENT = new(new SocketsHttpHandler { ConnectTimeout = CONNECT_TIMEOUT })
{
Timeout = REQUEST_TIMEOUT
};
private readonly Lock cancellationLock = new();
private bool isCancelled;
private bool isContainerStarted;
private string containerName = string.Empty;
private string volumeName = string.Empty;
[GeneratedRegex(@"^\s*image:\s*(\S+)\s*$", RegexOptions.Multiline)]
private static partial Regex WorkflowImageRegex();
[GeneratedRegex("^[0-9a-f]{40}$")]
private static partial Regex CommitHashRegex();
/// <summary>
/// Defines the command "flatpak".
/// </summary>
public static Command CreateCommand()
{
var output = new Option<string>("--output", "-o")
{
Description = "The folder for the bundles of AI Studio and its Pandoc plugin, outside the repository, e.g., ~/Downloads/flatpak. The command creates it when it does not exist",
Required = true,
};
var source = new Option<string>("--source", "-s") { Description = $"Which state of AI Studio goes into the Flatpak: {string.Join("; ", FlatpakSource.All.Select(candidate => $"{candidate.Name}, {candidate.Description}"))}" };
source.AcceptOnlyFromAmong([.. FlatpakSource.All.Select(candidate => candidate.Name)]);
var pullRequest = new Option<int?>("--pr", "-p") { Description = "The number of the pull request to build, e.g., 1219; implies --source pr" };
var architecture = new Option<string>("--arch", "-a") { Description = "The CPU architecture of the Flatpak, aarch64 or x86_64. Defaults to the one of the Docker host; the other one needs an emulation such as Rosetta and takes much longer" };
architecture.AcceptOnlyFromAmong(FlatpakArchitecture.AARCH64.FlatpakName, FlatpakArchitecture.X86_64.FlatpakName);
var command = new Command("flatpak", "Build the Flatpak of AI Studio and its Pandoc plugin in Docker, the way a release builds them. Without --source or --pr, the command asks what to build") { output, source, pullRequest, architecture };
command.SetAction((parseResult, _) => new FlatpakCommand().BuildFlatpak(parseResult.GetRequiredValue(output), parseResult.GetValue(source), parseResult.GetValue(pullRequest), parseResult.GetValue(architecture)));
return command;
}
public async Task<int> BuildFlatpak(string output, string? sourceName, int? pullRequestOption, string? architectureName)
{
if (!Environment.IsWorkingDirectoryValid())
return 1;
var outputDirectory = PrepareOutputDirectory(output);
if (outputDirectory is null)
return 1;
Console.WriteLine("==============================");
Console.WriteLine("- Building the Flatpak of AI Studio in Docker ...");
var workingDirectory = Directory.GetCurrentDirectory();
var dockerVersion = await CommandRunner.ReadOutputAsync(workingDirectory, "docker", ["version", "--format", "{{.Server.Version}}"]);
if (dockerVersion.ExitCode is CommandRunner.COULD_NOT_START)
return 1;
if (dockerVersion.ExitCode is not 0)
{
Console.WriteLine("- Error: Docker does not answer. Start Docker, e.g., Docker Desktop or OrbStack, and try again.");
return 1;
}
//
// The questions come before the command handles Ctrl+C itself: up to here, nothing needs to be cleaned
// up, so Ctrl+C may end the command at once, also while it waits for an answer.
//
var source = DetermineSource(sourceName, pullRequestOption);
if (source is FlatpakSource.NONE)
return 1;
int? pullRequestNumber = null;
if (source is FlatpakSource.PULL_REQUEST)
{
pullRequestNumber = pullRequestOption ?? AskForPullRequestNumber();
if (pullRequestNumber is null)
return 1;
if (pullRequestNumber <= 0)
{
Console.WriteLine($"- Error: {pullRequestNumber} is not the number of a pull request.");
return 1;
}
}
Console.CancelKeyPress += this.OnCancelKeyPress;
try
{
return await this.BuildInDockerAsync(workingDirectory, dockerVersion.Text.Trim(), outputDirectory, source, pullRequestNumber, architectureName);
}
finally
{
Console.CancelKeyPress -= this.OnCancelKeyPress;
}
}
private async Task<int> BuildInDockerAsync(string workingDirectory, string dockerVersion, string outputDirectory, FlatpakSource source, int? pullRequestNumber, string? architectureName)
{
var stopwatch = Stopwatch.StartNew();
var architecture = await DetermineArchitectureAsync(workingDirectory, architectureName);
if (architecture is FlatpakArchitecture.NONE || this.IsCancelled)
return this.ExitCodeAfterFailure;
string? aiStudioCommit;
var aiStudioDescription = source.Description;
IReadOnlyList<string> localFiles = [];
var repositoryDirectory = Environment.GetRepositoryDirectory();
switch (source)
{
case FlatpakSource.PULL_REQUEST when pullRequestNumber is { } number:
aiStudioCommit = await ResolveRemoteCommitAsync(workingDirectory, AI_STUDIO_REPOSITORY, $"refs/pull/{number}/head", $"no pull request #{number}");
if (aiStudioCommit is not null)
aiStudioDescription = await DescribePullRequestAsync(number);
break;
case FlatpakSource.LOCAL:
aiStudioCommit = await ReadLocalHeadAsync(repositoryDirectory);
var files = await ListLocalFilesAsync(repositoryDirectory);
if (files is null)
return 1;
localFiles = files;
aiStudioDescription = await DescribeLocalCheckoutAsync(repositoryDirectory);
break;
default:
aiStudioCommit = await ResolveRemoteCommitAsync(workingDirectory, AI_STUDIO_REPOSITORY, MAIN_BRANCH, "no branch main");
break;
}
if (aiStudioCommit is null || this.IsCancelled)
return this.ExitCodeAfterFailure;
var flatpakCommit = await ResolveRemoteCommitAsync(workingDirectory, FLATPAK_REPOSITORY, MAIN_BRANCH, "no branch main");
if (flatpakCommit is null || this.IsCancelled)
return this.ExitCodeAfterFailure;
var image = await ReadCiImageAsync(flatpakCommit);
if (image is null || this.IsCancelled)
return this.ExitCodeAfterFailure;
Console.WriteLine($"- Docker {dockerVersion} builds the Flatpak for {architecture.FlatpakName}:");
Console.WriteLine($" - AI Studio: {aiStudioDescription}, commit {aiStudioCommit}");
Console.WriteLine($" - Flatpak repository: main of MindWorkAI/Flatpak, commit {flatpakCommit}");
Console.WriteLine($" - Image: {image}");
Console.WriteLine($" - Output: {outputDirectory}");
await ReportLeftoversAsync(workingDirectory);
if (await CommandRunner.RunAsync(workingDirectory, "docker", ["pull", "--platform", architecture.DockerPlatform, image]) is not 0 || this.IsCancelled)
{
if (!this.IsCancelled)
Console.WriteLine($"- Error: Docker could not pull the image {image} for {architecture.DockerPlatform}.");
return this.ExitCodeAfterFailure;
}
var environment = new Dictionary<string, string>
{
["ARCH"] = architecture.FlatpakName,
["SOURCE"] = source.Name,
["FLATPAK_URL"] = FLATPAK_REPOSITORY,
["FLATPAK_COMMIT"] = flatpakCommit,
["APP_BUNDLE"] = architecture.AppBundleName,
["PANDOC_BUNDLE"] = architecture.PandocBundleName,
["BUILD_DIRECTORY"] = CONTAINER_BUILD_DIRECTORY,
["OUT_DIRECTORY"] = CONTAINER_OUTPUT_DIRECTORY,
};
//
// The local checkout has no commit which the container could fetch. The script commits the copied files in
// a repository of its own instead and builds from there:
//
if (source is FlatpakSource.LOCAL)
environment["LOCAL_CHECKOUT"] = $"/{CONTAINER_INPUT_DIRECTORY}/{CONTAINER_CHECKOUT_DIRECTORY}";
else
{
environment["AI_STUDIO_URL"] = AI_STUDIO_REPOSITORY;
environment["AI_STUDIO_COMMIT"] = aiStudioCommit;
}
var name = $"aistudio-flatpak-{architecture.FlatpakName}-{DateTime.UtcNow:yyyyMMdd-HHmmss}";
try
{
var exitCode = await this.BuildInContainerAsync(workingDirectory, name, image, architecture, environment, repositoryDirectory, localFiles, outputDirectory);
if (exitCode is 0)
Console.WriteLine($"- Done after {(int)stopwatch.Elapsed.TotalMinutes} min {stopwatch.Elapsed.Seconds} s.");
return exitCode;
}
finally
{
await this.RemoveContainerAndVolumeAsync(workingDirectory);
}
}
private async Task<int> BuildInContainerAsync(string workingDirectory, string name, string image, FlatpakArchitecture architecture, IReadOnlyDictionary<string, string> environment, string repositoryDirectory, IReadOnlyList<string> localFiles, string outputDirectory)
{
var volume = await CommandRunner.ReadOutputAsync(workingDirectory, "docker", ["volume", "create", "--label", DOCKER_LABEL, name]);
if (volume.ExitCode is not 0)
{
Console.WriteLine($"- Error: Docker could not create the volume {name}.");
return 1;
}
lock (this.cancellationLock)
this.volumeName = name;
List<string> arguments = ["create", "--name", name, "--label", DOCKER_LABEL, "--init", "--privileged", "--platform", architecture.DockerPlatform, "--volume", $"{name}:{CONTAINER_BUILD_DIRECTORY}"];
foreach (var (key, value) in environment)
arguments.AddRange(["--env", $"{key}={value}"]);
arguments.AddRange([image, "bash", $"/{CONTAINER_INPUT_DIRECTORY}/{CONTAINER_SCRIPT_NAME}"]);
var container = await CommandRunner.ReadOutputAsync(workingDirectory, "docker", arguments);
if (container.ExitCode is not 0)
{
Console.WriteLine($"- Error: Docker could not create the container {name}.");
return 1;
}
lock (this.cancellationLock)
this.containerName = name;
Console.WriteLine($"- Created the container and the volume {name}.");
var script = await ReadContainerScriptAsync();
if (await CommandRunner.RunAsync(workingDirectory, "docker", ["cp", "-", $"{name}:/"], stream => WriteScriptArchiveAsync(stream, script)) is not 0)
{
Console.WriteLine($"- Error: Docker could not copy the build script into the container {name}.");
return 1;
}
if (localFiles.Count > 0)
{
var megabytes = localFiles.Sum(file => new FileInfo(Path.Join(repositoryDirectory, file)).Length) / 1024 / 1024;
Console.WriteLine($"- Copying {localFiles.Count} files ({megabytes} MB) of the local checkout into the container ...");
if (await CommandRunner.RunAsync(workingDirectory, "docker", ["cp", "-", $"{name}:/"], stream => WriteCheckoutArchiveAsync(stream, repositoryDirectory, localFiles)) is not 0 || this.IsCancelled)
{
if (!this.IsCancelled)
Console.WriteLine($"- Error: Docker could not copy the local checkout into the container {name}.");
return this.ExitCodeAfterFailure;
}
}
lock (this.cancellationLock)
{
if (this.isCancelled)
return CANCELLED_EXIT_CODE;
this.isContainerStarted = true;
}
//
// docker start returns early when it gets a signal of its own, such as the Ctrl+C of the terminal, and the
// container may still be running then. Only the state of the container tells whether the build ended, and how:
//
var startExitCode = await CommandRunner.RunAsync(workingDirectory, "docker", ["start", "--attach", name]);
var buildExitCode = this.IsCancelled ? null : await ReadBuildExitCodeAsync(workingDirectory, name);
if (this.IsCancelled)
{
Console.WriteLine("- The build was cancelled.");
return CANCELLED_EXIT_CODE;
}
if (buildExitCode is null)
{
Console.WriteLine($"- Error: The container {name} did not finish its build; docker start ended with exit code {startExitCode}.");
return 1;
}
if (buildExitCode is not 0)
{
Console.WriteLine($"- Error: The build in the container failed with exit code {buildExitCode}. Its output above says why.");
return 1;
}
//
// Bundles of an earlier build would otherwise pass for those of this one, should the container
// not deliver one of them:
//
foreach (var bundleName in new[] { architecture.AppBundleName, architecture.PandocBundleName })
File.Delete(Path.Join(outputDirectory, bundleName));
if (await CommandRunner.RunAsync(workingDirectory, "docker", ["cp", $"{name}:{CONTAINER_OUTPUT_DIRECTORY}/.", outputDirectory]) is not 0)
{
Console.WriteLine($"- Error: Docker could not copy the bundles out of the container {name}.");
return 1;
}
return await ReportBundlesAsync(outputDirectory, architecture) ? 0 : 1;
}
/// <summary>
/// Reads how the build in the container ended.
/// </summary>
/// <returns>The exit code of the build script, or null when the container has not run to its end.</returns>
private static async Task<int?> ReadBuildExitCodeAsync(string workingDirectory, string name)
{
var state = await CommandRunner.ReadOutputAsync(workingDirectory, "docker", ["inspect", "--format", "{{.State.Status}} {{.State.ExitCode}}", name]);
var parts = state.Text.Trim().Split(' ');
if (state.ExitCode is not 0 || parts.Length is not 2 || parts[0] is not "exited" || !int.TryParse(parts[1], out var exitCode))
return null;
return exitCode;
}
private bool IsCancelled
{
get
{
lock (this.cancellationLock)
return this.isCancelled;
}
}
private int ExitCodeAfterFailure => this.IsCancelled ? CANCELLED_EXIT_CODE : 1;
/// <summary>
/// Stops the build at the first Ctrl+C, so that the command can still remove its container and volume.
/// </summary>
/// <remarks>
/// The shell inside the container waits for flatpak-builder and passes the signal on only after that, so the
/// container gets killed instead. A second Ctrl+C ends the command at once and names what it leaves behind.
/// </remarks>
private void OnCancelKeyPress(object? sender, ConsoleCancelEventArgs eventArgs)
{
string container;
bool isStarted;
lock (this.cancellationLock)
{
if (this.isCancelled)
{
Console.WriteLine("- Quitting at once.");
WriteRemovalCommands(this.containerName, this.volumeName);
return;
}
this.isCancelled = true;
container = this.containerName;
isStarted = this.isContainerStarted;
}
eventArgs.Cancel = true;
Console.WriteLine("- Cancelling: the build stops, and the command removes its container and volume. Press Ctrl+C again to quit at once.");
if (isStarted)
_ = CommandRunner.ReadOutputAsync(Directory.GetCurrentDirectory(), "docker", ["kill", container]);
}
private async Task RemoveContainerAndVolumeAsync(string workingDirectory)
{
string container;
string volume;
lock (this.cancellationLock)
{
container = this.containerName;
volume = this.volumeName;
}
var leftContainer = string.Empty;
if (!string.IsNullOrWhiteSpace(container) && (await CommandRunner.ReadOutputAsync(workingDirectory, "docker", ["rm", "--force", container])).ExitCode is not 0)
leftContainer = container;
var leftVolume = string.Empty;
if (!string.IsNullOrWhiteSpace(volume) && (await CommandRunner.ReadOutputAsync(workingDirectory, "docker", ["volume", "rm", volume])).ExitCode is not 0)
leftVolume = volume;
if (string.IsNullOrWhiteSpace(leftContainer) && string.IsNullOrWhiteSpace(leftVolume))
{
if (!string.IsNullOrWhiteSpace(volume))
Console.WriteLine($"- Removed the container and the volume {volume}.");
return;
}
Console.WriteLine("- Error: Docker could not remove everything this build created.");
WriteRemovalCommands(leftContainer, leftVolume);
}
private static void WriteRemovalCommands(string container, string volume)
{
if (string.IsNullOrWhiteSpace(container) && string.IsNullOrWhiteSpace(volume))
return;
Console.WriteLine(" Remove what is left with:");
if (!string.IsNullOrWhiteSpace(container))
Console.WriteLine($" docker rm --force {container}");
if (!string.IsNullOrWhiteSpace(volume))
Console.WriteLine($" docker volume rm {volume}");
}
/// <summary>
/// Resolves the output folder and creates it when it does not exist.
/// </summary>
/// <remarks>
/// A folder inside the repository is refused: the bundles would show up in git status, and a build of the local
/// checkout would copy them into the container.
/// </remarks>
/// <param name="output">The folder as the user gave it; a leading ~ stands for the home folder.</param>
/// <returns>The absolute path of the folder, or null when it cannot be used.</returns>
private static string? PrepareOutputDirectory(string output)
{
var outputDirectory = Path.GetFullPath(ExpandHomeDirectory(output));
var repositoryDirectory = Environment.GetRepositoryDirectory();
var relativePath = Path.GetRelativePath(repositoryDirectory, outputDirectory);
var isOutsideRepository = Path.IsPathRooted(relativePath) || relativePath == ".." || relativePath.StartsWith($"..{Path.DirectorySeparatorChar}", StringComparison.Ordinal);
if (!isOutsideRepository)
{
Console.WriteLine($"- Error: The output folder '{outputDirectory}' lies inside the repository. The bundles would show up in git status, and a build of the local checkout would copy them into the container.");
Console.WriteLine($" Choose a folder outside of '{repositoryDirectory}', e.g., --output ~/Downloads/flatpak.");
return null;
}
try
{
Directory.CreateDirectory(outputDirectory);
return outputDirectory;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
Console.WriteLine($"- Error: Could not create the output folder '{outputDirectory}': {exception.Message}");
return null;
}
}
private static string ExpandHomeDirectory(string path)
{
var homeDirectory = global::System.Environment.GetFolderPath(global::System.Environment.SpecialFolder.UserProfile);
if (path == "~")
return homeDirectory;
if (path.StartsWith("~/", StringComparison.Ordinal) || path.StartsWith(@"~\", StringComparison.Ordinal))
return Path.Join(homeDirectory, path[2..]);
return path;
}
private static async Task<FlatpakArchitecture> DetermineArchitectureAsync(string workingDirectory, string? architectureName)
{
if (!string.IsNullOrWhiteSpace(architectureName))
return FlatpakArchitecture.FromName(architectureName);
var dockerInfo = await CommandRunner.ReadOutputAsync(workingDirectory, "docker", ["info", "--format", "{{.Architecture}}"]);
if (dockerInfo.ExitCode is not 0)
{
Console.WriteLine("- Error: Docker did not name the architecture of its host. Choose one with --arch aarch64 or --arch x86_64.");
return FlatpakArchitecture.NONE;
}
var architecture = FlatpakArchitecture.FromName(dockerInfo.Text);
if (architecture is FlatpakArchitecture.NONE)
Console.WriteLine($"- Error: The Docker host runs on '{dockerInfo.Text.Trim()}', for which there is no Flatpak. Choose one with --arch aarch64 or --arch x86_64.");
return architecture;
}
/// <summary>
/// Asks a repository on GitHub which commit a reference points to.
/// </summary>
/// <remarks>
/// The command fixes every commit before the build starts. A push during the build therefore cannot mix two
/// states, and the output names exactly what the Flatpak contains.
/// </remarks>
/// <param name="workingDirectory">Where git should run.</param>
/// <param name="repository">The URL of the repository.</param>
/// <param name="reference">The full name of the reference, e.g., refs/heads/main.</param>
/// <param name="whatIsMissing">What the repository lacks when the reference does not exist, e.g., "no branch main".</param>
/// <returns>The hash of the commit, or null when the repository has no such reference.</returns>
private static async Task<string?> ResolveRemoteCommitAsync(string workingDirectory, string repository, string reference, string whatIsMissing)
{
var references = await CommandRunner.ReadOutputAsync(workingDirectory, "git", ["ls-remote", repository, reference]);
if (references.ExitCode is not 0)
{
Console.WriteLine($"- Error: Could not ask {repository} for '{reference}'.");
return null;
}
foreach (var line in references.Text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var parts = line.Split('\t');
if (parts.Length is 2 && parts[1] == reference && CommitHashRegex().IsMatch(parts[0]))
return parts[0];
}
Console.WriteLine($"- Error: {repository} has {whatIsMissing}.");
return null;
}
/// <summary>
/// Decides which state of AI Studio goes into the Flatpak, and asks when the options leave it open.
/// </summary>
/// <returns>The source, or NONE when the options contradict each other or nobody answered.</returns>
private static FlatpakSource DetermineSource(string? sourceName, int? pullRequestOption)
{
var source = string.IsNullOrWhiteSpace(sourceName) ? FlatpakSource.NONE : FlatpakSource.FromName(sourceName);
if (pullRequestOption is not null)
{
if (source is FlatpakSource.NONE or FlatpakSource.PULL_REQUEST)
return FlatpakSource.PULL_REQUEST;
Console.WriteLine($"- Error: --pr builds a pull request, while --source {source.Name} builds something else. Leave out one of them.");
return FlatpakSource.NONE;
}
return source is FlatpakSource.NONE ? AskForSource() : source;
}
private static FlatpakSource AskForSource()
{
var sources = FlatpakSource.All;
Console.WriteLine("- Which state of AI Studio should go into the Flatpak?");
for (var index = 0; index < sources.Count; index++)
Console.WriteLine($" {index + 1}) {sources[index].Description}");
while (true)
{
Console.Write($"- Your choice (1-{sources.Count}): ");
var answer = Console.ReadLine();
if (answer is null)
{
Console.WriteLine();
Console.WriteLine($"- Error: No answer arrived. Choose with --source {string.Join(", --source ", sources.Select(candidate => candidate.Name))}, or with --pr <number>.");
return FlatpakSource.NONE;
}
if (int.TryParse(answer.Trim(), out var choice) && choice >= 1 && choice <= sources.Count)
return sources[choice - 1];
Console.WriteLine($" Please enter a number from 1 to {sources.Count}.");
}
}
private static int? AskForPullRequestNumber()
{
while (true)
{
Console.Write("- Number of the pull request: ");
var answer = Console.ReadLine();
if (answer is null)
{
Console.WriteLine();
Console.WriteLine("- Error: No answer arrived. Pass the number with --pr <number>.");
return null;
}
if (int.TryParse(answer.Trim().TrimStart('#'), out var number) && number > 0)
return number;
Console.WriteLine(" Please enter the number of a pull request, e.g., 1219.");
}
}
/// <summary>
/// Describes a pull request with its title and state, so that a mistyped number stands out before the build.
/// </summary>
/// <remarks>
/// The commit comes from git, which needs no token and knows no rate limit. The title is a courtesy on top: when
/// the GitHub API refuses to answer, e.g., after too many requests without a token, the build goes on without it.
/// </remarks>
private static async Task<string> DescribePullRequestAsync(int number)
{
var description = $"pull request #{number} of MindWorkAI/AI-Studio";
try
{
using var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.github.com/repos/MindWorkAI/AI-Studio/pulls/{number}");
request.Headers.UserAgent.ParseAdd("MindWork-AI-Studio-Build-Script");
request.Headers.Accept.ParseAdd("application/vnd.github+json");
using var response = await CLIENT.SendAsync(request);
if (!response.IsSuccessStatusCode)
return $"{description} (GitHub did not tell its title: {(int)response.StatusCode} {response.ReasonPhrase})";
await using var stream = await response.Content.ReadAsStreamAsync();
using var json = await JsonDocument.ParseAsync(stream);
var root = json.RootElement;
var title = root.GetProperty("title").GetString();
var state = root.GetProperty("merged").GetBoolean() ? "merged" : root.GetProperty("state").GetString() switch
{
"open" => "open",
_ => "closed without merging",
};
return $"{description}, \"{title}\" ({state})";
}
catch (Exception exception) when (exception is HttpRequestException or TaskCanceledException or JsonException or KeyNotFoundException or InvalidOperationException)
{
return $"{description} (GitHub did not tell its title: {exception.Message})";
}
}
/// <summary>
/// Reads which container image the CI of the Flatpak repository builds with.
/// </summary>
/// <remarks>
/// The image carries the GNOME runtime the manifest builds against. Reading it from the workflow keeps the local
/// build in step with the CI, e.g., when the Flatpak moves on to a newer GNOME runtime.
/// </remarks>
/// <param name="flatpakCommit">The commit of the Flatpak repository whose workflow counts.</param>
/// <returns>The image, or null when the workflow cannot be read or names more or less than one image.</returns>
private static async Task<string?> ReadCiImageAsync(string flatpakCommit)
{
var url = $"https://raw.githubusercontent.com/MindWorkAI/Flatpak/{flatpakCommit}/.github/workflows/flatpak.yml";
string workflow;
try
{
workflow = await CLIENT.GetStringAsync(url);
}
catch (Exception exception) when (exception is HttpRequestException or TaskCanceledException)
{
Console.WriteLine($"- Error: Could not read the CI workflow of the Flatpak repository from {url}: {exception.Message}");
return null;
}
var images = WorkflowImageRegex().Matches(workflow).Select(match => match.Groups[1].Value).Distinct().ToList();
if (images.Count is 1)
return images[0];
Console.WriteLine($"- Error: The CI workflow of the Flatpak repository names {images.Count} container images instead of one: {url}");
return null;
}
/// <summary>
/// Names the containers and volumes which earlier builds left behind, e.g., after the terminal was closed.
/// </summary>
/// <remarks>
/// They may also belong to a build which is still running in another terminal. Hence, the command only names
/// them and leaves the removal to the user.
/// </remarks>
private static async Task ReportLeftoversAsync(string workingDirectory)
{
var containers = await ReadNamesAsync(workingDirectory, ["ps", "--all", "--filter", $"label={DOCKER_LABEL}", "--format", "{{.Names}}"]);
var volumes = await ReadNamesAsync(workingDirectory, ["volume", "ls", "--filter", $"label={DOCKER_LABEL}", "--format", "{{.Name}}"]);
if (containers.Count is 0 && volumes.Count is 0)
return;
Console.WriteLine("- Note: Docker still holds containers or volumes of earlier builds. They may belong to a build which is still running, so the command leaves them alone. Once no other build runs, remove them with:");
foreach (var container in containers)
Console.WriteLine($" docker rm --force {container}");
foreach (var volume in volumes)
Console.WriteLine($" docker volume rm {volume}");
}
private static async Task<IReadOnlyList<string>> ReadNamesAsync(string workingDirectory, IReadOnlyList<string> arguments)
{
var names = await CommandRunner.ReadOutputAsync(workingDirectory, "docker", arguments);
return names.ExitCode is 0 ? names.Text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) : [];
}
/// <summary>
/// Reads the script which builds inside the container, with LF line endings.
/// </summary>
/// <remarks>
/// Git on Windows may check the script out with CR LF, which bash refuses.
/// </remarks>
private static async Task<byte[]> ReadContainerScriptAsync()
{
var path = Path.Join(Directory.GetCurrentDirectory(), CONTAINER_SCRIPT_DIRECTORY, CONTAINER_SCRIPT_NAME);
var script = await File.ReadAllTextAsync(path, Encoding.UTF8);
return Environment.UTF8_NO_BOM.GetBytes(script.ReplaceLineEndings("\n"));
}
/// <summary>
/// Writes the build script as a tar archive, which docker cp unpacks into the container.
/// </summary>
/// <remarks>
/// docker cp copies a single file only into a folder which already exists, so the archive brings its folder along.
/// </remarks>
private static async Task WriteScriptArchiveAsync(Stream stream, byte[] script)
{
await using var writer = new TarWriter(stream, TarEntryFormat.Pax, leaveOpen: true);
await writer.WriteEntryAsync(new PaxTarEntry(TarEntryType.Directory, $"{CONTAINER_INPUT_DIRECTORY}/") { Mode = EXECUTABLE_MODE });
using var data = new MemoryStream(script);
await writer.WriteEntryAsync(new PaxTarEntry(TarEntryType.RegularFile, $"{CONTAINER_INPUT_DIRECTORY}/{CONTAINER_SCRIPT_NAME}") { Mode = EXECUTABLE_MODE, DataStream = data });
}
/// <summary>
/// Writes the files of the local checkout as a tar archive, which docker cp unpacks into the container.
/// </summary>
/// <remarks>
/// The archive reads one file after the other straight into the stream, so even a large checkout never sits in
/// memory as a whole.
/// </remarks>
private static async Task WriteCheckoutArchiveAsync(Stream stream, string repositoryDirectory, IReadOnlyList<string> files)
{
var checkoutDirectory = $"{CONTAINER_INPUT_DIRECTORY}/{CONTAINER_CHECKOUT_DIRECTORY}";
await using var writer = new TarWriter(stream, TarEntryFormat.Pax, leaveOpen: true);
await writer.WriteEntryAsync(new PaxTarEntry(TarEntryType.Directory, $"{checkoutDirectory}/") { Mode = EXECUTABLE_MODE });
foreach (var file in files)
await writer.WriteEntryAsync(Path.Join(repositoryDirectory, file), $"{checkoutDirectory}/{file}");
}
/// <summary>
/// Reads the commit the local checkout stands on, which the summary names before the build.
/// </summary>
/// <returns>The hash of the commit, or null when the checkout has none.</returns>
private static async Task<string?> ReadLocalHeadAsync(string repositoryDirectory)
{
var head = await CommandRunner.ReadOutputAsync(repositoryDirectory, "git", ["rev-parse", "HEAD"]);
if (head.ExitCode is 0 && CommitHashRegex().IsMatch(head.Text.Trim()))
return head.Text.Trim();
Console.WriteLine($"- Error: The local checkout in '{repositoryDirectory}' has no commit to start from.");
return null;
}
/// <summary>
/// Lists the files of the local checkout which go into the Flatpak.
/// </summary>
/// <remarks>
/// These are the files git knows plus the new ones which no ignore rule covers, the same files a commit of
/// everything would hold. Build outputs such as bin, obj, or target stay behind, and so do deleted files.
/// </remarks>
/// <returns>The paths relative to the repository, with forward slashes, or null when git fails.</returns>
private static async Task<IReadOnlyList<string>?> ListLocalFilesAsync(string repositoryDirectory)
{
var listing = await CommandRunner.ReadOutputAsync(repositoryDirectory, "git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"]);
if (listing.ExitCode is not 0)
{
Console.WriteLine($"- Error: git could not list the files of the local checkout in '{repositoryDirectory}'.");
return null;
}
return listing.Text.Split('\0', StringSplitOptions.RemoveEmptyEntries).Distinct().Where(file => File.Exists(Path.Join(repositoryDirectory, file))).ToList();
}
/// <summary>
/// Describes the local checkout with its branch and the number of files which differ from its commit.
/// </summary>
/// <remarks>
/// git status refreshes the index by default, which is a change to the repository. Without optional locks, it
/// only reads.
/// </remarks>
private static async Task<string> DescribeLocalCheckoutAsync(string repositoryDirectory)
{
var branch = await CommandRunner.ReadOutputAsync(repositoryDirectory, "git", ["rev-parse", "--abbrev-ref", "HEAD"]);
var status = await CommandRunner.ReadOutputAsync(repositoryDirectory, "git", ["--no-optional-locks", "status", "--porcelain", "--untracked-files=all"]);
var changedFiles = status.Text.Split('\n', StringSplitOptions.RemoveEmptyEntries).Length;
var changes = changedFiles is 0 ? "without uncommitted changes" : $"with {changedFiles} changed or new files";
return $"the local checkout on {branch.Text.Trim()}, {changes}";
}
/// <summary>
/// Names the bundles in the output folder, with their sizes and SHA-256 hashes.
/// </summary>
/// <returns>True, when both bundles are there.</returns>
private static async Task<bool> ReportBundlesAsync(string outputDirectory, FlatpakArchitecture architecture)
{
Console.WriteLine("- The bundles:");
foreach (var bundleName in new[] { architecture.AppBundleName, architecture.PandocBundleName })
{
var path = Path.Join(outputDirectory, bundleName);
if (!File.Exists(path))
{
Console.WriteLine($"- Error: The container did not deliver '{bundleName}'.");
return false;
}
await using var bundle = File.OpenRead(path);
var hash = Convert.ToHexStringLower(await SHA256.HashDataAsync(bundle));
Console.WriteLine($" - {path}");
Console.WriteLine($" {bundle.Length / 1024 / 1024} MB, SHA-256 {hash}");
}
return true;
}
}
+13
View File
@@ -0,0 +1,13 @@
namespace Build.Commands;
/// <summary>
/// Which state of AI Studio goes into a Flatpak which the build command "flatpak" builds.
/// </summary>
public enum FlatpakSource
{
NONE,
MAIN,
PULL_REQUEST,
LOCAL,
}
@@ -0,0 +1,44 @@
namespace Build.Commands;
public static class FlatpakSourceExtensions
{
/// <param name="source">The state of AI Studio which goes into the Flatpak.</param>
extension(FlatpakSource source)
{
/// <summary>
/// The name of the source for the option --source.
/// </summary>
public string Name => source switch
{
FlatpakSource.MAIN => "main",
FlatpakSource.PULL_REQUEST => "pr",
FlatpakSource.LOCAL => "local",
_ => string.Empty,
};
/// <summary>
/// What the source builds, and what for.
/// </summary>
public string Description => source switch
{
FlatpakSource.MAIN => "main of MindWorkAI/AI-Studio, to simulate a pre-release",
FlatpakSource.PULL_REQUEST => "a pull request of MindWorkAI/AI-Studio, to test its changes early",
FlatpakSource.LOCAL => "this local checkout with its uncommitted changes, to test work before there is a pull request",
_ => string.Empty,
};
/// <summary>
/// All sources the command offers, in the order of its menu.
/// </summary>
public static IReadOnlyList<FlatpakSource> All => [FlatpakSource.MAIN, FlatpakSource.PULL_REQUEST, FlatpakSource.LOCAL];
/// <summary>
/// Finds the source for its name.
/// </summary>
/// <param name="name">The name of the source, as the option --source takes it.</param>
/// <returns>The source, or NONE for an unknown name.</returns>
public static FlatpakSource FromName(string name) => FlatpakSource.All.FirstOrDefault(candidate => string.Equals(candidate.Name, name.Trim(), StringComparison.OrdinalIgnoreCase));
}
}
+11 -9
View File
@@ -9,7 +9,7 @@ namespace Build.Commands;
public static class Pdfium
{
private const int MAX_DOWNLOAD_ATTEMPTS = 3;
private const int MAX_INSTALL_ATTEMPTS = 3;
private static readonly TimeSpan CONNECT_TIMEOUT = TimeSpan.FromSeconds(30);
private static readonly TimeSpan RESPONSE_TIMEOUT = TimeSpan.FromSeconds(60);
@@ -77,7 +77,7 @@ public static class Pdfium
return;
}
for (var attempt = 1; attempt <= MAX_DOWNLOAD_ATTEMPTS; attempt++)
for (var attempt = 1; attempt <= MAX_INSTALL_ATTEMPTS; attempt++)
{
try
{
@@ -88,7 +88,7 @@ public static class Pdfium
catch (Exception exception) when (IsTransientFailure(exception))
{
Console.Write($" failed: {DescribeFailure(exception)}");
if (attempt < MAX_DOWNLOAD_ATTEMPTS)
if (attempt < MAX_INSTALL_ATTEMPTS)
{
Console.Write($" Retrying in {RETRY_DELAY.TotalSeconds:0} seconds ...");
await Task.Delay(RETRY_DELAY);
@@ -97,7 +97,7 @@ public static class Pdfium
}
Console.WriteLine();
Console.WriteLine($"- Error: Could not download Pdfium {version} for {rid.UserFriendlyName} from {pdfiumUrl} in {MAX_DOWNLOAD_ATTEMPTS} attempts.");
Console.WriteLine($"- Error: Could not install Pdfium {version} for {rid.UserFriendlyName} from {pdfiumUrl} in {MAX_INSTALL_ATTEMPTS} attempts.");
if (File.Exists(pdfiumLibTargetPath))
Console.WriteLine(" To build with the library which is already present, use --offline.");
@@ -172,12 +172,14 @@ public static class Pdfium
//
// Deploy the library. The marker goes first, so that it never describes a library
// which was only half replaced:
// which was only half replaced. The directory of the marker does not exist before the
// first Rust build, which comes after this step on a fresh clone, and File.Delete
// throws when a directory is missing:
//
Console.Write(" deploying ...");
Directory.CreateDirectory(Path.GetDirectoryName(versionMarkerPath)!);
File.Delete(versionMarkerPath);
File.Move(pdfiumLibTmpTargetPath, pdfiumLibTargetPath, true);
Directory.CreateDirectory(Path.GetDirectoryName(versionMarkerPath)!);
await File.WriteAllTextAsync(versionMarkerPath, versionMarker, Environment.UTF8_NO_BOM);
}
catch (OperationCanceledException) when (attemptTimeout.IsCancellationRequested)
@@ -199,14 +201,14 @@ public static class Pdfium
}
/// <summary>
/// Whether another attempt may succeed where a download attempt failed with the given exception.
/// Whether another attempt may succeed where an attempt to install the library failed with the given exception.
/// </summary>
/// <param name="exception">The exception the attempt failed with.</param>
/// <returns>True, when the download is worth another attempt.</returns>
/// <returns>True, when the installation is worth another attempt.</returns>
private static bool IsTransientFailure(Exception exception) => exception is HttpRequestException or OperationCanceledException or TimeoutException or IOException or InvalidDataException;
/// <summary>
/// Describes why a download attempt failed, in one line.
/// Describes why an attempt to install the library failed, in one line.
/// </summary>
/// <remarks>
/// The innermost exception names the actual cause, such as the socket error behind an HttpRequestException
+2 -2
View File
@@ -55,11 +55,11 @@ public sealed class VerifyCommand
// Tauri's build script insists that everything the configuration lists is already
// there and refuses to run otherwise, so nothing Rust compiles until a build has
// produced those files once. Failing here would be a trap rather than a gate: the way
// to produce them is `dotnet run build`, and that command runs this gate first -- a
// to produce them is `dotnet run -- build`, and that command runs this gate first -- a
// fresh clone would never get past it.
//
Console.WriteLine("- Skipping the Rust tests and Clippy: the .NET sidecar or the downloaded libraries are missing, and Tauri's build script needs both before anything Rust compiles.");
Console.WriteLine(" Run 'dotnet run build --skip-verify' once. From then on, this part of the gate runs with the rest.");
Console.WriteLine(" Run 'dotnet run -- build --skip-verify' once. From then on, this part of the gate runs with the rest.");
}
results.Add(("Model sources", new VerifyModelsCommand().VerifyModels()));
+256
View File
@@ -0,0 +1,256 @@
#!/usr/bin/env bash
#
# Builds the Flatpak of AI Studio and its Pandoc plugin. The build command "flatpak" of app/Build, see
# Commands/FlatpakCommand.cs, runs this script inside the CI image of the Flatpak repository and copies the
# bundles out of the output folder afterward.
#
# The sync below simulates the job "sync_flatpak_repo" of .github/workflows/build-and-release.yml, which
# prepares the Flatpak repository for a release. Whoever changes one of them changes the other one as well.
# On purpose, the script differs from the job in three points:
#
# - It removes the tag of AI Studio. flatpak-builder checks a tag against the commit, and the commit of a
# test build has none.
# - It skips update-metainfo.py --check. The metainfo gets the entry of a release from the release command
# only, so a test build lacks it.
# - It sets the URL of AI Studio as well. For the source "local", it points to a repository inside the
# container, which holds the copied files of the local checkout in a single commit.
#
set -euo pipefail
: "${ARCH:?}" "${SOURCE:?}" "${FLATPAK_URL:?}" "${FLATPAK_COMMIT:?}"
: "${APP_BUNDLE:?}" "${PANDOC_BUNDLE:?}" "${BUILD_DIRECTORY:?}" "${OUT_DIRECTORY:?}"
if [ "$SOURCE" = "local" ]; then
: "${LOCAL_CHECKOUT:?}"
else
: "${AI_STUDIO_URL:?}" "${AI_STUDIO_COMMIT:?}"
fi
# The same version of yq as the pipeline uses, see FLATPAK_YQ_VERSION and FLATPAK_YQ_SHA256 there:
YQ_VERSION="4.44.6"
YQ_SHA256_X86_64="0c2b24e645b57d8e7c0566d18643a6d4f5580feeea3878127354a46f2a1e4598"
YQ_SHA256_AARCH64="9477ac3cc447b6c083986129e35af8122eb2b938fe55c9c3e40436fb966e5813"
FLATHUB_REPO_URL="https://flathub.org/repo/flathub.flatpakrepo"
APP_MANIFEST="org.mindworkai.AIStudio.yml"
PANDOC_MANIFEST="plugins/pandoc/org.mindworkai.AIStudio.plugin.pandoc.yml"
stage() {
printf '\n===== %s: %s =====\n' "$(date -u '+%H:%M:%S')" "$*"
}
fail() {
echo >&2 "error: $*"
exit 1
}
# Fetches a single commit of a repository into a new folder, without its history.
fetch_commit() {
local url="$1" commit="$2" directory="$3"
shift 3
git init --quiet "$directory"
git -C "$directory" remote add origin "$url"
git -C "$directory" fetch --quiet --depth 1 "$@" origin "$commit"
}
# Installs the given refs from Flathub, unless they are installed already. The image brings some runtimes
# in a lower layer of its file system, where updating them fails with "Invalid cross-device link". Hence,
# the script never updates them, and flatpak-builder runs without --install-deps-from.
install_missing() {
local missing=()
local ref
for ref in "$@"; do
if flatpak info --system "$ref" > /dev/null 2>&1; then
echo "Already installed: $ref"
else
missing+=("$ref")
fi
done
if [ "${#missing[@]}" -gt 0 ]; then
flatpak install --system --noninteractive -y flathub "${missing[@]}"
fi
}
# Prints the branch of an SDK extension: the version of the extension point which the SDK declares, e.g.,
# 26.08 for org.freedesktop.Sdk.Extension.dotnet10 in org.gnome.Sdk//51.
extension_branch() {
local sdk_ref="$1" extension="$2"
flatpak info --system --show-metadata "$sdk_ref" | awk -v section="[Extension ${extension%.*}]" '
$0 == section { inside = 1; next }
/^\[/ { inside = 0 }
inside && $1 == "version" { sub(/^[^=]*=[[:space:]]*/, ""); print; exit }
'
}
stage "Checking the container"
test "$(uname -m)" = "$ARCH" || fail "the container runs on $(uname -m) instead of $ARCH"
for tool in curl flatpak flatpak-builder git jq python3 sha256sum uv; do
hash "$tool" 2> /dev/null || fail "the image lacks $tool"
done
echo "Building the source '$SOURCE' for $ARCH"
stage "Preparing yq ${YQ_VERSION}"
case "$ARCH" in
aarch64)
yq_asset="yq_linux_arm64"
yq_sha256="$YQ_SHA256_AARCH64"
;;
x86_64)
yq_asset="yq_linux_amd64"
yq_sha256="$YQ_SHA256_X86_64"
;;
*)
fail "there is no Flatpak for $ARCH"
;;
esac
mkdir -p "$BUILD_DIRECTORY/tools" "$OUT_DIRECTORY"
curl -fsSL -o "$BUILD_DIRECTORY/tools/yq" "https://github.com/mikefarah/yq/releases/download/v${YQ_VERSION}/${yq_asset}"
echo "${yq_sha256} $BUILD_DIRECTORY/tools/yq" | sha256sum --check --strict
chmod 755 "$BUILD_DIRECTORY/tools/yq"
export PATH="$BUILD_DIRECTORY/tools:$PATH"
if [ "$SOURCE" = "local" ]; then
stage "Committing the local checkout in a repository of its own"
# The files arrive with the owner of the checkout, and git refuses to work in a repository of another user:
chown -R root:root "$LOCAL_CHECKOUT"
git init --quiet "$LOCAL_CHECKOUT"
# A checkout on Windows may hold CR LF line endings, which a commit there would turn into LF. The fetches by
# commit, from update-dependencies and flatpak-builder alike, need the two uploadpack settings:
git -C "$LOCAL_CHECKOUT" config core.autocrlf input
git -C "$LOCAL_CHECKOUT" config core.safecrlf false
git -C "$LOCAL_CHECKOUT" config uploadpack.allowAnySHA1InWant true
git -C "$LOCAL_CHECKOUT" config uploadpack.allowFilter true
git -C "$LOCAL_CHECKOUT" add --all
git -C "$LOCAL_CHECKOUT" -c user.name="AI Studio build" -c user.email="build@localhost" commit --quiet --no-verify -m "Local checkout"
AI_STUDIO_URL="file://$LOCAL_CHECKOUT"
AI_STUDIO_COMMIT=$(git -C "$LOCAL_CHECKOUT" rev-parse HEAD)
echo "Committed $(git -C "$LOCAL_CHECKOUT" ls-files | wc -l) files as ${AI_STUDIO_COMMIT}"
fi
stage "Fetching the Flatpak repository at ${FLATPAK_COMMIT}"
fetch_commit "$FLATPAK_URL" "$FLATPAK_COMMIT" "$BUILD_DIRECTORY/flatpak"
cd "$BUILD_DIRECTORY/flatpak"
git checkout --quiet FETCH_HEAD
stage "Installing the runtimes and SDKs"
runtime_version=$(yq -r '."runtime-version"' "$APP_MANIFEST")
sdk_ref="$(yq -r '.sdk' "$APP_MANIFEST")//${runtime_version}"
install_missing "$(yq -r '.runtime' "$APP_MANIFEST")//${runtime_version}" "$sdk_ref"
refs=()
while IFS= read -r extension; do
branch=$(extension_branch "$sdk_ref" "$extension")
[ -n "$branch" ] || fail "$sdk_ref declares no extension point for $extension"
refs+=("${extension}//${branch}")
done < <(yq -r '."sdk-extensions"[]' "$APP_MANIFEST")
# update-dependencies restores the .NET projects inside the Freedesktop SDK and its .NET extension, in the
# versions it passes to flatpak-dotnet-generator.py:
generator_call=$(grep -E 'flatpak-dotnet-generator\.py' update-dependencies)
freedesktop_version=$(grep -oE -e '-f [0-9]+\.[0-9]+' <<< "$generator_call" | cut -d' ' -f2)
dotnet_major=$(grep -oE -e '-d [0-9]+' <<< "$generator_call" | cut -d' ' -f2)
[ -n "$freedesktop_version" ] && [ -n "$dotnet_major" ] || fail "update-dependencies calls flatpak-dotnet-generator.py without -f and -d"
refs+=("org.freedesktop.Sdk//${freedesktop_version}" "org.freedesktop.Sdk.Extension.dotnet${dotnet_major}//${freedesktop_version}")
pandoc_sdk=$(yq -r '.sdk' "$PANDOC_MANIFEST")
[[ "$pandoc_sdk" == *//* ]] || fail "the Pandoc plugin names its SDK without a branch: $pandoc_sdk"
refs+=("$pandoc_sdk")
install_missing "${refs[@]}"
stage "Reading metadata.txt of AI Studio ${AI_STUDIO_COMMIT}"
fetch_commit "$AI_STUDIO_URL" "$AI_STUDIO_COMMIT" "$BUILD_DIRECTORY/ai-studio-metadata" --filter=blob:none
metadata=$(git -C "$BUILD_DIRECTORY/ai-studio-metadata" show FETCH_HEAD:metadata.txt | tr -d '\r')
app_version=$(sed -n '1p' <<< "$metadata")
pdfium_full_version=$(sed -n '10p' <<< "$metadata")
pdfium_chromium_revision=$(cut -d'.' -f3 <<< "$pdfium_full_version")
[[ "$pdfium_chromium_revision" =~ ^[0-9]+$ ]] || fail "line 10 of metadata.txt names no PDFium version: $pdfium_full_version"
echo "AI Studio ${app_version} with PDFium ${pdfium_full_version}"
stage "Syncing the Flatpak repository like the release pipeline"
pdfium_base_url="https://github.com/bblanchon/pdfium-binaries/releases/download/chromium%2F${pdfium_chromium_revision}"
export AI_STUDIO_URL AI_STUDIO_COMMIT
export PDFIUM_X64_URL="${pdfium_base_url}/pdfium-linux-x64.tgz"
export PDFIUM_ARM64_URL="${pdfium_base_url}/pdfium-linux-arm64.tgz"
curl -fsSL -o "$BUILD_DIRECTORY/pdfium-linux-x64.tgz" "$PDFIUM_X64_URL"
curl -fsSL -o "$BUILD_DIRECTORY/pdfium-linux-arm64.tgz" "$PDFIUM_ARM64_URL"
export PDFIUM_X64_SHA256
export PDFIUM_ARM64_SHA256
PDFIUM_X64_SHA256=$(sha256sum "$BUILD_DIRECTORY/pdfium-linux-x64.tgz" | awk '{print $1}')
PDFIUM_ARM64_SHA256=$(sha256sum "$BUILD_DIRECTORY/pdfium-linux-arm64.tgz" | awk '{print $1}')
yq -i '
(.modules[] | select(.name == "mind-work-ai-studio").sources[0].url) = strenv(AI_STUDIO_URL) |
(.modules[] | select(.name == "mind-work-ai-studio").sources[0].commit) = strenv(AI_STUDIO_COMMIT) |
del(.modules[] | select(.name == "mind-work-ai-studio").sources[0].tag) |
(.modules[] | select(.name == "mind-work-ai-studio").sources[] | select(.type == "archive" and .only-arches[0] == "x86_64").url) = strenv(PDFIUM_X64_URL) |
(.modules[] | select(.name == "mind-work-ai-studio").sources[] | select(.type == "archive" and .only-arches[0] == "x86_64").sha256) = strenv(PDFIUM_X64_SHA256) |
(.modules[] | select(.name == "mind-work-ai-studio").sources[] | select(.type == "archive" and .only-arches[0] == "aarch64").url) = strenv(PDFIUM_ARM64_URL) |
(.modules[] | select(.name == "mind-work-ai-studio").sources[] | select(.type == "archive" and .only-arches[0] == "aarch64").sha256) = strenv(PDFIUM_ARM64_SHA256)
' "$APP_MANIFEST"
./update-dependencies
test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[0].url' "$APP_MANIFEST")" = "$AI_STUDIO_URL"
test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[0].commit' "$APP_MANIFEST")" = "$AI_STUDIO_COMMIT"
test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[0].tag' "$APP_MANIFEST")" = "null"
test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[] | select(.type == "archive" and .only-arches[0] == "x86_64").url' "$APP_MANIFEST")" = "$PDFIUM_X64_URL"
test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[] | select(.type == "archive" and .only-arches[0] == "x86_64").sha256' "$APP_MANIFEST")" = "$PDFIUM_X64_SHA256"
test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[] | select(.type == "archive" and .only-arches[0] == "aarch64").url' "$APP_MANIFEST")" = "$PDFIUM_ARM64_URL"
test "$(yq -r '(.modules[] | select(.name == "mind-work-ai-studio")).sources[] | select(.type == "archive" and .only-arches[0] == "aarch64").sha256' "$APP_MANIFEST")" = "$PDFIUM_ARM64_SHA256"
for generated_source in cargo-sources.json dotnet-sources.json tauri-cli-sources.json; do
test -s "$generated_source"
jq -e 'type == "array" and length > 0' "$generated_source" > /dev/null
done
git diff --check
git diff --stat
stage "Building the Flatpak of AI Studio"
app_id=$(yq -r '.id' "$APP_MANIFEST")
flatpak-builder \
--arch="$ARCH" \
--repo="$BUILD_DIRECTORY/repo" \
--state-dir="$BUILD_DIRECTORY/state" \
--disable-rofiles-fuse \
--force-clean \
--default-branch=stable \
"$BUILD_DIRECTORY/build-app" \
"$APP_MANIFEST"
flatpak build-bundle \
--arch="$ARCH" \
--runtime-repo="$FLATHUB_REPO_URL" \
"$BUILD_DIRECTORY/repo" \
"$OUT_DIRECTORY/$APP_BUNDLE" \
"$app_id" \
stable
stage "Building the Pandoc plugin"
# Like the CI, the plugin builds against the app it extends, so the bundle of the app gets installed first:
flatpak install --system --noninteractive -y --bundle "$OUT_DIRECTORY/$APP_BUNDLE"
flatpak-builder \
--arch="$ARCH" \
--repo="$BUILD_DIRECTORY/repo" \
--state-dir="$BUILD_DIRECTORY/state" \
--disable-rofiles-fuse \
--force-clean \
"$BUILD_DIRECTORY/build-pandoc" \
"$PANDOC_MANIFEST"
flatpak build-bundle \
--arch="$ARCH" \
--runtime \
"$BUILD_DIRECTORY/repo" \
"$OUT_DIRECTORY/$PANDOC_BUNDLE" \
"$(yq -r '.id' "$PANDOC_MANIFEST")" \
"$(yq -r '.branch' "$PANDOC_MANIFEST")"
stage "Done"
ls -l "$OUT_DIRECTORY"
+10 -4
View File
@@ -8,7 +8,7 @@ using Build.Tools;
// a root with the same name as one of its commands. Hence, the root is a command of its own, which
// brings only the help option of a RootCommand along:
//
var rootCommand = new Command("build-script", "Build, check, and release MindWork AI Studio. Run the commands from app/Build with 'dotnet run <command>'.")
var rootCommand = new Command("build-script", "Build, check, and release MindWork AI Studio. Run the commands from app/Build with 'dotnet run -- <command>'.")
{
new HelpOption(),
CheckRidsCommand.CreateCommand(),
@@ -23,17 +23,23 @@ var rootCommand = new Command("build-script", "Build, check, and release MindWor
CollectI18NKeysCommand.CreateCommand(),
AssistantPluginHashCommand.CreateCommand(),
VerifyModelsCommand.CreateCommand(),
VerifyCommand.CreateCommand()
VerifyCommand.CreateCommand(),
FlatpakCommand.CreateCommand()
};
//
// A command which fails deep inside, e.g., the build within a release, ends the whole script through
// a CommandExitedException, once it has said why. System.CommandLine would print that exception with
// its stack trace, so we handle the exceptions ourselves and print only those nobody expected:
// its stack trace, so we handle the exceptions ourselves and print only those nobody expected.
//
// System.CommandLine would also answer Ctrl+C by cancelling a token and ending the script two seconds
// later, whether the command has finished or not. No command reads that token, and the command flatpak
// needs longer to remove its container and volume. Without the timeout, Ctrl+C ends a command at once,
// unless the command handles Ctrl+C itself, as flatpak does:
//
try
{
return await rootCommand.Parse(args).InvokeAsync(new InvocationConfiguration { EnableDefaultExceptionHandler = false });
return await rootCommand.Parse(args).InvokeAsync(new InvocationConfiguration { EnableDefaultExceptionHandler = false, ProcessTerminationTimeout = null });
}
catch (CommandExitedException exception)
{
+12
View File
@@ -0,0 +1,12 @@
namespace Build.Tools;
/// <summary>
/// What an external tool wrote to its standard output, and how it ended.
/// </summary>
/// <remarks>
/// The standard error of the tool went straight to the terminal. A tool which fails says why it failed there, so
/// whoever reads the terminal learns the reason from the tool itself.
/// </remarks>
/// <param name="Text">Everything the tool wrote to its standard output.</param>
/// <param name="ExitCode">The exit code of the tool, where anything but zero is a failure.</param>
public readonly record struct CapturedOutput(string Text, int ExitCode);
+111 -5
View File
@@ -44,9 +44,55 @@ public static class CommandRunner
{
using var process = Process.Start(startInfo);
if (process is null)
return ReportNotStarted(fileName);
await process.WaitForExitAsync();
return process.ExitCode;
}
catch (Win32Exception exception)
{
return ReportCouldNotStart(fileName, exception);
}
}
/// <summary>
/// Runs a tool with a list of arguments and waits for it.
/// </summary>
/// <remarks>
/// Each argument reaches the tool unchanged, also when it contains spaces or quotes, because the system quotes
/// it as the platform needs it. Paths which a user chose, such as an output folder, therefore need no quoting.
/// </remarks>
/// <param name="workingDirectory">Where the tool should run.</param>
/// <param name="fileName">The tool, as it is called on the PATH.</param>
/// <param name="arguments">What to pass it, one argument per entry.</param>
/// <param name="writeInput">Writes the standard input of the tool, or null when the tool reads none. The input ends once the callback returns.</param>
/// <returns>The exit code of the tool, or COULD_NOT_START when it never ran.</returns>
public static async Task<int> RunAsync(string workingDirectory, string fileName, IReadOnlyList<string> arguments, Func<Stream, Task>? writeInput = null)
{
Console.WriteLine($"- Running '{fileName} {DescribeArguments(arguments)}' in '{workingDirectory}' ...");
var startInfo = CreateStartInfo(workingDirectory, fileName, arguments);
startInfo.RedirectStandardInput = writeInput is not null;
try
{
using var process = Process.Start(startInfo);
if (process is null)
return ReportNotStarted(fileName);
if (writeInput is not null)
{
Console.WriteLine($"- Error: '{fileName}' did not start, and the system did not say why.");
return COULD_NOT_START;
try
{
await using var input = process.StandardInput.BaseStream;
await writeInput(input);
}
catch (IOException)
{
//
// The tool closed its input early, which it does when it fails. Its exit code
// and what it wrote to the terminal tell more than the broken pipe could:
//
}
}
await process.WaitForExitAsync();
@@ -54,9 +100,69 @@ public static class CommandRunner
}
catch (Win32Exception exception)
{
Console.WriteLine($"- Error: '{fileName}' could not be started: {exception.Message}");
Console.WriteLine($" Is '{fileName}' installed and on the PATH?");
return COULD_NOT_START;
return ReportCouldNotStart(fileName, exception);
}
}
/// <summary>
/// Runs a tool with a list of arguments and collects what it writes to its standard output.
/// </summary>
/// <remarks>
/// Its standard error still goes to the terminal, so a failing tool explains itself there. The standard output
/// stays clean for reading answers such as a commit hash, which a warning on the same stream would spoil.
/// </remarks>
/// <param name="workingDirectory">Where the tool should run.</param>
/// <param name="fileName">The tool, as it is called on the PATH.</param>
/// <param name="arguments">What to pass it, one argument per entry.</param>
/// <returns>The standard output and the exit code of the tool; the exit code is COULD_NOT_START when it never ran.</returns>
public static async Task<CapturedOutput> ReadOutputAsync(string workingDirectory, string fileName, IReadOnlyList<string> arguments)
{
var startInfo = CreateStartInfo(workingDirectory, fileName, arguments);
startInfo.RedirectStandardOutput = true;
try
{
using var process = Process.Start(startInfo);
if (process is null)
return new(string.Empty, ReportNotStarted(fileName));
var text = await process.StandardOutput.ReadToEndAsync();
await process.WaitForExitAsync();
return new(text, process.ExitCode);
}
catch (Win32Exception exception)
{
return new(string.Empty, ReportCouldNotStart(fileName, exception));
}
}
private static ProcessStartInfo CreateStartInfo(string workingDirectory, string fileName, IReadOnlyList<string> arguments)
{
var startInfo = new ProcessStartInfo
{
FileName = fileName,
WorkingDirectory = workingDirectory,
UseShellExecute = false,
};
foreach (var argument in arguments)
startInfo.ArgumentList.Add(argument);
return startInfo;
}
private static string DescribeArguments(IReadOnlyList<string> arguments) => string.Join(' ', arguments.Select(argument => argument.Contains(' ') ? $"\"{argument}\"" : argument));
private static int ReportNotStarted(string fileName)
{
Console.WriteLine($"- Error: '{fileName}' did not start, and the system did not say why.");
return COULD_NOT_START;
}
private static int ReportCouldNotStart(string fileName, Win32Exception exception)
{
Console.WriteLine($"- Error: '{fileName}' could not be started: {exception.Message}");
Console.WriteLine($" Is '{fileName}' installed and on the PATH?");
return COULD_NOT_START;
}
}
+2
View File
@@ -13,6 +13,7 @@
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=IERI/@EntryIndexedValue">IERI</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=IMIME/@EntryIndexedValue">IMIME</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=IONOS/@EntryIndexedValue">IONOS</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=LF/@EntryIndexedValue">LF</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=LLM/@EntryIndexedValue">LLM</s:String>
<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>
@@ -21,6 +22,7 @@
<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/=SWOT/@EntryIndexedValue">SWOT</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=TA/@EntryIndexedValue">TA</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=TB/@EntryIndexedValue">TB</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=UI/@EntryIndexedValue">UI</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=URL/@EntryIndexedValue">URL</s:String>
@@ -0,0 +1,88 @@
# AGENTS.md
These instructions cover the AI operations in `app/MindWork AI Studio/AIOperations/`. They add to the
`AGENTS.md` in the repository root, which applies here as well.
## What an AI operation is
An AI operation is a task which AI Studio hands to a model on its own: one request in, one result out, without
a loop. The text content cleaner, the data source selection and the retrieval context validation of the
classic RAG process, and the security audit of plugins are AI operations. A conversation with the user, a loop
of tool calls, or an agent which plans its own steps is not one.
The common types live in this folder; each operation lives in a folder of its own, `AIOperations/<Name>/`,
with `<Name>Operation`, `<Name>Request`, and its result types.
**Never name a folder after a type of the app.** Its namespace `AIStudio.AIOperations.<Name>` would hide that
type wherever the namespace is in reach (CS0118). The component `DataSourceSelection` exists, so the
operation which selects data sources lives in `DataSourceChoice/`.
## The parts
- **`IAIOperation<TRequest, TResult>`** - `Id` for the log, `Component` for the User-Agent and
`ChatThread.RuntimeComponent`, `GetRequiredConfidence(request)`, and `RunAsync(request, context, token)`.
The required confidence comes from the content of the request alone, e.g., its data sources or the
confidence a chat requires; the minimum of the operation is a setting and not part of it.
- **`AIOperationBase<TRequest, TResult>`** - `AskAsync` sends one request with a chat thread of its own to the
provider of the context and waits for the whole answer. Right before, it checks the provider once more
against a prohibition, the global minimum, and the confidence the request requires, but not against the
minimum of the operation, because a caller may exempt a fallback from it.
- **`AIOperationContext`** - what a call runs with apart from its request, the provider above all.
- **`GetProviderSettings(SettingsManager)`** - every operation declares this public static method, which
reads its preferred provider and its minimum confidence fresh on every call. It is static, so that a service
learns which provider would run without an instance. `AIOperationsAreStatelessTests` checks that it exists.
## Thread safety
Every operation is registered as a singleton in `Program.cs` and serves several callers at once, e.g., two
chats with RAG. It therefore keeps nothing of a call: no writable field or property, only the services of
its primary constructor, which are singletons as well. Everything a call needs lives in local variables or
travels with the request and the context. A limit per call, such as the parallel validations of retrieval
contexts, is a local `SemaphoreSlim`. `AIOperationsAreStatelessTests` checks both the state and the
registration.
## Choosing the provider
The caller chooses the provider of a call and passes it in the `AIOperationContext`; an operation never
chooses one itself.
- **`AIOperationProviderChoice.Choose`** decides, a pure function on the facts about each candidate
(`AIOperationProviderCandidate`) and the confidence levels to reach (`AIOperationProviderRules`). The
preferred provider of the operation wins when it passes every rule; otherwise the first fallback in the
order of the caller which passes. A prohibition, the global minimum, the confidence the request requires,
and the check of the caller apply to every candidate; the minimum of the operation applies to the fallbacks
only when the caller says so.
- **`AIOperationProviderIssue`** - why a candidate failed, in the order of the checks. The choice reports the
issue of the preferred provider and, when nothing was chosen, of the first named fallback. Explain a choice
to the user from these issues; never guess the reason afterward.
- **`AIOperationProviderResolver`** gathers the facts from the settings. Call `Resolve` right before running
an operation, which logs the choice, and `Preview` for a check in advance or a hint in the UI.
- **`AIOperationProviderOptions`** - what the caller adds: the fallbacks in order, whether the minimum of the
operation applies to them, and a check of its own, e.g., whether a provider may see the data sources. The
app-wide default is `SettingsManager.AppDefaultProviderId`.
Build the options of a caller in one place, so that a check in advance counts the providers which run:
`ClassicRagProviderOptions` serves the classic RAG process and `DataSourceService`,
`AssistantPluginAuditService.GetProviderOptions` the audit, and `ReadWebContent.GetCleanerProviderOptions` the
text content cleaner.
## Settings
Each operation has a preferred provider and a minimum confidence in its settings data class, managed through
`ManagedConfiguration` and documented in `Plugins/configuration/plugin.lua`. With a switch such as
`PreselectAgentOptions`, both apply only while it is on, like the settings of the assistants. Add the minimum
to `ComponentsExtensions.MinimumConfidence` as well, so that the provider selections of the settings filter by
it.
## Answers with JSON
Find the JSON in an answer with `ModelAnswerJson` and read it with `AIOperationsJson.OPTIONS`. A new JSON type
goes into `AIOperationsJsonContext` and into `JsonTestRoots.ModelAnswers` in `app/Tests/Serialization/`. Give
a result an explicit way to say that the model gave no usable answer, such as `IsAnswered`, instead of a value
which stands for it.
## Tests
The tests live in `app/Tests/AIOperations/`: the choice as a table (`AIOperationProviderChoiceTests`), the
resolver on real settings (`AIOperationProviderResolverTests`), the statelessness of all operations, and per
operation the options its callers pass (`<Name>ProviderTests`).
@@ -0,0 +1,128 @@
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Settings;
namespace AIStudio.AIOperations;
/// <summary>
/// The base of the AI operations, with what each of them needs to ask a model.
/// </summary>
/// <remarks>
/// It keeps nothing of a call: every request gets a chat thread of its own, and the provider comes with the
/// context. Derived operations keep it that way, see IAIOperation; AIOperationsAreStatelessTests checks it.
/// </remarks>
/// <typeparam name="TRequest">What the operation works on.</typeparam>
/// <typeparam name="TResult">What the operation returns.</typeparam>
public abstract class AIOperationBase<TRequest, TResult>(ILogger logger, SettingsManager settingsManager) : IAIOperation<TRequest, TResult>
{
protected ILogger Logger { get; } = logger;
protected SettingsManager SettingsManager { get; } = settingsManager;
#region Implementation of IAIOperation
/// <inheritdoc />
public abstract string Id { get; }
/// <inheritdoc />
public abstract Tools.Components Component { get; }
/// <inheritdoc />
public abstract ConfidenceLevel GetRequiredConfidence(TRequest request);
/// <inheritdoc />
public abstract Task<TResult> RunAsync(TRequest request, AIOperationContext context, CancellationToken token = default);
#endregion
/// <summary>
/// Sends one request to the provider of the context and waits for the whole answer.
/// </summary>
/// <remarks>
/// The provider is checked once more right before: the organization must not have prohibited it, and it
/// has to reach the global minimum and the confidence the content of the request requires. The minimum
/// of the operation itself is not checked here, because a caller may exempt a fallback from it.
/// </remarks>
/// <param name="request">The request, for the confidence its content requires.</param>
/// <param name="context">What the call runs with, the provider above all.</param>
/// <param name="systemPrompt">The system prompt.</param>
/// <param name="userPrompt">The user prompt.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The text of the answer, or null when the provider must not see the request or did not answer.</returns>
protected async Task<string?> AskAsync(TRequest request, AIOperationContext context, string systemPrompt, string userPrompt, CancellationToken token)
{
var provider = context.Provider;
if (!this.MayAsk(provider, request))
return null;
var thread = new ChatThread
{
WorkspaceId = Guid.Empty,
ChatId = Guid.NewGuid(),
Name = string.Empty,
SystemPrompt = systemPrompt,
Blocks = [],
RuntimeComponent = this.Component,
};
var time = DateTimeOffset.Now;
var prompt = new ContentText
{
Text = userPrompt,
};
thread.Blocks.Add(new ContentBlock
{
Time = time,
ContentType = ContentType.TEXT,
Role = ChatRole.USER,
Content = prompt,
});
var answer = new ContentText
{
// We have to wait for the remote for the content stream:
InitialRemoteWait = true,
};
thread.Blocks.Add(new ContentBlock
{
Time = time,
ContentType = ContentType.TEXT,
Role = ChatRole.AI,
Content = answer,
});
// Awaiting this line waits for the entire content to be streamed:
await answer.CreateFromProviderAsync(provider.CreateProvider(), provider.Model, prompt, thread, token);
if (string.IsNullOrWhiteSpace(answer.Text))
{
this.Logger.LogWarning($"The AI operation '{this.Id}' got no answer from the provider '{provider.InstanceName}'.");
return null;
}
return answer.Text;
}
private bool MayAsk(Settings.Provider provider, TRequest request)
{
if (provider == Settings.Provider.NONE || provider.UsedLLMProvider is LLMProviders.NONE)
{
this.Logger.LogWarning($"The AI operation '{this.Id}' has no provider.");
return false;
}
var minimumLevel = this.SettingsManager.GlobalMinimumConfidenceLevel;
var requiredLevel = this.GetRequiredConfidence(request);
if (requiredLevel > minimumLevel)
minimumLevel = requiredLevel;
if (!this.SettingsManager.IsProviderUsable(provider.UsedLLMProvider, minimumLevel))
{
this.Logger.LogWarning($"The AI operation '{this.Id}' must not use the provider '{provider.InstanceName}': the organization prohibited it, or its confidence is below '{minimumLevel.Name}'.");
return false;
}
return true;
}
}
@@ -0,0 +1,7 @@
namespace AIStudio.AIOperations;
/// <summary>
/// What a call of an AI operation runs with, apart from its request.
/// </summary>
/// <param name="Provider">The provider which the caller chose for this call, usually through AIOperationProviderResolver.</param>
public sealed record AIOperationContext(Settings.Provider Provider);
@@ -0,0 +1,29 @@
using AIStudio.Provider;
namespace AIStudio.AIOperations;
/// <summary>
/// What is known about one provider which an AI operation might use.
/// </summary>
/// <remarks>
/// AIOperationProviderResolver gathers these facts from the settings, and AIOperationProviderChoice decides
/// on them alone. That keeps the decision apart from the settings and easy to test.
/// </remarks>
/// <param name="Provider">The configured provider; Provider.NONE when nobody named one or when it is missing.</param>
/// <param name="IsNamed">Whether somebody named a provider here at all.</param>
/// <param name="Exists">Whether the named provider is configured.</param>
/// <param name="IsProhibited">Whether the organization prohibited the provider.</param>
/// <param name="Confidence">The confidence level of the provider.</param>
/// <param name="CallerIssue">What the check of the caller found; NONE when the provider passed it or when there is no such check.</param>
public sealed record AIOperationProviderCandidate(Settings.Provider Provider, bool IsNamed, bool Exists, bool IsProhibited, ConfidenceLevel Confidence, AIOperationProviderIssue CallerIssue)
{
/// <summary>
/// A candidate which nobody named.
/// </summary>
public static readonly AIOperationProviderCandidate NOT_NAMED = new(Settings.Provider.NONE, false, false, false, ConfidenceLevel.NONE, AIOperationProviderIssue.NONE);
/// <summary>
/// A candidate whose provider is no longer configured.
/// </summary>
public static readonly AIOperationProviderCandidate MISSING = new(Settings.Provider.NONE, true, false, false, ConfidenceLevel.NONE, AIOperationProviderIssue.NONE);
}
@@ -0,0 +1,90 @@
namespace AIStudio.AIOperations;
/// <summary>
/// The provider chosen for an AI operation, together with the reasons why others were not chosen.
/// </summary>
/// <remarks>
/// The reasons let a caller explain the choice instead of guessing it, e.g., why the model of the
/// assistant cleaned a web page although the user picked another one for that.
/// </remarks>
/// <param name="Provider">The chosen provider; Provider.NONE when no candidate passed.</param>
/// <param name="PreferredIssue">Why the preferred provider of the operation was not chosen: NONE when it was, NOT_SET when there is none.</param>
/// <param name="FallbackIssue">Only when no provider was chosen: why the first named fallback failed, NOT_SET when the caller named none. NONE otherwise.</param>
public sealed record AIOperationProviderChoice(Settings.Provider Provider, AIOperationProviderIssue PreferredIssue, AIOperationProviderIssue FallbackIssue)
{
/// <summary>
/// Whether a provider was chosen.
/// </summary>
public bool HasProvider => this.Provider != Settings.Provider.NONE;
/// <summary>
/// Whether a fallback was chosen instead of the preferred provider.
/// </summary>
public bool UsesFallback => this.HasProvider && this.PreferredIssue is not AIOperationProviderIssue.NONE;
/// <summary>
/// Chooses the provider for an AI operation from the facts about its candidates.
/// </summary>
/// <remarks>
/// <para>
/// The preferred provider wins when somebody named it, when it exists, when the organization did not
/// prohibit it, when it reaches the global minimum, the minimum of the operation, and the confidence the
/// content requires, and when it passes the check of the caller.
/// </para>
/// <para>
/// Otherwise, the first fallback in the order of the caller wins which passes the same. The minimum of
/// the operation applies to the fallbacks only when the rules say so; a prohibition, the global minimum,
/// the confidence the content requires, and the check of the caller apply to every candidate.
/// </para>
/// </remarks>
/// <param name="preferred">The provider picked for the operation itself.</param>
/// <param name="fallbacks">The providers to fall back on, in the order of the caller.</param>
/// <param name="rules">The confidence levels to reach.</param>
/// <returns>The chosen provider with the reasons why the others were not chosen.</returns>
public static AIOperationProviderChoice Choose(AIOperationProviderCandidate preferred, IReadOnlyList<AIOperationProviderCandidate> fallbacks, AIOperationProviderRules rules)
{
var preferredIssue = Check(preferred, rules, false);
if (preferredIssue is AIOperationProviderIssue.NONE)
return new(preferred.Provider, AIOperationProviderIssue.NONE, AIOperationProviderIssue.NONE);
// A named candidate never reports NOT_SET, so this stays NOT_SET until the first named fallback fails:
var fallbackIssue = AIOperationProviderIssue.NOT_SET;
foreach (var fallback in fallbacks)
{
var issue = Check(fallback, rules, true);
if (issue is AIOperationProviderIssue.NONE)
return new(fallback.Provider, preferredIssue, AIOperationProviderIssue.NONE);
if (fallbackIssue is AIOperationProviderIssue.NOT_SET)
fallbackIssue = issue;
}
return new(Settings.Provider.NONE, preferredIssue, fallbackIssue);
}
/// <summary>
/// Finds the first rule a candidate breaks, in the order of AIOperationProviderIssue.
/// </summary>
private static AIOperationProviderIssue Check(AIOperationProviderCandidate candidate, AIOperationProviderRules rules, bool isFallback)
{
if (!candidate.IsNamed)
return AIOperationProviderIssue.NOT_SET;
if (!candidate.Exists)
return AIOperationProviderIssue.MISSING;
if (candidate.IsProhibited)
return AIOperationProviderIssue.PROHIBITED;
if (candidate.Confidence < rules.GlobalMinimumConfidence)
return AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE;
if ((!isFallback || rules.OwnMinimumAppliesToFallbacks) && candidate.Confidence < rules.OwnMinimumConfidence)
return AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE;
if (candidate.Confidence < rules.RequiredConfidence)
return AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT;
return candidate.CallerIssue;
}
}
@@ -0,0 +1,53 @@
namespace AIStudio.AIOperations;
/// <summary>
/// Why a provider was not chosen for an AI operation.
/// </summary>
/// <remarks>
/// The members follow the order in which AIOperationProviderChoice checks a candidate, so that a candidate
/// reports the first rule it breaks.
/// </remarks>
public enum AIOperationProviderIssue
{
/// <summary>
/// Nothing stands in the way of the provider.
/// </summary>
NONE = 0,
/// <summary>
/// Nobody named a provider here.
/// </summary>
/// <remarks>
/// That is no problem to report: an operation without a provider of its own falls back as intended.
/// </remarks>
NOT_SET,
/// <summary>
/// The named provider is no longer configured, e.g., because the user deleted it.
/// </summary>
MISSING,
/// <summary>
/// The organization prohibited the provider.
/// </summary>
PROHIBITED,
/// <summary>
/// The confidence level of the provider is below the global minimum or below the minimum of the operation.
/// </summary>
BELOW_MINIMUM_CONFIDENCE,
/// <summary>
/// The content of the request must not reach the provider.
/// </summary>
/// <remarks>
/// Either the confidence level of the provider is below what the content requires, or a check of the
/// caller refused the provider, e.g., for the security of a data source or the restrictions of a chat.
/// </remarks>
NOT_ALLOWED_FOR_CONTENT,
/// <summary>
/// A check of the caller found the context window of the model too small for the operation.
/// </summary>
CONTEXT_WINDOW_TOO_SMALL,
}
@@ -0,0 +1,34 @@
namespace AIStudio.AIOperations;
/// <summary>
/// What the caller of an AI operation adds to the choice of its provider.
/// </summary>
public sealed record AIOperationProviderOptions
{
/// <summary>
/// The IDs of the providers to fall back on when the preferred provider of the operation cannot be used, in order.
/// </summary>
/// <remarks>
/// An empty ID is allowed and stands for a fallback nobody named, e.g., an assistant without a provider.
/// </remarks>
public IReadOnlyList<string?> FallbackProviderIds { get; init; } = [];
/// <summary>
/// Whether the minimum confidence of the operation applies to the fallbacks as well.
/// </summary>
/// <remarks>
/// Usually it does: a provider somebody picked for something else has to clear the bar of the operation,
/// otherwise a provider ruled out for it would still see its content. A caller turns it off where the
/// fallback saw the content anyway, e.g., the model of a chat which summarizes that very chat.
/// </remarks>
public bool OwnMinimumConfidenceAppliesToFallbacks { get; init; } = true;
/// <summary>
/// An optional check of the caller, applied to every configured candidate.
/// </summary>
/// <remarks>
/// It returns NONE when the provider passes, and otherwise the issue to report, usually
/// NOT_ALLOWED_FOR_CONTENT or CONTEXT_WINDOW_TOO_SMALL.
/// </remarks>
public Func<Settings.Provider, AIOperationProviderIssue>? CheckProvider { get; init; }
}
@@ -0,0 +1,78 @@
using AIStudio.Provider;
using AIStudio.Settings;
namespace AIStudio.AIOperations;
/// <summary>
/// Chooses the provider for a call of an AI operation.
/// </summary>
/// <remarks>
/// It gathers the facts about each candidate from the settings, fresh on every call, and leaves the decision
/// to AIOperationProviderChoice.Choose. Every caller which runs an operation chooses through it, and so does
/// every check which needs to know in advance which provider would see the content, so that the two never
/// drift apart.
/// </remarks>
public sealed class AIOperationProviderResolver(SettingsManager settingsManager, ILogger<AIOperationProviderResolver> logger)
{
/// <summary>
/// Chooses the provider for running an operation with the given request, and logs the choice.
/// </summary>
/// <param name="operation">The operation to run.</param>
/// <param name="request">The request to run it with.</param>
/// <param name="settings">The provider settings of the operation, from its GetProviderSettings.</param>
/// <param name="options">What the caller adds: the fallbacks, whether the minimum of the operation applies to them, and a check of its own.</param>
/// <returns>The chosen provider with the reasons why the others were not chosen.</returns>
public AIOperationProviderChoice Resolve<TRequest, TResult>(IAIOperation<TRequest, TResult> operation, TRequest request, AIOperationProviderSettings settings, AIOperationProviderOptions options)
{
var choice = this.Preview(settings, operation.GetRequiredConfidence(request), options);
if (choice.HasProvider)
{
var provider = choice.Provider;
var fallbackNote = choice.UsesFallback ? $" as a fallback, since its preferred provider was {choice.PreferredIssue}" : string.Empty;
logger.LogInformation($"The AI operation '{operation.Id}' uses the provider '{provider.InstanceName}' ({provider.UsedLLMProvider.Name}, confidence={provider.UsedLLMProvider.GetConfidence(settingsManager).Level.Name}){fallbackNote}.");
}
else
logger.LogWarning($"The AI operation '{operation.Id}' has no provider: its preferred provider was {choice.PreferredIssue}, its first fallback was {choice.FallbackIssue}.");
return choice;
}
/// <summary>
/// Chooses the provider which would run an operation, without logging the choice.
/// </summary>
/// <remarks>
/// For checks in advance, e.g., which providers get to see the data of a data source.
/// </remarks>
/// <param name="settings">The provider settings of the operation, from its GetProviderSettings.</param>
/// <param name="requiredConfidence">The confidence level the content of the request requires; NONE when it is not known yet.</param>
/// <param name="options">What the caller adds: the fallbacks, whether the minimum of the operation applies to them, and a check of its own.</param>
/// <returns>The chosen provider with the reasons why the others were not chosen.</returns>
public AIOperationProviderChoice Preview(AIOperationProviderSettings settings, ConfidenceLevel requiredConfidence, AIOperationProviderOptions options)
{
var preferred = this.Describe(settings.PreferredProviderId, options.CheckProvider);
var fallbacks = options.FallbackProviderIds.Select(id => this.Describe(id, options.CheckProvider)).ToList();
var rules = new AIOperationProviderRules(settingsManager.GlobalMinimumConfidenceLevel, settings.MinimumConfidence, requiredConfidence, options.OwnMinimumConfidenceAppliesToFallbacks);
return AIOperationProviderChoice.Choose(preferred, fallbacks, rules);
}
/// <summary>
/// Gathers the facts about the provider with the given ID.
/// </summary>
private AIOperationProviderCandidate Describe(string? providerId, Func<Settings.Provider, AIOperationProviderIssue>? checkProvider)
{
if (string.IsNullOrWhiteSpace(providerId) || string.Equals(providerId, Settings.Provider.NONE.Id, StringComparison.OrdinalIgnoreCase))
return AIOperationProviderCandidate.NOT_NAMED;
var provider = settingsManager.GetProviderById(providerId);
if (provider == Settings.Provider.NONE || provider.UsedLLMProvider is LLMProviders.NONE)
return AIOperationProviderCandidate.MISSING;
return new AIOperationProviderCandidate(
provider,
true,
true,
settingsManager.IsProviderProhibited(provider.UsedLLMProvider),
provider.UsedLLMProvider.GetConfidence(settingsManager).Level,
checkProvider?.Invoke(provider) ?? AIOperationProviderIssue.NONE);
}
}
@@ -0,0 +1,12 @@
using AIStudio.Provider;
namespace AIStudio.AIOperations;
/// <summary>
/// The confidence levels which a provider has to reach for an AI operation.
/// </summary>
/// <param name="GlobalMinimumConfidence">The global minimum, when the user or the organization enforces one. It applies to every candidate.</param>
/// <param name="OwnMinimumConfidence">The minimum of the operation itself, from its settings.</param>
/// <param name="RequiredConfidence">What the content of the request requires, e.g., its data sources. It applies to every candidate.</param>
/// <param name="OwnMinimumAppliesToFallbacks">Whether the minimum of the operation applies to the fallbacks as well, not only to its preferred provider.</param>
public sealed record AIOperationProviderRules(ConfidenceLevel GlobalMinimumConfidence, ConfidenceLevel OwnMinimumConfidence, ConfidenceLevel RequiredConfidence, bool OwnMinimumAppliesToFallbacks);
@@ -0,0 +1,16 @@
using AIStudio.Provider;
namespace AIStudio.AIOperations;
/// <summary>
/// The settings of an AI operation which decide its provider.
/// </summary>
/// <param name="PreferredProviderId">The ID of the provider picked for the operation; empty when nobody picked one or when the preselection is switched off.</param>
/// <param name="MinimumConfidence">The minimum confidence level of the operation itself.</param>
public sealed record AIOperationProviderSettings(string PreferredProviderId, ConfidenceLevel MinimumConfidence)
{
/// <summary>
/// No provider of its own and no minimum.
/// </summary>
public static readonly AIOperationProviderSettings NONE = new(string.Empty, ConfidenceLevel.NONE);
}
@@ -0,0 +1,21 @@
using System.Text.Json;
namespace AIStudio.AIOperations;
/// <summary>
/// How AI operations read the JSON in the answers of models.
/// </summary>
/// <remarks>
/// Find the JSON in an answer with ModelAnswerJson first, then read it with these options.
/// </remarks>
internal static class AIOperationsJson
{
/// <summary>
/// The options for the JSON in a model answer to an AI operation.
/// </summary>
internal static readonly JsonSerializerOptions OPTIONS = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
TypeInfoResolver = AIOperationsJsonContext.Default,
}.AsReadOnly();
}
@@ -0,0 +1,16 @@
using System.Text.Json.Serialization;
using AIStudio.AIOperations.DataSourceChoice;
using AIStudio.AIOperations.PluginAudit;
using AIStudio.AIOperations.RetrievalContextValidation;
namespace AIStudio.AIOperations;
/// <summary>
/// The contracts with which System.Text.Json reads the answers of models to AI operations, built at compile time.
/// </summary>
[JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(List<SelectedDataSource>))]
[JsonSerializable(typeof(RetrievalContextValidationAnswer))]
[JsonSerializable(typeof(PluginAuditResult))]
internal sealed partial class AIOperationsJsonContext : JsonSerializerContext;
@@ -0,0 +1 @@
@AGENTS.md
@@ -0,0 +1,198 @@
using System.Text;
using System.Text.Json;
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
using AIStudio.Tools.Services;
namespace AIStudio.AIOperations.DataSourceChoice;
/// <summary>
/// Chooses the data sources which fit a prompt, from the descriptions of the data sources.
/// </summary>
/// <remarks>
/// The classic RAG process runs it before it searches, see AgenticSrcSelWithDynHeur.
/// </remarks>
public sealed class DataSourceChoiceOperation(ILogger<DataSourceChoiceOperation> logger, SettingsManager settingsManager, DataSourceDescriptionService descriptionService) : AIOperationBase<DataSourceChoiceRequest, DataSourceChoiceResult>(logger, settingsManager)
{
private const string JOB_DESCRIPTION =
"""
You receive a system and a user prompt, as well as a list of possible data sources as input.
Your task is to select the appropriate data sources for the given task. You may choose none,
one, or multiple sources, depending on what best fits the system and user prompt. You need
to estimate and assess which source, based on its description, might be helpful in
processing the prompts.
Your response is a JSON list in the following format:
```
[
{"id": "The data source ID", "reason": "Why did you choose this source?", "confidence": 0.87},
{"id": "The data source ID", "reason": "Why did you choose this source?", "confidence": 0.54}
]
```
You express your confidence as a floating-point number between 0.0 (maximum uncertainty) and
1.0 (you are absolutely certain that this source is needed).
The JSON schema is:
```
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array",
"items": [
{
"type": "object",
"properties": {
"id": {
"type": "string"
},
"reason": {
"type": "string"
},
"confidence": {
"type": "number"
}
},
"required": [
"id",
"reason",
"confidence"
]
}
]
}
```
When no data source is needed, you return an empty JSON list `[]`. You do not ask any
follow-up questions. You do not address the user. Your response consists solely of
the JSON list.
""";
/// <summary>
/// Reads the provider settings of the operation.
/// </summary>
/// <param name="settingsManager">The settings to read.</param>
/// <returns>The preferred provider and the minimum confidence, or none of them while the preselection is switched off.</returns>
public static AIOperationProviderSettings GetProviderSettings(SettingsManager settingsManager)
{
var settings = settingsManager.ConfigurationData.AgentDataSourceSelection;
return settings.PreselectAgentOptions
? new(settings.PreselectedAgentProvider, settings.MinimumProviderConfidence)
: AIOperationProviderSettings.NONE;
}
#region Overrides of AIOperationBase
/// <inheritdoc />
public override string Id => "Data Source Selection";
/// <inheritdoc />
public override Tools.Components Component => Tools.Components.AGENT_DATA_SOURCE_SELECTION;
/// <summary>
/// The model reads the descriptions of the data sources, so it has to reach what they require.
/// </summary>
public override ConfidenceLevel GetRequiredConfidence(DataSourceChoiceRequest request) => request.DataSources.GetRequiredConfidenceLevel();
/// <inheritdoc />
public override async Task<DataSourceChoiceResult> RunAsync(DataSourceChoiceRequest request, AIOperationContext context, CancellationToken token = default)
{
this.Logger.LogInformation("The AI should select the appropriate data sources.");
//
// 1. Prepare the last prompt of the user as input:
//
var lastPromptContent = request.LastUserPrompt switch
{
ContentText text => text.Text,
// Image prompts may be empty, e.g., when the image is too large:
ContentImage image => await image.TryAsBase64(token) is (success: true, { } base64Image)
? base64Image
: string.Empty,
// Other content types are not supported yet:
_ => string.Empty,
};
if (string.IsNullOrWhiteSpace(lastPromptContent))
{
this.Logger.LogWarning("The last prompt is empty. The AI cannot select data sources.");
return DataSourceChoiceResult.NOT_ANSWERED;
}
//
// 2. Prepare the data sources to choose from:
//
var availableDataSources = new StringBuilder();
availableDataSources.AppendLineLF("The following data sources are available for selection:");
foreach (var dataSource in request.DataSources)
{
var description = await descriptionService.GetDescriptionAsync(dataSource, token);
var descriptionPart = string.IsNullOrWhiteSpace(description) ? string.Empty : $", description='{description}'";
switch (dataSource)
{
case DataSourceLocalDirectory localDirectory:
availableDataSources.AppendLineLF($"- Id={dataSource.Id}, name='{localDirectory.Name}', type=local directory, path='{localDirectory.Path}'{descriptionPart}");
break;
case DataSourceLocalFile localFile:
availableDataSources.AppendLineLF($"- Id={dataSource.Id}, name='{localFile.Name}', type=local file, path='{localFile.FilePath}'{descriptionPart}");
break;
case IERIDataSource eriDataSource:
availableDataSources.AppendLineLF($"- Id={dataSource.Id}, name='{eriDataSource.Name}', type=external data source{descriptionPart}");
break;
}
}
var systemPrompt = $"""
{JOB_DESCRIPTION}
{availableDataSources}
""";
var userPrompt = $"""
The system prompt is:
```
{request.SystemPrompt}
```
The user prompt is:
```
{lastPromptContent}
```
""";
//
// 3. Let the model choose:
//
var answer = await this.AskAsync(request, context, systemPrompt, userPrompt, token);
if (answer is null)
return DataSourceChoiceResult.NOT_ANSWERED;
//
// 4. Read the answer. We know how bad models may be at writing JSON without surrounding text,
// so we expect the worst and extract the JSON list from the text:
//
var json = ModelAnswerJson.ExtractObjectList(answer);
try
{
var selectedDataSources = JsonSerializer.Deserialize<List<SelectedDataSource>>(json, AIOperationsJson.OPTIONS);
return new DataSourceChoiceResult(selectedDataSources ?? [], true);
}
catch
{
this.Logger.LogWarning("The AI answered with an invalid or unexpected JSON format.");
return DataSourceChoiceResult.NOT_ANSWERED;
}
}
#endregion
}
@@ -0,0 +1,12 @@
using AIStudio.Chat;
using AIStudio.Settings;
namespace AIStudio.AIOperations.DataSourceChoice;
/// <summary>
/// A prompt for which a model chooses the data sources to search.
/// </summary>
/// <param name="SystemPrompt">The system prompt of the chat.</param>
/// <param name="LastUserPrompt">The last prompt of the user.</param>
/// <param name="DataSources">The data sources to choose from, which the chat may use.</param>
public sealed record DataSourceChoiceRequest(string SystemPrompt, IContent LastUserPrompt, IReadOnlyList<IDataSource> DataSources);
@@ -0,0 +1,14 @@
namespace AIStudio.AIOperations.DataSourceChoice;
/// <summary>
/// The data sources a model chose for a prompt.
/// </summary>
/// <param name="SelectedDataSources">The chosen data sources, as the model named them; empty when it chose none.</param>
/// <param name="IsAnswered">Whether the model gave a usable answer. Without one, nothing was chosen either.</param>
public sealed record DataSourceChoiceResult(IReadOnlyList<SelectedDataSource> SelectedDataSources, bool IsAnswered)
{
/// <summary>
/// No usable answer: no provider, an empty prompt, or an answer without valid JSON.
/// </summary>
public static readonly DataSourceChoiceResult NOT_ANSWERED = new([], false);
}
@@ -1,9 +1,9 @@
namespace AIStudio.Agents;
namespace AIStudio.AIOperations.DataSourceChoice;
/// <summary>
/// Represents a selected data source, chosen by the agent.
/// Represents a selected data source, chosen by the model.
/// </summary>
/// <param name="Id">The data source ID.</param>
/// <param name="Reason">The reason for selecting the data source.</param>
/// <param name="Confidence">The confidence of the agent in the selection.</param>
/// <param name="Confidence">The confidence of the model in the selection.</param>
public readonly record struct SelectedDataSource(string Id, string Reason, float Confidence) : IConfidence;
@@ -0,0 +1,58 @@
using AIStudio.Provider;
namespace AIStudio.AIOperations;
/// <summary>
/// A task which AI Studio hands to a model on its own: one request in, one result out, without a loop.
/// </summary>
/// <remarks>
/// <para>
/// An operation is registered as a singleton and keeps no state between calls, so several callers may run
/// it at the same time, e.g., two chats with RAG. Everything a call needs travels with it: the request, and
/// in the AIOperationContext the provider which the caller chose for it.
/// </para>
/// <para>
/// Each operation also declares a static method GetProviderSettings(SettingsManager), which reads the
/// provider settings of the operation fresh on every call. It is static, so that a service can learn which
/// provider would run without an instance of the operation. AIOperationProviderResolver chooses the
/// provider from these settings; see the AGENTS.md of this folder.
/// </para>
/// </remarks>
/// <typeparam name="TRequest">What the operation works on.</typeparam>
/// <typeparam name="TResult">What the operation returns.</typeparam>
public interface IAIOperation<in TRequest, TResult>
{
/// <summary>
/// The name of the operation in the log, in English.
/// </summary>
public string Id { get; }
/// <summary>
/// The component the operation runs as.
/// </summary>
/// <remarks>
/// Its requests name it, e.g., in the User-Agent for self-hosted servers. Without it, an operation
/// working for an assistant would be counted as chat.
/// </remarks>
public Tools.Components Component { get; }
/// <summary>
/// The confidence level which the content of the request requires of a provider.
/// </summary>
/// <remarks>
/// It comes from the request alone, e.g., from the data sources it carries or from the confidence a
/// chat requires. The minimum confidence of the operation itself is a setting and not part of it.
/// </remarks>
/// <param name="request">The request to run.</param>
/// <returns>The confidence level the content requires, NONE when it requires nothing.</returns>
public ConfidenceLevel GetRequiredConfidence(TRequest request);
/// <summary>
/// Runs the operation for one request.
/// </summary>
/// <param name="request">The request to run.</param>
/// <param name="context">What the call runs with, the provider above all.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The result of the operation.</returns>
public Task<TResult> RunAsync(TRequest request, AIOperationContext context, CancellationToken token = default);
}
@@ -1,11 +1,11 @@
using System.Text.Json.Serialization;
namespace AIStudio.Agents.AssistantAudit;
namespace AIStudio.AIOperations.PluginAudit;
/// <summary>
/// Represents a single structured security finding produced by the assistant audit agent.
/// Represents a single structured security finding produced by the security audit of a plugin.
/// </summary>
public sealed class AssistantAuditFinding
public sealed class PluginAuditFinding
{
#pragma warning disable MWAIS0005
/// <summary>
@@ -13,7 +13,7 @@ public sealed class AssistantAuditFinding
/// </summary>
#pragma warning restore MWAIS0005
[JsonIgnore]
public AssistantAuditLevel Severity { get; private set; } = AssistantAuditLevel.UNKNOWN;
public PluginAuditLevel Severity { get; private set; } = PluginAuditLevel.UNKNOWN;
/// <summary>
@@ -24,22 +24,22 @@ public sealed class AssistantAuditFinding
{
get => this.Severity switch
{
AssistantAuditLevel.DANGEROUS => "critical",
AssistantAuditLevel.CAUTION => "medium",
AssistantAuditLevel.SAFE => "low",
PluginAuditLevel.DANGEROUS => "critical",
PluginAuditLevel.CAUTION => "medium",
PluginAuditLevel.SAFE => "low",
_ => "unknown",
};
set => this.Severity = value.Trim().ToLowerInvariant() switch
{
"critical" => AssistantAuditLevel.DANGEROUS,
"medium" => AssistantAuditLevel.CAUTION,
"low" => AssistantAuditLevel.SAFE,
_ => AssistantAuditLevel.UNKNOWN,
"critical" => PluginAuditLevel.DANGEROUS,
"medium" => PluginAuditLevel.CAUTION,
"low" => PluginAuditLevel.SAFE,
_ => PluginAuditLevel.UNKNOWN,
};
}
public string Category { get; set; } = string.Empty;
public string Location { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
}
}
@@ -1,12 +1,12 @@
namespace AIStudio.Agents.AssistantAudit;
namespace AIStudio.AIOperations.PluginAudit;
/// <summary>
/// Defines the normalized outcome levels used for assistant plugin security audits.
/// </summary>
public enum AssistantAuditLevel
public enum PluginAuditLevel
{
UNKNOWN = 0,
DANGEROUS = 100,
CAUTION = 200,
SAFE = 300,
}
}
@@ -0,0 +1,50 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.AIOperations.PluginAudit;
public static class PluginAuditLevelExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(PluginAuditLevelExtensions).Namespace, nameof(PluginAuditLevelExtensions));
extension(PluginAuditLevel level)
{
public string Name => level switch
{
PluginAuditLevel.DANGEROUS => TB("Dangerous"),
PluginAuditLevel.CAUTION => TB("Concerning"),
PluginAuditLevel.SAFE => TB("Safe"),
_ => TB("Unknown"),
};
public Severity Severity => level switch
{
PluginAuditLevel.DANGEROUS => Severity.Error,
PluginAuditLevel.CAUTION => Severity.Warning,
PluginAuditLevel.SAFE => Severity.Success,
_ => Severity.Info,
};
public Color Color => level switch
{
PluginAuditLevel.DANGEROUS => Color.Error,
PluginAuditLevel.CAUTION => Color.Warning,
PluginAuditLevel.SAFE => Color.Success,
_ => Color.Default,
};
public string Icon => level switch
{
PluginAuditLevel.DANGEROUS => AppIcons.SECURITY_DANGEROUS,
PluginAuditLevel.CAUTION => AppIcons.WARNING,
PluginAuditLevel.SAFE => AppIcons.AUDIT_SAFE,
_ => AppIcons.UNKNOWN,
};
/// <summary>
/// Parses an audit level string and falls back to <see cref="PluginAuditLevel.UNKNOWN"/> when parsing fails.
/// </summary>
/// <param name="value">The audit level text to parse.</param>
/// <returns>The parsed audit level, or <see cref="PluginAuditLevel.UNKNOWN"/> for null, empty, or invalid values.</returns>
public static PluginAuditLevel ParseOrUnknown(string? value) => Enum.TryParse<PluginAuditLevel>(value, true, out var parsedLevel) ? parsedLevel : PluginAuditLevel.UNKNOWN;
}
}
@@ -1,31 +1,26 @@
using System.Text;
using System.Text.Json;
using AIStudio.Assistants;
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.PluginSystem.Assistants;
using AIStudio.Tools.Services;
using AIStudio.Tools.ToolCallingSystem;
namespace AIStudio.Agents.AssistantAudit;
namespace AIStudio.AIOperations.PluginAudit;
/// <summary>
/// Audits dynamic assistant plugins by sending their prompts, component structure, and Lua manifest
/// to a configured LLM and normalizing the response into a structured audit result.
/// Audits an assistant plugin by sending its prompts, component structure, and Lua manifest to a model and
/// normalizing the answer into a structured audit result.
/// </summary>
public sealed class AssistantAuditAgent(ILogger<AssistantAuditAgent> logger, ILogger<AgentBase> baseLogger, SettingsManager settingsManager, DataSourceService dataSourceService, ToolRegistry toolRegistry, ThreadSafeRandom rng) : AgentBase(baseLogger, settingsManager, dataSourceService, rng)
public sealed class PluginAuditOperation(ILogger<PluginAuditOperation> logger, SettingsManager settingsManager, ToolRegistry toolRegistry) : AIOperationBase<PluginAuditRequest, PluginAuditResult>(logger, settingsManager)
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(AssistantAuditAgent).Namespace, nameof(AssistantAuditAgent));
protected override Type Type => Type.SYSTEM;
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(PluginAuditOperation).Namespace, nameof(PluginAuditOperation));
protected override Tools.Components Component => Tools.Components.AGENT_ASSISTANT_PLUGIN_AUDIT;
private static string TA(string fallbackEN) => I18N.I.TA(fallbackEN, typeof(PluginAuditOperation).Namespace, nameof(PluginAuditOperation));
public override string Id => "Assistant Plugin Security Audit";
protected override string JobDescription =>
private const string JOB_DESCRIPTION =
"""
You are a conservative security auditor for Lua-based assistant plugins in private and enterprise environments.
The Lua code is parsed into functional assistants that help users with tasks like coding, emails, translations, and other workflows defined by plugin developers.
@@ -99,90 +94,38 @@ public sealed class AssistantAuditAgent(ILogger<AssistantAuditAgent> logger, ILo
and do not limit yourself to literal phrase matching.
""";
protected override string SystemPrompt(string additionalData) => string.IsNullOrWhiteSpace(additionalData)
? this.JobDescription
: $"{this.JobDescription}{Environment.NewLine}{Environment.NewLine}{additionalData}";
public override AIStudio.Settings.Provider ProviderSettings { get; set; } = AIStudio.Settings.Provider.NONE;
public override Task<ChatThread> ProcessContext(ChatThread chatThread, IDictionary<string, string> additionalData) => Task.FromResult(chatThread);
public override async Task<ContentBlock> ProcessInput(ContentBlock input, IDictionary<string, string> additionalData)
{
if (input.Content is not ContentText text || string.IsNullOrWhiteSpace(text.Text) || text.InitialRemoteWait || text.IsStreaming)
return EMPTY_BLOCK;
var thread = this.CreateChatThread(this.SystemPrompt(string.Empty));
var userRequest = AddUserRequest(thread, text.Text);
await this.AddAIResponseAsync(thread, userRequest.UserPrompt, userRequest.Time);
return thread.Blocks[^1];
}
public override Task<bool> MadeDecision(ContentBlock input) => Task.FromResult(true);
public override IReadOnlyCollection<ContentBlock> GetContext() => [];
public override IReadOnlyCollection<ContentBlock> GetAnswers() => [];
/// <summary>
/// Resolves and stores the provider configuration used for assistant plugin audits.
/// Reads the provider settings of the operation.
/// </summary>
/// <param name="fallbackProvider">The provider to use when no provider is configured for the audit agent.</param>
/// <returns>The configured provider, or Provider.NONE when no audit provider is configured.</returns>
/// <remarks>
/// A fallback is a provider somebody picked for something else: the assistant they were building,
/// the revision they asked for, the check they are standing in front of. Whether it may read a
/// plugin's source and its Lua files is decided by what this agent requires, not by what it was
/// picked under, so it has to clear this agent's confidence bar before it is used. Otherwise a
/// provider an organization ruled out for audits would see the very thing it was ruled out for.
/// Unlike the other operations, the audit has no switch for its preselection: an organization rolls its
/// provider out, and that is what audits run with.
/// </remarks>
public AIStudio.Settings.Provider ResolveProvider(AIStudio.Settings.Provider? fallbackProvider = null)
/// <param name="settingsManager">The settings to read.</param>
/// <returns>The preferred provider and the minimum confidence.</returns>
public static AIOperationProviderSettings GetProviderSettings(SettingsManager settingsManager)
{
var provider = this.SettingsManager.GetPreselectedProvider(Tools.Components.AGENT_ASSISTANT_PLUGIN_AUDIT, null, true);
if (provider == AIStudio.Settings.Provider.NONE && fallbackProvider is { } candidate && this.SettingsManager.IsProviderConfident(candidate, Tools.Components.AGENT_ASSISTANT_PLUGIN_AUDIT))
provider = candidate;
this.ProviderSettings = provider;
return provider;
var settings = settingsManager.ConfigurationData.AssistantPluginAudit;
return new(settings.PreselectedAgentProvider, settings.MinimumProviderConfidence);
}
#region Overrides of AIOperationBase
/// <inheritdoc />
public override string Id => "Assistant Plugin Security Audit";
/// <inheritdoc />
public override Tools.Components Component => Tools.Components.AGENT_ASSISTANT_PLUGIN_AUDIT;
/// <summary>
/// Runs a security audit for the specified assistant plugin and parses the LLM response into a structured result.
/// A plugin requires nothing of its own: whoever may audit it is decided by the minimum of the audit.
/// </summary>
/// <param name="plugin">The assistant plugin to audit.</param>
/// <param name="fallbackProvider">The provider to use when no provider is configured for the audit agent.</param>
/// <param name="token">A cancellation token for prompt generation and the audit request.</param>
/// <returns>
/// The parsed audit result, or an <c>UNKNOWN</c> result when no provider is configured or the model response cannot be used.
/// </returns>
public async Task<AssistantAuditResult> AuditAsync(PluginAssistants plugin, Settings.Provider? fallbackProvider = null, CancellationToken token = default)
public override ConfidenceLevel GetRequiredConfidence(PluginAuditRequest request) => ConfidenceLevel.NONE;
/// <inheritdoc />
public override async Task<PluginAuditResult> RunAsync(PluginAuditRequest request, AIOperationContext context, CancellationToken token = default)
{
var provider = this.ResolveProvider(fallbackProvider);
if (provider == AIStudio.Settings.Provider.NONE)
{
//
// There are two ways to end up here, and they send the user to different places: nobody
// named a provider, or the one at hand is not trusted enough for an audit. Saying that
// none is configured while one sits right there would send them looking in vain.
//
var wasFallbackRejected = fallbackProvider is { UsedLLMProvider: not LLMProviders.NONE };
var message = wasFallbackRejected
? TB("The selected provider is not trusted enough for security checks. Pick one which meets the confidence required here, or choose a dedicated provider for security checks in the app settings.")
: TB("No provider is configured for the Security Audit Agent.");
await MessageBus.INSTANCE.SendError(new (Icons.Material.Filled.SettingsSuggest, message));
return new AssistantAuditResult
{
Level = nameof(AssistantAuditLevel.UNKNOWN),
Summary = wasFallbackRejected
? TB("The provider is not trusted enough for security checks.")
: TB("No audit provider is configured."),
};
}
logger.LogInformation($"The assistant plugin audit agent uses the provider '{provider.InstanceName}' ({provider.UsedLLMProvider.Name}, confidence={provider.UsedLLMProvider.GetConfidence(this.SettingsManager).Level.Name}).");
var plugin = request.Plugin;
var promptPreview = await plugin.BuildAuditPromptPreviewAsync(token);
var promptFallbackPreview = plugin.BuildAuditPromptFallbackPreview();
var luaManifest = FormatLuaManifest(plugin.ReadAllLuaFiles());
@@ -256,64 +199,56 @@ public sealed class AssistantAuditAgent(ILogger<AssistantAuditAgent> logger, ILo
```
""";
var response = await this.ProcessInput(new ContentBlock
var answer = await this.AskAsync(request, context, JOB_DESCRIPTION, userPrompt, token);
if (answer is null)
{
Time = DateTimeOffset.UtcNow,
ContentType = ContentType.TEXT,
Role = ChatRole.USER,
Content = new ContentText
{
Text = userPrompt,
},
}, new Dictionary<string, string>());
this.Logger.LogWarning("The AI operation for the plugin audit got no usable answer.");
await MessageBus.INSTANCE.SendWarning(new (AppIcons.AUDIT_INCOMPLETE, TA("The security check could not be completed because the LLM's response was unusable. The audit level remains Unknown, so please try again later.")));
if (response.Content is not ContentText content || string.IsNullOrWhiteSpace(content.Text))
{
logger.LogWarning($"The assistant plugin audit agent did not return text: {response}");
await MessageBus.INSTANCE.SendWarning(new (Icons.Material.Filled.PendingActions, string.Format(TB("The security check could not be completed because the LLM's response was unusable. The audit level remains Unknown, so please try again later."))));
return new AssistantAuditResult
return new PluginAuditResult
{
Level = nameof(AssistantAuditLevel.UNKNOWN),
Summary = TB("The audit agent did not return a usable response."),
Level = nameof(PluginAuditLevel.UNKNOWN),
Summary = TB("The audit did not return a usable response."),
};
}
var json = ModelAnswerJson.ExtractObject(content.Text);
var json = ModelAnswerJson.ExtractObject(answer);
try
{
var result = JsonSerializer.Deserialize<AssistantAuditResult>(json, JSON_SERIALIZER_OPTIONS);
var result = JsonSerializer.Deserialize<PluginAuditResult>(json, AIOperationsJson.OPTIONS);
return result is null
? new AssistantAuditResult
? new PluginAuditResult
{
Level = nameof(AssistantAuditLevel.UNKNOWN),
Level = nameof(PluginAuditLevel.UNKNOWN),
Summary = TB("The audit result was empty."),
}
: NormalizeResult(result);
}
catch
{
logger.LogWarning($"The assistant plugin audit agent returned invalid JSON: {json}");
return new AssistantAuditResult
this.Logger.LogWarning($"The AI operation for the plugin audit got invalid JSON: {json}");
return new PluginAuditResult
{
Level = nameof(AssistantAuditLevel.UNKNOWN),
Summary = TB("The audit agent returned invalid JSON."),
Level = nameof(PluginAuditLevel.UNKNOWN),
Summary = TB("The audit returned invalid JSON."),
};
}
}
#endregion
/// <summary>
/// Normalizes the model output so deterministic policy rules can correct inconsistent level assignments.
/// </summary>
private static AssistantAuditResult NormalizeResult(AssistantAuditResult result)
private static PluginAuditResult NormalizeResult(PluginAuditResult result)
{
var normalizedFindings = result.Findings;
var parsedLevel = AssistantAuditLevel.ParseOrUnknown(result.Level);
var parsedLevel = PluginAuditLevel.ParseOrUnknown(result.Level);
var lowestFindingLevel = GetMostSevereFindingLevel(normalizedFindings);
if (lowestFindingLevel != AssistantAuditLevel.UNKNOWN && (parsedLevel == AssistantAuditLevel.UNKNOWN || lowestFindingLevel < parsedLevel))
if (lowestFindingLevel != PluginAuditLevel.UNKNOWN && (parsedLevel == PluginAuditLevel.UNKNOWN || lowestFindingLevel < parsedLevel))
parsedLevel = lowestFindingLevel;
return new AssistantAuditResult
return new PluginAuditResult
{
Level = parsedLevel.ToString(),
Summary = result.Summary,
@@ -343,11 +278,11 @@ public sealed class AssistantAuditAgent(ILogger<AssistantAuditAgent> logger, ILo
var definition = toolRegistry.GetDefinition(toolId);
if (definition is null)
{
builder.AppendLine($"- {toolId}: unknown to this installation");
builder.AppendLineLF($"- {toolId}: unknown to this installation");
continue;
}
builder.AppendLine($"- {toolId}: {definition.Function.DescriptionForLLM}");
builder.AppendLineLF($"- {toolId}: {definition.Function.DescriptionForLLM}");
}
return builder.ToString().TrimEnd();
@@ -368,11 +303,11 @@ public sealed class AssistantAuditAgent(ILogger<AssistantAuditAgent> logger, ILo
foreach (var luaFile in luaFiles.OrderBy(file => file.Key, StringComparer.Ordinal))
{
if (builder.Length > 0)
builder.AppendLine().AppendLine();
builder.AppendLineLF().AppendLineLF();
builder.Append("-- File: ");
builder.AppendLine(luaFile.Key);
builder.AppendLine(luaFile.Value);
builder.AppendLineLF(luaFile.Key);
builder.AppendLineLF(luaFile.Value);
}
return builder.ToString().TrimEnd();
@@ -381,19 +316,19 @@ public sealed class AssistantAuditAgent(ILogger<AssistantAuditAgent> logger, ILo
/// <summary>
/// Returns the most severe finding level contained in the result, where DANGEROUS is more severe than CAUTION and SAFE.
/// </summary>
private static AssistantAuditLevel GetMostSevereFindingLevel(IEnumerable<AssistantAuditFinding> findings)
private static PluginAuditLevel GetMostSevereFindingLevel(IEnumerable<PluginAuditFinding> findings)
{
var mostSevere = AssistantAuditLevel.UNKNOWN;
var mostSevere = PluginAuditLevel.UNKNOWN;
foreach (var finding in findings)
{
if (finding.Severity == AssistantAuditLevel.UNKNOWN)
if (finding.Severity == PluginAuditLevel.UNKNOWN)
continue;
if (mostSevere == AssistantAuditLevel.UNKNOWN || finding.Severity < mostSevere)
if (mostSevere == PluginAuditLevel.UNKNOWN || finding.Severity < mostSevere)
mostSevere = finding.Severity;
}
return mostSevere;
}
}
}
@@ -0,0 +1,9 @@
using AIStudio.Tools.PluginSystem.Assistants;
namespace AIStudio.AIOperations.PluginAudit;
/// <summary>
/// A plugin to audit for security risks.
/// </summary>
/// <param name="Plugin">The assistant plugin to audit.</param>
public sealed record PluginAuditRequest(PluginAssistants Plugin);
@@ -1,15 +1,15 @@
namespace AIStudio.Agents.AssistantAudit;
namespace AIStudio.AIOperations.PluginAudit;
/// <summary>
/// Represents the normalized result returned by the assistant plugin security audit flow.
/// </summary>
public sealed record AssistantAuditResult
public sealed record PluginAuditResult
{
/// <summary>
/// Gets the serialized audit level returned by the model before callers normalize it to <see cref="AssistantAuditLevel"/>.
/// Gets the serialized audit level returned by the model before callers normalize it to <see cref="PluginAuditLevel"/>.
/// </summary>
public string Level { get; set; } = string.Empty;
public string Summary { get; set; } = string.Empty;
public float Confidence { get; set; }
public List<AssistantAuditFinding> Findings { get; set; } = [];
}
public List<PluginAuditFinding> Findings { get; set; } = [];
}
@@ -0,0 +1,14 @@
namespace AIStudio.AIOperations.RetrievalContextValidation;
/// <summary>
/// What a model writes when it judges whether a retrieval context helps with a prompt.
/// </summary>
/// <remarks>
/// Every value may be missing from the answer, and a missing value stays null instead of turning into the
/// default of its type. An answer without a decision or a confidence is no usable answer, see
/// RetrievalContextValidationOperation.ReadAnswer.
/// </remarks>
/// <param name="Decision">Whether the retrieval context helps with the prompt.</param>
/// <param name="Reason">Why the model decided so.</param>
/// <param name="Confidence">The probability that the decision is right, between 0 and 1.</param>
public readonly record struct RetrievalContextValidationAnswer(bool? Decision, string? Reason, float? Confidence);
@@ -0,0 +1,258 @@
using System.Text.Json;
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Tools.RAG;
namespace AIStudio.AIOperations.RetrievalContextValidation;
/// <summary>
/// Judges for each passage found by the classic RAG process whether it helps with the prompt.
/// </summary>
/// <remarks>
/// It asks one request per passage, several at once, as many as NumParallelValidations allows. The limit
/// holds per call: two chats validating at the same time each get their own.
/// </remarks>
public sealed class RetrievalContextValidationOperation(ILogger<RetrievalContextValidationOperation> logger, SettingsManager settingsManager) : AIOperationBase<RetrievalContextValidationRequest, IReadOnlyList<RetrievalContextValidationResult>>(logger, settingsManager)
{
private const int DEFAULT_PARALLEL_VALIDATIONS = 3;
private const string JOB_DESCRIPTION =
"""
You receive a system and user prompt as well as a retrieval context as input. Your task is to decide whether this
retrieval context is helpful in processing the prompts or not. You respond with the decision, your reasoning,
and your confidence in this decision.
Your decision is true when the retrieval context helps in processing the prompts, and false when it does not.
Your response is only one JSON object in the following format:
```
{"decision": true, "reason": "Why does this retrieval context help or not?", "confidence": 0.87}
```
Your confidence is the probability that your decision is right, as a floating-point number between 0.0 and
1.0: 0.5 means that your decision is no better than a guess, and 1.0 means that you are absolutely certain
of it. This holds for both decisions: when you are certain that the retrieval context does not help, your
decision is false and your confidence is 1.0.
The JSON schema is:
```
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"decision": {
"type": "boolean"
},
"reason": {
"type": "string"
},
"confidence": {
"type": "number",
"minimum": 0,
"maximum": 1
}
},
"required": [
"decision",
"reason",
"confidence"
]
}
```
You do not ask any follow-up questions. You do not address the user. Your response consists solely of
that one JSON object.
""";
/// <summary>
/// Reads the provider settings of the operation.
/// </summary>
/// <param name="settingsManager">The settings to read.</param>
/// <returns>The preferred provider and the minimum confidence, or none of them while the preselection is switched off.</returns>
public static AIOperationProviderSettings GetProviderSettings(SettingsManager settingsManager)
{
var settings = settingsManager.ConfigurationData.AgentRetrievalContextValidation;
return settings.PreselectAgentOptions
? new(settings.PreselectedAgentProvider, settings.MinimumProviderConfidence)
: AIOperationProviderSettings.NONE;
}
#region Overrides of AIOperationBase
/// <inheritdoc />
public override string Id => "Retrieval Context Validation";
/// <inheritdoc />
public override Tools.Components Component => Tools.Components.AGENT_RETRIEVAL_CONTEXT_VALIDATION;
/// <summary>
/// The model reads the passages, so it has to reach what the chat requires of every provider which reads its data.
/// </summary>
public override ConfidenceLevel GetRequiredConfidence(RetrievalContextValidationRequest request) => request.RequiredConfidence;
/// <inheritdoc />
public override async Task<IReadOnlyList<RetrievalContextValidationResult>> RunAsync(RetrievalContextValidationRequest request, AIOperationContext context, CancellationToken token = default)
{
this.Logger.LogInformation($"Validating {request.RetrievalContexts.Count:###,###,###,###} retrieval contexts.");
//
// The last prompt of the user is the same for every passage, so it is prepared once:
//
var lastPromptContent = request.LastUserPrompt switch
{
ContentText text => text.Text,
// Image prompts may be empty, e.g., when the image is too large:
ContentImage image => await image.TryAsBase64(token) is (success: true, { } base64Image)
? base64Image
: string.Empty,
// Other content types are not supported yet:
_ => string.Empty,
};
if (string.IsNullOrWhiteSpace(lastPromptContent))
{
this.Logger.LogWarning("The last prompt is empty. The AI cannot validate the retrieval contexts.");
return request.RetrievalContexts.Select(retrievalContext => RetrievalContextValidationResult.NotAnswered(retrievalContext, "The last prompt was empty.")).ToList();
}
var settings = this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation;
var numParallelValidations = settings.PreselectAgentOptions ? settings.NumParallelValidations : DEFAULT_PARALLEL_VALIDATIONS;
//
// A semaphore of this call limits the validations running at once. It is local, so that
// another chat validating at the same time does not share the limit of this one:
//
using var semaphore = new SemaphoreSlim(Math.Max(1, numParallelValidations));
var validationTasks = new List<Task<RetrievalContextValidationResult>>(request.RetrievalContexts.Count);
try
{
foreach (var retrievalContext in request.RetrievalContexts)
{
await semaphore.WaitAsync(token);
validationTasks.Add(this.ValidateAsync(request, context, lastPromptContent, retrievalContext, semaphore, token));
}
}
catch (OperationCanceledException)
{
//
// Each validation releases its slot when it ends, and the semaphore is disposed as soon
// as this method returns. The validations already running got the same token and stop
// soon; this call waits for them, so that none of them releases a disposed semaphore:
//
try
{
await Task.WhenAll(validationTasks);
}
catch (OperationCanceledException)
{
// Expected: they stop because of the same token.
}
catch (Exception exception)
{
this.Logger.LogWarning(exception, "A retrieval context validation failed while the validations were being canceled.");
}
throw;
}
return await Task.WhenAll(validationTasks);
}
#endregion
/// <summary>
/// Validates one passage and releases its slot of the semaphore afterward.
/// </summary>
private async Task<RetrievalContextValidationResult> ValidateAsync(RetrievalContextValidationRequest request, AIOperationContext context, string lastPromptContent, PreparedRetrievalContext retrievalContext, SemaphoreSlim semaphore, CancellationToken token)
{
try
{
//
// The validation may be canceled while it waits, e.g., by the user or because it took
// too long:
//
if (token.IsCancellationRequested)
return RetrievalContextValidationResult.NotAnswered(retrievalContext, "The validation was canceled.");
//
// The model reads the passage exactly as the chat model would, filtered once for both,
// so the check judges what is actually sent:
//
var systemPrompt = $"""
{JOB_DESCRIPTION}
{retrievalContext.ToMarkdown()}
""";
var userPrompt = $"""
The system prompt is:
```
{request.SystemPrompt}
```
The user prompt is:
```
{lastPromptContent}
```
""";
var answer = await this.AskAsync(request, context, systemPrompt, userPrompt, token);
if (answer is null)
{
this.Logger.LogWarning("The AI did not return a response to the validation of a retrieval context.");
return RetrievalContextValidationResult.NotAnswered(retrievalContext, "The AI did not return a response.");
}
var result = ReadAnswer(answer, retrievalContext);
if (!result.IsAnswered)
this.Logger.LogWarning($"The AI gave no usable answer to the validation of a retrieval context: {result.Reason}");
return result;
}
finally
{
semaphore.Release();
}
}
/// <summary>
/// Reads what a model answered about one retrieval context.
/// </summary>
/// <remarks>
/// We know how bad models may be at writing JSON without surrounding text, so we expect the worst and
/// extract the JSON object from the text. The answer counts only when it holds a decision and a confidence
/// between 0 and 1. Anything else is no usable answer, rather than being read as something the model did
/// not say: a missing decision would otherwise become false and drop a passage nobody judged.
/// </remarks>
/// <param name="answer">The whole answer of the model.</param>
/// <param name="retrievalContext">The retrieval context the model judged.</param>
/// <returns>The result, with IsAnswered being false when the answer is not usable.</returns>
internal static RetrievalContextValidationResult ReadAnswer(string answer, PreparedRetrievalContext retrievalContext)
{
RetrievalContextValidationAnswer judgment;
try
{
judgment = JsonSerializer.Deserialize<RetrievalContextValidationAnswer>(ModelAnswerJson.ExtractObject(answer), AIOperationsJson.OPTIONS);
}
catch (JsonException)
{
return RetrievalContextValidationResult.NotAnswered(retrievalContext, "The AI answered with an invalid or unexpected JSON format.");
}
if (judgment.Decision is not { } decision)
return RetrievalContextValidationResult.NotAnswered(retrievalContext, "The AI answered without a decision.");
if (judgment.Confidence is not { } confidence || confidence is not (>= 0f and <= 1f))
return RetrievalContextValidationResult.NotAnswered(retrievalContext, "The AI answered without a confidence between 0 and 1.");
return new(retrievalContext, true, decision, judgment.Reason ?? string.Empty, confidence);
}
}
@@ -0,0 +1,14 @@
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Tools.RAG;
namespace AIStudio.AIOperations.RetrievalContextValidation;
/// <summary>
/// The passages found for a prompt, for a model to judge whether they help with it.
/// </summary>
/// <param name="SystemPrompt">The system prompt of the chat.</param>
/// <param name="LastUserPrompt">The last prompt of the user.</param>
/// <param name="RetrievalContexts">The passages to judge, prepared for the AI and thus already filtered for prompt injections.</param>
/// <param name="RequiredConfidence">The confidence level the chat requires of every provider which reads its data.</param>
public sealed record RetrievalContextValidationRequest(string SystemPrompt, IContent LastUserPrompt, IReadOnlyList<PreparedRetrievalContext> RetrievalContexts, ConfidenceLevel RequiredConfidence);
@@ -0,0 +1,26 @@
using AIStudio.Tools.RAG;
namespace AIStudio.AIOperations.RetrievalContextValidation;
/// <summary>
/// Represents the result of a retrieval context validation.
/// </summary>
/// <remarks>
/// Decision and Confidence mean nothing unless IsAnswered is true: a validation which failed says nothing about
/// its retrieval context, neither that it helps nor that it does not.
/// </remarks>
/// <param name="RetrievalContext">The retrieval context that was validated, as it is prepared for the AI.</param>
/// <param name="IsAnswered">Whether the model gave a usable answer.</param>
/// <param name="Decision">Whether the retrieval context is useful or not.</param>
/// <param name="Reason">The reason for the decision, or why the model gave no usable answer.</param>
/// <param name="Confidence">The probability that the decision is right, between 0 and 1.</param>
public readonly record struct RetrievalContextValidationResult(PreparedRetrievalContext RetrievalContext, bool IsAnswered, bool Decision, string Reason, float Confidence) : IConfidence
{
/// <summary>
/// A validation without a usable answer, e.g., because the model gave none or its JSON was invalid.
/// </summary>
/// <param name="retrievalContext">The retrieval context that was to be validated.</param>
/// <param name="reason">Why there is no usable answer.</param>
/// <returns>The result, with IsAnswered being false.</returns>
public static RetrievalContextValidationResult NotAnswered(PreparedRetrievalContext retrievalContext, string reason) => new(retrievalContext, false, false, reason, 0f);
}
@@ -0,0 +1,65 @@
using AIStudio.Provider;
using AIStudio.Settings;
namespace AIStudio.AIOperations.TextContentCleaning;
/// <summary>
/// Keeps the main content of a web page and removes the rest, such as navigation, advertisements, and cookie banners.
/// </summary>
public sealed class TextContentCleaningOperation(ILogger<TextContentCleaningOperation> logger, SettingsManager settingsManager) : AIOperationBase<TextContentCleaningRequest, TextContentCleaningResult>(logger, settingsManager)
{
private const string JOB_DESCRIPTION =
"""
You receive a Markdown document as input. Your goal is to identify the main content of the document
and return it including Markdown formatting. Remove areas that do not belong to the main part of the
document. For a blog article, return only the text of the article with its formatting. For a scientific
paper, only the contents of the paper. Delete elements of navigation, advertisements, HTML artifacts,
cookie banners, etc. If the content contains images, these images remain. The same applies to links.
Ensure that links and images are present as valid Markdown:
- Syntax of links: [link text](URL)
- Syntax of images: ![alt text](URL)
If you find relative links or images with relative paths, correct them to absolute paths. For this
purpose, here is the source URL:
""";
/// <summary>
/// Reads the provider settings of the operation.
/// </summary>
/// <param name="settingsManager">The settings to read.</param>
/// <returns>The preferred provider and the minimum confidence, or none of them while the preselection is switched off.</returns>
public static AIOperationProviderSettings GetProviderSettings(SettingsManager settingsManager)
{
var settings = settingsManager.ConfigurationData.TextContentCleaner;
return settings.PreselectAgentOptions
? new(settings.PreselectedAgentProvider, settings.MinimumProviderConfidence)
: AIOperationProviderSettings.NONE;
}
#region Overrides of AIOperationBase
/// <inheritdoc />
public override string Id => "Text Content Cleaning";
/// <inheritdoc />
public override Tools.Components Component => Tools.Components.AGENT_TEXT_CONTENT_CLEANER;
/// <summary>
/// A web page requires nothing of its own: the user chose to read it with the assistant.
/// </summary>
public override ConfidenceLevel GetRequiredConfidence(TextContentCleaningRequest request) => ConfidenceLevel.NONE;
/// <inheritdoc />
public override async Task<TextContentCleaningResult> RunAsync(TextContentCleaningRequest request, AIOperationContext context, CancellationToken token = default)
{
var uncleaned = new TextContentCleaningResult(request.Markdown, false);
if (string.IsNullOrWhiteSpace(request.Markdown) || string.IsNullOrWhiteSpace(request.SourceUrl))
return uncleaned;
var answer = await this.AskAsync(request, context, $"{JOB_DESCRIPTION} `{request.SourceUrl}`.", request.Markdown, token);
return answer is null ? uncleaned : new TextContentCleaningResult(answer, true);
}
#endregion
}
@@ -0,0 +1,8 @@
namespace AIStudio.AIOperations.TextContentCleaning;
/// <summary>
/// A web page to clean.
/// </summary>
/// <param name="Markdown">The page as Markdown, already filtered for prompt injections.</param>
/// <param name="SourceUrl">The address of the page, for turning relative links into absolute ones.</param>
public sealed record TextContentCleaningRequest(string Markdown, string SourceUrl);
@@ -0,0 +1,8 @@
namespace AIStudio.AIOperations.TextContentCleaning;
/// <summary>
/// The text of a web page after the cleaning.
/// </summary>
/// <param name="Markdown">The cleaned page, or the page as it came when it could not be cleaned.</param>
/// <param name="IsCleaned">Whether a model cleaned the page.</param>
public sealed record TextContentCleaningResult(string Markdown, bool IsCleaned);
-141
View File
@@ -1,141 +0,0 @@
using System.Text.Json;
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Tools.Services;
// ReSharper disable MemberCanBePrivate.Global
namespace AIStudio.Agents;
public abstract class AgentBase(ILogger<AgentBase> logger, SettingsManager settingsManager, DataSourceService dataSourceService, ThreadSafeRandom rng) : IAgent
{
protected static readonly ContentBlock EMPTY_BLOCK = new()
{
Content = null,
ContentType = ContentType.NONE,
Role = ChatRole.AGENT,
Time = DateTimeOffset.UtcNow,
};
internal static readonly JsonSerializerOptions JSON_SERIALIZER_OPTIONS = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
TypeInfoResolver = AgentJsonContext.Default,
}.AsReadOnly();
protected DataSourceService DataSourceService { get; init; } = dataSourceService;
protected SettingsManager SettingsManager { get; init; } = settingsManager;
protected ThreadSafeRandom RNG { get; init; } = rng;
protected ILogger<AgentBase> Logger { get; init; } = logger;
/// <summary>
/// Represents the type or category of this agent.
/// </summary>
protected abstract Type Type { get; }
/// <summary>
/// The component this agent runs as.
/// </summary>
/// <remarks>
/// Its requests name it, e.g., in the User-Agent for self-hosted servers. Without it, an agent
/// working for an assistant would be counted as chat.
/// </remarks>
protected abstract Tools.Components Component { get; }
/// <summary>
/// The name of the agent.
/// </summary>
public abstract string Id { get; }
/// <summary>
/// The agent's job description. Will be used for the system prompt.
/// </summary>
protected abstract string JobDescription { get; }
/// <summary>
/// Represents the system prompt provided for the agent.
/// </summary>
protected abstract string SystemPrompt(string additionalData);
#region Implementation of IAgent
public abstract AIStudio.Settings.Provider ProviderSettings { get; set; }
public abstract Task<ChatThread> ProcessContext(ChatThread chatThread, IDictionary<string, string> additionalData);
public abstract Task<ContentBlock> ProcessInput(ContentBlock input, IDictionary<string, string> additionalData);
public abstract Task<bool> MadeDecision(ContentBlock input);
public abstract IReadOnlyCollection<ContentBlock> GetContext();
public abstract IReadOnlyCollection<ContentBlock> GetAnswers();
#endregion
protected ChatThread CreateChatThread(string systemPrompt) => new()
{
WorkspaceId = Guid.Empty,
ChatId = Guid.NewGuid(),
Name = string.Empty,
SystemPrompt = systemPrompt,
Blocks = [],
RuntimeComponent = this.Component,
};
protected static UserRequest AddUserRequest(ChatThread thread, string request)
{
var time = DateTimeOffset.Now;
var lastUserPrompt = new ContentText
{
Text = request,
};
thread.Blocks.Add(new ContentBlock
{
Time = time,
ContentType = ContentType.TEXT,
Role = ChatRole.USER,
Content = lastUserPrompt,
});
return new()
{
Time = time,
UserPrompt = lastUserPrompt,
};
}
protected async Task AddAIResponseAsync(ChatThread thread, IContent lastUserPrompt, DateTimeOffset time)
{
if(this.ProviderSettings == Settings.Provider.NONE)
return;
var aiText = new ContentText
{
// We have to wait for the remote
// for the content stream:
InitialRemoteWait = true,
};
var resultingContentBlock = new ContentBlock
{
Time = time,
ContentType = ContentType.TEXT,
Role = ChatRole.AI,
Content = aiText,
};
thread.Blocks.Add(resultingContentBlock);
// Use the selected provider to get the AI response.
// By awaiting this line, we wait for the entire
// content to be streamed.
await aiText.CreateFromProviderAsync(this.ProviderSettings.CreateProvider(), this.ProviderSettings.Model, lastUserPrompt, thread);
}
}
@@ -1,296 +0,0 @@
using System.Text;
using System.Text.Json;
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
using AIStudio.Tools.Services;
namespace AIStudio.Agents;
public sealed class AgentDataSourceSelection (ILogger<AgentDataSourceSelection> logger, ILogger<AgentBase> baseLogger, SettingsManager settingsManager, DataSourceService dataSourceService, DataSourceDescriptionService descriptionService, ThreadSafeRandom rng) : AgentBase(baseLogger, settingsManager, dataSourceService, rng)
{
private readonly List<ContentBlock> answers = new();
#region Overrides of AgentBase
/// <inheritdoc />
protected override Type Type => Type.SYSTEM;
/// <inheritdoc />
protected override Tools.Components Component => Tools.Components.AGENT_DATA_SOURCE_SELECTION;
/// <inheritdoc />
public override string Id => "Data Source Selection";
/// <inheritdoc />
protected override string JobDescription =>
"""
You receive a system and a user prompt, as well as a list of possible data sources as input.
Your task is to select the appropriate data sources for the given task. You may choose none,
one, or multiple sources, depending on what best fits the system and user prompt. You need
to estimate and assess which source, based on its description, might be helpful in
processing the prompts.
Your response is a JSON list in the following format:
```
[
{"id": "The data source ID", "reason": "Why did you choose this source?", "confidence": 0.87},
{"id": "The data source ID", "reason": "Why did you choose this source?", "confidence": 0.54}
]
```
You express your confidence as a floating-point number between 0.0 (maximum uncertainty) and
1.0 (you are absolutely certain that this source is needed).
The JSON schema is:
```
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array",
"items": [
{
"type": "object",
"properties": {
"id": {
"type": "string"
},
"reason": {
"type": "string"
},
"confidence": {
"type": "number"
}
},
"required": [
"id",
"reason",
"confidence"
]
}
]
}
```
When no data source is needed, you return an empty JSON list `[]`. You do not ask any
follow-up questions. You do not address the user. Your response consists solely of
the JSON list.
""";
/// <inheritdoc />
protected override string SystemPrompt(string availableDataSources) => $"""
{this.JobDescription}
{availableDataSources}
""";
/// <inheritdoc />
public override Settings.Provider ProviderSettings { get; set; } = Settings.Provider.NONE;
/// <summary>
/// The data source selection agent does not work with context. Use
/// the process input method instead.
/// </summary>
/// <returns>The chat thread without any changes.</returns>
public override Task<ChatThread> ProcessContext(ChatThread chatThread, IDictionary<string, string> additionalData) => Task.FromResult(chatThread);
/// <inheritdoc />
public override async Task<ContentBlock> ProcessInput(ContentBlock input, IDictionary<string, string> additionalData)
{
if (input.Content is not ContentText text)
return EMPTY_BLOCK;
if(text.InitialRemoteWait || text.IsStreaming)
return EMPTY_BLOCK;
if(string.IsNullOrWhiteSpace(text.Text))
return EMPTY_BLOCK;
if(!additionalData.TryGetValue("availableDataSources", out var availableDataSources) || string.IsNullOrWhiteSpace(availableDataSources))
return EMPTY_BLOCK;
var thread = this.CreateChatThread(this.SystemPrompt(availableDataSources));
var userRequest = AddUserRequest(thread, text.Text);
await this.AddAIResponseAsync(thread, userRequest.UserPrompt, userRequest.Time);
var answer = thread.Blocks[^1];
this.answers.Add(answer);
return answer;
}
// <inheritdoc />
public override Task<bool> MadeDecision(ContentBlock input) => Task.FromResult(true);
// <inheritdoc />
public override IReadOnlyCollection<ContentBlock> GetContext() => [];
// <inheritdoc />
public override IReadOnlyCollection<ContentBlock> GetAnswers() => this.answers;
#endregion
public async Task<List<SelectedDataSource>> PerformSelectionAsync(IProvider provider, IContent lastUserPrompt, ChatThread chatThread, AllowedSelectedDataSources dataSources, CancellationToken token = default)
{
logger.LogInformation("The AI should select the appropriate data sources.");
//
// 1. Which LLM provider should the agent use?
//
// We start with the provider currently selected by the user:
var requiredDataSecurity = dataSources.AllowedDataSources.GetRequiredSecurityPolicy();
var requiredConfidenceLevel = dataSources.AllowedDataSources.GetRequiredConfidenceLevel();
var agentProvider = this.SettingsManager.GetPreselectedProvider(Tools.Components.AGENT_DATA_SOURCE_SELECTION, provider.ConfiguredProviderId, true);
if (agentProvider == Settings.Provider.NONE)
{
logger.LogWarning("No provider is selected for the agent. The agent cannot select data sources.");
return [];
}
if (!agentProvider.AllowsDataSourceAccess(this.SettingsManager, requiredDataSecurity, requiredConfidenceLevel))
{
logger.LogWarning($"The agent for data source selection uses provider '{agentProvider.InstanceName}' with confidence '{agentProvider.GetConfidenceLevel(this.SettingsManager).Name}', but the available data sources require data security '{requiredDataSecurity}' and provider confidence '{requiredConfidenceLevel.Name}'. The agent cannot select data sources.");
return [];
}
// Assign the provider settings to the agent:
logger.LogInformation($"The agent for the data source selection uses the provider '{agentProvider.InstanceName}' ({agentProvider.UsedLLMProvider.Name}, confidence={agentProvider.UsedLLMProvider.GetConfidence(this.SettingsManager).Level.Name}).");
this.ProviderSettings = agentProvider;
//
// 2. Prepare the current system and user prompts as input for the agent:
//
var lastPromptContent = lastUserPrompt switch
{
ContentText text => text.Text,
// Image prompts may be empty, e.g., when the image is too large:
ContentImage image => await image.TryAsBase64(token) is (success: true, { } base64Image)
? base64Image
: string.Empty,
// Other content types are not supported yet:
_ => string.Empty,
};
if (string.IsNullOrWhiteSpace(lastPromptContent))
{
logger.LogWarning("The last prompt is empty. The AI cannot select data sources.");
return [];
}
//
// 3. Prepare the allowed data sources as input for the agent:
//
var additionalData = new Dictionary<string, string>();
logger.LogInformation("Preparing the list of allowed data sources for the agent to choose from.");
var sb = new StringBuilder();
sb.AppendLine("The following data sources are available for selection:");
foreach (var ds in dataSources.AllowedDataSources)
{
var description = await descriptionService.GetDescriptionAsync(ds, token);
var descriptionPart = string.IsNullOrWhiteSpace(description) ? string.Empty : $", description='{description}'";
switch (ds)
{
case DataSourceLocalDirectory localDirectory:
sb.AppendLine($"- Id={ds.Id}, name='{localDirectory.Name}', type=local directory, path='{localDirectory.Path}'{descriptionPart}");
break;
case DataSourceLocalFile localFile:
sb.AppendLine($"- Id={ds.Id}, name='{localFile.Name}', type=local file, path='{localFile.FilePath}'{descriptionPart}");
break;
case IERIDataSource eriDataSource:
sb.AppendLine($"- Id={ds.Id}, name='{eriDataSource.Name}', type=external data source{descriptionPart}");
break;
}
}
logger.LogInformation("Prepared the list of allowed data sources for the agent.");
additionalData.Add("availableDataSources", sb.ToString());
//
// 4. Let the agent select the data sources:
//
var prompt = $"""
The system prompt is:
```
{chatThread.SystemPrompt}
```
The user prompt is:
```
{lastPromptContent}
```
""";
// Call the agent:
var aiResponse = await this.ProcessInput(new ContentBlock
{
Time = DateTimeOffset.UtcNow,
ContentType = ContentType.TEXT,
Role = ChatRole.USER,
Content = new ContentText
{
Text = prompt,
},
}, additionalData);
if(aiResponse.Content is null)
{
logger.LogWarning("The agent did not return a response.");
return [];
}
switch (aiResponse)
{
//
// 5. Parse the agent response:
//
case { ContentType: ContentType.TEXT, Content: ContentText textContent }:
{
//
// What we expect is a JSON list of SelectedDataSource objects:
//
var selectedDataSourcesJson = textContent.Text;
//
// We know how bad LLM may be in generating JSON without surrounding text.
// Thus, we expect the worst and try to extract the JSON list from the text:
//
var json = ModelAnswerJson.ExtractObjectList(selectedDataSourcesJson);
try
{
var aiSelectedDataSources = JsonSerializer.Deserialize<List<SelectedDataSource>>(json, JSON_SERIALIZER_OPTIONS);
return aiSelectedDataSources ?? [];
}
catch
{
logger.LogWarning("The agent answered with an invalid or unexpected JSON format.");
return [];
}
}
case { ContentType: ContentType.TEXT }:
logger.LogWarning("The agent answered with an unexpected inner content type.");
return [];
case { ContentType: ContentType.NONE }:
logger.LogWarning("The agent did not return a response.");
return [];
default:
logger.LogWarning($"The agent answered with an unexpected content type '{aiResponse.ContentType}'.");
return [];
}
}
}
@@ -1,14 +0,0 @@
using System.Text.Json.Serialization;
using AIStudio.Agents.AssistantAudit;
namespace AIStudio.Agents;
/// <summary>
/// The contracts with which System.Text.Json reads the answers of the agents, built at compile time.
/// </summary>
[JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(List<SelectedDataSource>))]
[JsonSerializable(typeof(RetrievalContextValidationResult))]
[JsonSerializable(typeof(AssistantAuditResult))]
internal sealed partial class AgentJsonContext : JsonSerializerContext;
@@ -1,343 +0,0 @@
using System.Text.Json;
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
using AIStudio.Tools.RAG;
using AIStudio.Tools.Services;
namespace AIStudio.Agents;
public sealed class AgentRetrievalContextValidation (ILogger<AgentRetrievalContextValidation> logger, ILogger<AgentBase> baseLogger, SettingsManager settingsManager, DataSourceService dataSourceService, ThreadSafeRandom rng) : AgentBase(baseLogger, settingsManager, dataSourceService, rng)
{
#region Overrides of AgentBase
/// <inheritdoc />
protected override Type Type => Type.WORKER;
/// <inheritdoc />
protected override Tools.Components Component => Tools.Components.AGENT_RETRIEVAL_CONTEXT_VALIDATION;
/// <inheritdoc />
public override string Id => "Retrieval Context Validation";
/// <inheritdoc />
protected override string JobDescription =>
"""
You receive a system and user prompt as well as a retrieval context as input. Your task is to decide whether this
retrieval context is helpful in processing the prompts or not. You respond with the decision (true or false),
your reasoning, and your confidence in this decision.
Your response is only one JSON object in the following format:
```
{"decision": true, "reason": "Why did you choose this source?", "confidence": 0.87}
```
You express your confidence as a floating-point number between 0.0 (maximum uncertainty) and
1.0 (you are absolutely certain that this retrieval context is needed).
The JSON schema is:
```
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"decision": {
"type": "boolean"
},
"reason": {
"type": "string"
},
"confidence": {
"type": "number"
}
},
"required": [
"decision",
"reason",
"confidence"
]
}
```
You do not ask any follow-up questions. You do not address the user. Your response consists solely of
that one JSON object.
""";
/// <inheritdoc />
protected override string SystemPrompt(string retrievalContext) => $"""
{this.JobDescription}
{retrievalContext}
""";
/// <inheritdoc />
public override Settings.Provider ProviderSettings { get; set; } = Settings.Provider.NONE;
/// <summary>
/// The retrieval context validation agent does not work with context. Use
/// the process input method instead.
/// </summary>
/// <returns>The chat thread without any changes.</returns>
public override Task<ChatThread> ProcessContext(ChatThread chatThread, IDictionary<string, string> additionalData) => Task.FromResult(chatThread);
/// <inheritdoc />
public override async Task<ContentBlock> ProcessInput(ContentBlock input, IDictionary<string, string> additionalData)
{
if (input.Content is not ContentText text)
return EMPTY_BLOCK;
if(text.InitialRemoteWait || text.IsStreaming)
return EMPTY_BLOCK;
if(string.IsNullOrWhiteSpace(text.Text))
return EMPTY_BLOCK;
if(!additionalData.TryGetValue("retrievalContext", out var retrievalContext) || string.IsNullOrWhiteSpace(retrievalContext))
return EMPTY_BLOCK;
var thread = this.CreateChatThread(this.SystemPrompt(retrievalContext));
var userRequest = AddUserRequest(thread, text.Text);
await this.AddAIResponseAsync(thread, userRequest.UserPrompt, userRequest.Time);
return thread.Blocks[^1];
}
/// <inheritdoc />
public override Task<bool> MadeDecision(ContentBlock input) => Task.FromResult(true);
/// <summary>
/// We do not provide any context. This agent will process many retrieval contexts.
/// This would block a huge amount of memory.
/// </summary>
/// <returns>An empty list.</returns>
public override IReadOnlyCollection<ContentBlock> GetContext() => [];
/// <summary>
/// We do not provide any answers. This agent will process many retrieval contexts.
/// This would block a huge amount of memory.
/// </summary>
/// <returns>An empty list.</returns>
public override IReadOnlyCollection<ContentBlock> GetAnswers() => [];
#endregion
/// <summary>
/// Sets the LLM provider for the agent.
/// </summary>
/// <remarks>
/// When you have to call the validation in parallel for many retrieval contexts,
/// you can set the provider once and then call the validation method in parallel.
/// </remarks>
/// <param name="provider">The current LLM provider. When the user doesn't preselect an agent provider, the agent uses this provider.</param>
/// <param name="requiredDataSecurity">The data security required by the retrieved data.</param>
/// <param name="requiredConfidenceLevel">The minimum provider confidence required by the retrieved data.</param>
public bool SetLLMProvider(IProvider provider, DataSourceSecurity requiredDataSecurity = DataSourceSecurity.NOT_SPECIFIED, ConfidenceLevel requiredConfidenceLevel = ConfidenceLevel.NONE)
{
// We start with the provider currently selected by the user:
var agentProvider = this.SettingsManager.GetPreselectedProvider(Tools.Components.AGENT_RETRIEVAL_CONTEXT_VALIDATION, provider.ConfiguredProviderId, true);
if (agentProvider == Settings.Provider.NONE)
{
logger.LogWarning("No provider is selected for the agent.");
this.ProviderSettings = Settings.Provider.NONE;
return false;
}
if (!agentProvider.AllowsDataSourceAccess(this.SettingsManager, requiredDataSecurity, requiredConfidenceLevel))
{
logger.LogWarning($"The agent for retrieval context validation uses provider '{agentProvider.InstanceName}' with confidence '{agentProvider.GetConfidenceLevel(this.SettingsManager).Name}', but the retrieved data requires data security '{requiredDataSecurity}' and provider confidence '{requiredConfidenceLevel.Name}'. The agent cannot validate retrieval contexts.");
this.ProviderSettings = Settings.Provider.NONE;
return false;
}
// Assign the provider settings to the agent:
logger.LogInformation($"The agent for the retrieval context validation uses the provider '{agentProvider.InstanceName}' ({agentProvider.UsedLLMProvider.Name}, confidence={agentProvider.UsedLLMProvider.GetConfidence(this.SettingsManager).Level.Name}).");
this.ProviderSettings = agentProvider;
return true;
}
/// <summary>
/// Validate all retrieval contexts against the last user and the system prompt.
/// </summary>
/// <param name="lastUserPrompt">The last user prompt.</param>
/// <param name="chatThread">The chat thread.</param>
/// <param name="retrievalContexts">All retrieval contexts to validate, prepared for the AI and thus already filtered for prompt injections.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The validation results.</returns>
public async Task<IReadOnlyList<RetrievalContextValidationResult>> ValidateRetrievalContextsAsync(IContent lastUserPrompt, ChatThread chatThread, IReadOnlyList<PreparedRetrievalContext> retrievalContexts, CancellationToken token = default)
{
// Check if the retrieval context validation is enabled:
if (!this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.EnableRetrievalContextValidation)
return [];
logger.LogInformation($"Validating {retrievalContexts.Count:###,###,###,###} retrieval contexts.");
// Prepare the list of validation tasks:
var validationTasks = new List<Task<RetrievalContextValidationResult>>(retrievalContexts.Count);
// Read the number of parallel validations:
var numParallelValidations = 3;
if(this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectAgentOptions)
numParallelValidations = this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation.NumParallelValidations;
numParallelValidations = Math.Max(1, numParallelValidations);
// Use a semaphore to limit the number of parallel validations:
using var semaphore = new SemaphoreSlim(numParallelValidations);
foreach (var retrievalContext in retrievalContexts)
{
// Wait for an available slot in the semaphore:
await semaphore.WaitAsync(token);
// Start the next validation task:
validationTasks.Add(this.ValidateRetrievalContextAsync(lastUserPrompt, chatThread, retrievalContext, semaphore, token));
}
// Wait for all validation tasks to complete:
return await Task.WhenAll(validationTasks);
}
/// <summary>
/// Validates the retrieval context against the last user and the system prompt.
/// </summary>
/// <remarks>
/// Probably, you have a lot of retrieval contexts to validate. In this case, you
/// can call this method in parallel for each retrieval context. You might use
/// the ValidateRetrievalContextsAsync method to validate all retrieval contexts.
/// </remarks>
/// <param name="lastUserPrompt">The last user prompt.</param>
/// <param name="chatThread">The chat thread.</param>
/// <param name="retrievalContext">The retrieval context to validate, prepared for the AI and thus already filtered for prompt injections.</param>
/// <param name="semaphore">The optional semaphore to limit the number of parallel validations.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The validation result.</returns>
public async Task<RetrievalContextValidationResult> ValidateRetrievalContextAsync(IContent lastUserPrompt, ChatThread chatThread, PreparedRetrievalContext retrievalContext, SemaphoreSlim? semaphore = null, CancellationToken token = default)
{
try
{
//
// Check if the validation was canceled. This could happen when the user
// canceled the validation process or when the validation process took
// too long:
//
if(token.IsCancellationRequested)
return new(false, "The validation was canceled.", 1.0f, retrievalContext);
//
// 1. Prepare the current system and user prompts as input for the agent:
//
var lastPromptContent = lastUserPrompt switch
{
ContentText text => text.Text,
// Image prompts may be empty, e.g., when the image is too large:
ContentImage image => await image.TryAsBase64(token) is (success: true, { } base64Image)
? base64Image
: string.Empty,
// Other content types are not supported yet:
_ => string.Empty,
};
if (string.IsNullOrWhiteSpace(lastPromptContent))
{
logger.LogWarning("The last prompt is empty. The AI cannot validate the retrieval context.");
return new(false, "The last prompt was empty.", 1.0f, retrievalContext);
}
//
// 2. Prepare the retrieval context for the agent. It reads the context exactly as the
// AI would, filtered once for both, so the check judges what is actually sent:
//
var additionalData = new Dictionary<string, string>();
additionalData.Add("retrievalContext", retrievalContext.ToMarkdown());
//
// 3. Let the agent validate the retrieval context:
//
var prompt = $"""
The system prompt is:
```
{chatThread.SystemPrompt}
```
The user prompt is:
```
{lastPromptContent}
```
""";
// Call the agent:
var aiResponse = await this.ProcessInput(new ContentBlock
{
Time = DateTimeOffset.UtcNow,
ContentType = ContentType.TEXT,
Role = ChatRole.USER,
Content = new ContentText
{
Text = prompt,
},
}, additionalData);
if (aiResponse.Content is null)
{
logger.LogWarning("The agent did not return a response.");
return new(false, "The agent did not return a response.", 1.0f, retrievalContext);
}
switch (aiResponse)
{
//
// 4. Parse the agent response:
//
case { ContentType: ContentType.TEXT, Content: ContentText textContent }:
{
//
// What we expect is one JSON object:
//
var validationJson = textContent.Text;
//
// We know how bad LLM may be in generating JSON without surrounding text.
// Thus, we expect the worst and try to extract the JSON object from the text:
//
var json = ModelAnswerJson.ExtractObject(validationJson);
try
{
var result = JsonSerializer.Deserialize<RetrievalContextValidationResult>(json, JSON_SERIALIZER_OPTIONS);
return result with { RetrievalContext = retrievalContext };
}
catch
{
logger.LogWarning("The agent answered with an invalid or unexpected JSON format.");
return new(false, "The agent answered with an invalid or unexpected JSON format.", 1.0f, retrievalContext);
}
}
case { ContentType: ContentType.TEXT }:
logger.LogWarning("The agent answered with an unexpected inner content type.");
return new(false, "The agent answered with an unexpected inner content type.", 1.0f, retrievalContext);
case { ContentType: ContentType.NONE }:
logger.LogWarning("The agent did not return a response.");
return new(false, "The agent did not return a response.", 1.0f, retrievalContext);
default:
logger.LogWarning($"The agent answered with an unexpected content type '{aiResponse.ContentType}'.");
return new(false, $"The agent answered with an unexpected content type '{aiResponse.ContentType}'.", 1.0f, retrievalContext);
}
}
finally
{
// Release the semaphore slot:
semaphore?.Release();
}
}
}
@@ -1,88 +0,0 @@
using AIStudio.Chat;
using AIStudio.Settings;
using AIStudio.Tools.Services;
namespace AIStudio.Agents;
public sealed class AgentTextContentCleaner(ILogger<AgentBase> logger, SettingsManager settingsManager, DataSourceService dataSourceService, ThreadSafeRandom rng) : AgentBase(logger, settingsManager, dataSourceService, rng)
{
private readonly List<ContentBlock> context = new();
private readonly List<ContentBlock> answers = new();
#region Overrides of AgentBase
public override AIStudio.Settings.Provider ProviderSettings { get; set; } = AIStudio.Settings.Provider.NONE;
protected override Type Type => Type.SYSTEM;
protected override Tools.Components Component => Tools.Components.AGENT_TEXT_CONTENT_CLEANER;
public override string Id => "Text Content Cleaner";
protected override string JobDescription =>
"""
You receive a Markdown document as input. Your goal is to identify the main content of the document
and return it including Markdown formatting. Remove areas that do not belong to the main part of the
document. For a blog article, return only the text of the article with its formatting. For a scientific
paper, only the contents of the paper. Delete elements of navigation, advertisements, HTML artifacts,
cookie banners, etc. If the content contains images, these images remain. The same applies to links.
Ensure that links and images are present as valid Markdown:
- Syntax of links: [link text](URL)
- Syntax of images: ![alt text](URL)
If you find relative links or images with relative paths, correct them to absolute paths. For this
purpose, here is the source URL:
""";
protected override string SystemPrompt(string additionalData) => $"{this.JobDescription} `{additionalData}`.";
/// <inheritdoc />
public override async Task<ChatThread> ProcessContext(ChatThread chatThread, IDictionary<string, string> additionalData)
{
// We process the last block of the chat thread. Then, we add the result
// to the chat thread as the last block:
var answer = await this.ProcessInput(chatThread.Blocks[^1], additionalData);
chatThread.Blocks.Add(answer);
this.context.Clear();
this.context.AddRange(chatThread.Blocks);
return chatThread;
}
// <inheritdoc />
public override async Task<ContentBlock> ProcessInput(ContentBlock input, IDictionary<string, string> additionalData)
{
if (input.Content is not ContentText text)
return EMPTY_BLOCK;
if(text.InitialRemoteWait || text.IsStreaming)
return EMPTY_BLOCK;
if(string.IsNullOrWhiteSpace(text.Text))
return EMPTY_BLOCK;
if(!additionalData.TryGetValue("sourceURL", out var sourceURL) || string.IsNullOrWhiteSpace(sourceURL))
return EMPTY_BLOCK;
var thread = this.CreateChatThread(this.SystemPrompt(sourceURL));
var userRequest = AddUserRequest(thread, text.Text);
await this.AddAIResponseAsync(thread, userRequest.UserPrompt, userRequest.Time);
var answer = thread.Blocks[^1];
this.answers.Add(answer);
return answer;
}
// <inheritdoc />
public override Task<bool> MadeDecision(ContentBlock input) => Task.FromResult(true);
// <inheritdoc />
public override IReadOnlyCollection<ContentBlock> GetContext() => this.context;
// <inheritdoc />
public override IReadOnlyCollection<ContentBlock> GetAnswers() => this.answers;
#endregion
}
@@ -1,50 +0,0 @@
using AIStudio.Tools.PluginSystem;
namespace AIStudio.Agents.AssistantAudit;
public static class AssistantAuditLevelExtensions
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(AssistantAuditLevelExtensions).Namespace, nameof(AssistantAuditLevelExtensions));
extension(AssistantAuditLevel level)
{
public string Name => level switch
{
AssistantAuditLevel.DANGEROUS => TB("Dangerous"),
AssistantAuditLevel.CAUTION => TB("Concerning"),
AssistantAuditLevel.SAFE => TB("Safe"),
_ => TB("Unknown"),
};
public Severity Severity => level switch
{
AssistantAuditLevel.DANGEROUS => Severity.Error,
AssistantAuditLevel.CAUTION => Severity.Warning,
AssistantAuditLevel.SAFE => Severity.Success,
_ => Severity.Info,
};
public Color Color => level switch
{
AssistantAuditLevel.DANGEROUS => Color.Error,
AssistantAuditLevel.CAUTION => Color.Warning,
AssistantAuditLevel.SAFE => Color.Success,
_ => Color.Default,
};
public string Icon => level switch
{
AssistantAuditLevel.DANGEROUS => Icons.Material.Filled.Dangerous,
AssistantAuditLevel.CAUTION => Icons.Material.Filled.Warning,
AssistantAuditLevel.SAFE => Icons.Material.Filled.Verified,
_ => Icons.Material.Filled.HelpOutline,
};
/// <summary>
/// Parses an audit level string and falls back to <see cref="AssistantAuditLevel.UNKNOWN"/> when parsing fails.
/// </summary>
/// <param name="value">The audit level text to parse.</param>
/// <returns>The parsed audit level, or <see cref="AssistantAuditLevel.UNKNOWN"/> for null, empty, or invalid values.</returns>
public static AssistantAuditLevel ParseOrUnknown(string? value) => Enum.TryParse<AssistantAuditLevel>(value, true, out var parsedLevel) ? parsedLevel : AssistantAuditLevel.UNKNOWN;
}
}
-55
View File
@@ -1,55 +0,0 @@
using AIStudio.Chat;
namespace AIStudio.Agents;
public interface IAgent
{
/// <summary>
/// Gets the name of the agent.
/// </summary>
public string Id { get; }
/// <summary>
/// The provider to use for this agent.
/// </summary>
public Settings.Provider ProviderSettings { get; set; }
/// <summary>
/// Processes a chat thread (i.e., context) and returns the updated thread.
/// </summary>
/// <param name="chatThread">The chat thread to process. The thread is the context for the agent.</param>
/// <param name="additionalData">Additional data to use for processing the chat thread.</param>
/// <returns>The updated chat thread. The last content block of the thread is the agent's response.</returns>
public Task<ChatThread> ProcessContext(ChatThread chatThread, IDictionary<string, string> additionalData);
/// <summary>
/// Processes the input content block and returns the agent's response.
/// </summary>
/// <param name="input">The content block to process. It represents the input.</param>
/// <param name="additionalData">Additional data to use for processing the input.</param>
/// <returns>The content block representing the agent's response.</returns>
public Task<ContentBlock> ProcessInput(ContentBlock input, IDictionary<string, string> additionalData);
/// <summary>
/// The agent makes a decision based on the input.
/// </summary>
/// <param name="input">The content block to process. Should be a question or a request.</param>
/// <returns>
/// True if a decision has been made based on the input, false otherwise.
/// </returns>
public Task<bool> MadeDecision(ContentBlock input);
/// <summary>
/// Retrieves the context of the agent.
/// </summary>
/// <returns>The collection of content blocks representing the agent's context. This includes the user's and the other agent's messages.</returns>
public IReadOnlyCollection<ContentBlock> GetContext();
/// <summary>
/// Retrieves the answers from the agent's context.
/// </summary>
/// <returns>
/// The collection of content blocks representing the answers provided by this agent.
/// </returns>
public IReadOnlyCollection<ContentBlock> GetAnswers();
}
@@ -1,12 +0,0 @@
using AIStudio.Tools.RAG;
namespace AIStudio.Agents;
/// <summary>
/// Represents the result of a retrieval context validation.
/// </summary>
/// <param name="Decision">Whether the retrieval context is useful or not.</param>
/// <param name="Reason">The reason for the decision.</param>
/// <param name="Confidence">The confidence of the decision.</param>
/// <param name="RetrievalContext">The retrieval context that was validated, as it is prepared for the AI.</param>
public readonly record struct RetrievalContextValidationResult(bool Decision, string Reason, float Confidence, PreparedRetrievalContext? RetrievalContext) : IConfidence;
-27
View File
@@ -1,27 +0,0 @@
namespace AIStudio.Agents;
public enum Type
{
/// <summary>
/// Represents an unspecified agent type.
/// </summary>
UNSPECIFIED = 0,
/// <summary>
/// Represents a conversational agent who produces human-like responses and feedback (depending on the context and its job description).
/// For example, an expert agent for a specific domain. Answers might be detailed and informative.
/// </summary>
CONVERSATIONAL,
/// <summary>
/// Represents a worker agent type who performs tasks and provides information or services (depending on the context and its job description).
/// For example, a quality assurance agent who assesses the quality of a product or service. Answers might be short and concise.
/// </summary>
WORKER,
/// <summary>
/// Represents the system agent type who processes the input and provides a specific response (depending on the context and its job description).
/// For example, a HTML content agent who processes the arbitrary HTML content and provides a structured Markdown response. Answers might be structured and formatted.
/// </summary>
SYSTEM,
}
@@ -1,19 +0,0 @@
using AIStudio.Chat;
namespace AIStudio.Agents;
/// <summary>
/// The created user request.
/// </summary>
public sealed class UserRequest
{
/// <summary>
/// The time when the request was created.
/// </summary>
public required DateTimeOffset Time { get; init; }
/// <summary>
/// The user prompt.
/// </summary>
public required IContent UserPrompt { get; init; }
}
@@ -1,11 +1,11 @@
@attribute [Route(Routes.ASSISTANT_AGENDA)]
@inherits AssistantBaseCore<AIStudio.Dialogs.Settings.SettingsDialogAgenda>
<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-Value="@this.inputName" Validation="@this.ValidateName" DebounceInterval="@TextFieldDefaults.VALIDATION_DEBOUNCE_MILLISECONDS" Label="@T("Meeting Name")" Adornment="Adornment.Start" AdornmentIcon="@AppIcons.NAME" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@TA("Name the meeting, seminar, etc.")" Placeholder="@T("Weekly jour fixe")" Class="mb-3"/>
<MudTextField T="string" @bind-Value="@this.inputTopic" Validation="@this.ValidateTopic" DebounceInterval="@TextFieldDefaults.VALIDATION_DEBOUNCE_MILLISECONDS" Label="@T("Topic")" Adornment="Adornment.Start" AdornmentIcon="@AppIcons.MEETING_TOPIC" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@TA("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"/>
<ReadFileContent Text="@T("Load the content list from file")" FileContent="@this.inputContent" FileContentChanged="@this.ContentLoadedFromFile" EnableDragDrop="true"/>
<DebouncedTextField @bind-Text="@this.inputContent" ValidationFunc="@this.ValidateContent" DebounceTime="TimeSpan.FromSeconds(1)" Label="@T("Content list")" Lines="6" Attributes="@USER_INPUT_ATTRIBUTES" HelpText="@T("Bullet list the content of the meeting, seminar, etc. roughly. Use dashes (-) to separate the items.")" Placeholder="@PLACEHOLDER_CONTENT" WhenTextCanged="@this.OnContentChanged" Icon="@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">
<DebouncedTextField @bind-Text="@this.inputContent" ValidationFunc="@this.ValidateContent" DebounceTime="TimeSpan.FromSeconds(1)" Label="@T("Content list")" Lines="6" Attributes="@USER_INPUT_ATTRIBUTES" HelpText="@TA("Bullet list the content of the meeting, seminar, etc. roughly. Use dashes (-) to separate the items.")" Placeholder="@PLACEHOLDER_CONTENT" WhenTextCanged="@this.OnContentChanged" Icon="@AppIcons.LIST"/>
<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="@AppIcons.LIST">
@foreach (var contentLine in this.contentLines)
{
@if(!this.justBriefly.Contains(contentLine))
@@ -17,7 +17,7 @@
}
</MudSelect>
<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">
<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="@AppIcons.LIST">
@foreach (var contentLine in this.contentLines)
{
@if(!this.selectedFoci.Contains(contentLine))
@@ -29,19 +29,19 @@
}
</MudSelect>
<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"/>
<MudTextField T="string" @bind-Value="@this.inputObjective" Validation="@this.ValidateObjective" DebounceInterval="@TextFieldDefaults.VALIDATION_DEBOUNCE_MILLISECONDS" Label="@T("Objective")" Adornment="Adornment.Start" AdornmentIcon="@AppIcons.OBJECTIVE" Variant="Variant.Outlined" Lines="3" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@TA("Describe the objective(s) of the meeting, seminar, etc. What should be achieved?")" Placeholder="@TA("Discuss the current project status and plan the next steps.")" Class="mb-3"/>
<MudTextField T="string" @bind-Value="@this.inputModerator" Validation="@this.ValidateModerator" DebounceInterval="@TextFieldDefaults.VALIDATION_DEBOUNCE_MILLISECONDS" Label="@T("Moderator")" Adornment="Adornment.Start" AdornmentIcon="@AppIcons.MODERATOR" 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-Value="@this.inputDuration" Validation="@this.ValidateDuration" DebounceInterval="@TextFieldDefaults.VALIDATION_DEBOUNCE_MILLISECONDS" Label="@T("Duration")" Adornment="Adornment.Start" AdornmentIcon="@AppIcons.TIME" 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-Value="@this.inputStartTime" Validation="@this.ValidateStartTime" DebounceInterval="@TextFieldDefaults.VALIDATION_DEBOUNCE_MILLISECONDS" Label="@T("Start time")" Adornment="Adornment.Start" AdornmentIcon="@AppIcons.TIME" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES" HelperText="@TA("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="@TA("(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"/>
<EnumSelection T="NumberParticipants" @bind-Value="@this.numberParticipants" NameFunc="@(participants => participants.Name)" Icon="@AppIcons.PARTICIPANTS" 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="@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"/>
<MudTextField T="string" @bind-Value="@this.inputLocation" Validation="@this.ValidateLocation" DebounceInterval="@TextFieldDefaults.VALIDATION_DEBOUNCE_MILLISECONDS" Label="@T("Location")" Adornment="Adornment.Start" AdornmentIcon="@AppIcons.LOCATION" 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")" />
@@ -52,5 +52,5 @@
</MudPaper>
}
<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")" />
<EnumSelection T="CommonLanguages" NameFunc="@(language => language.NameSelecting)" @bind-Value="@this.selectedTargetLanguage" ValidateSelection="@this.ValidateTargetLanguage" Icon="@AppIcons.LANGUAGE" 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"/>
@@ -12,7 +12,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
protected override string Title => T("Agenda Planner");
protected override string Description => 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 Description => TA("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.");
// The prompt of this assistant demands the agenda in a fixed format, so the chat gets a prompt of its own, which keeps the knowledge and the language:
protected override ChatSystemPromptChoice ChatSystemPrompt => ChatSystemPromptChoice.Custom(this.CreateChatSystemPrompt);
@@ -352,7 +352,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateLocation(string location)
{
if(!this.isMeetingVirtual && string.IsNullOrWhiteSpace(location))
return T("Please provide a location for the meeting or the seminar.");
return TA("Please provide a location for the meeting or the seminar.");
return null;
}
@@ -360,7 +360,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateNumberParticipants(NumberParticipants selectedSize)
{
if(selectedSize is NumberParticipants.NOT_SPECIFIED)
return T("Please select the number of participants.");
return TA("Please select the number of participants.");
return null;
}
@@ -368,7 +368,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateTargetLanguage(CommonLanguages language)
{
if(language is CommonLanguages.AS_IS)
return T("Please select a target language for the agenda.");
return TA("Please select a target language for the agenda.");
return null;
}
@@ -376,7 +376,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateDuration(string duration)
{
if(string.IsNullOrWhiteSpace(duration))
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 TA("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;
}
@@ -384,7 +384,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateStartTime(string startTime)
{
if(string.IsNullOrWhiteSpace(startTime))
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 TA("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;
}
@@ -392,7 +392,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateCustomLanguage(string language)
{
if(this.selectedTargetLanguage == CommonLanguages.OTHER && string.IsNullOrWhiteSpace(language))
return T("Please provide a custom language.");
return TA("Please provide a custom language.");
return null;
}
@@ -400,7 +400,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateTopic(string topic)
{
if(string.IsNullOrWhiteSpace(topic))
return T("Please provide a topic for the agenda. What is the meeting or the seminar about?");
return TA("Please provide a topic for the agenda. What is the meeting or the seminar about?");
return null;
}
@@ -408,7 +408,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateName(string name)
{
if(string.IsNullOrWhiteSpace(name))
return T("Please provide a name for the meeting or the seminar.");
return TA("Please provide a name for the meeting or the seminar.");
return null;
}
@@ -416,12 +416,12 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateContent(string content)
{
if(string.IsNullOrWhiteSpace(content))
return T("Please provide some content for the agenda. What are the main points of the meeting or the seminar?");
return TA("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 T("Please start each line of your content list with a dash (-) to create a bullet point list.");
return TA("Please start each line of your content list with a dash (-) to create a bullet point list.");
return null;
}
@@ -429,7 +429,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateObjective(string objective)
{
if(string.IsNullOrWhiteSpace(objective))
return T("Please provide an objective for the meeting or the seminar. What do you want to achieve?");
return TA("Please provide an objective for the meeting or the seminar. What do you want to achieve?");
return null;
}
@@ -437,7 +437,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
private string? ValidateModerator(string moderator)
{
if(string.IsNullOrWhiteSpace(moderator))
return T("Please provide a moderator for the meeting or the seminar. Who will lead the discussion?");
return TA("Please provide a moderator for the meeting or the seminar. Who will lead the discussion?");
return null;
}
@@ -618,7 +618,7 @@ public partial class AssistantAgenda : AssistantBaseCore<SettingsDialogAgenda>
{
var markdown = new StringBuilder();
foreach (var item in items)
markdown.AppendLine($"- {item}");
markdown.AppendLineLF($"- {item}");
return markdown.ToString();
}
@@ -3,12 +3,14 @@ namespace AIStudio.Assistants.Agenda;
public static class NumberParticipantsExtensions
{
private static string TB(string fallbackEN) => Tools.PluginSystem.I18N.I.T(fallbackEN, typeof(NumberParticipantsExtensions).Namespace, nameof(NumberParticipantsExtensions));
private static string TA(string fallbackEN) => Tools.PluginSystem.I18N.I.TA(fallbackEN, typeof(NumberParticipantsExtensions).Namespace, nameof(NumberParticipantsExtensions));
extension(NumberParticipants numberParticipants)
{
public string Name => numberParticipants switch
{
NumberParticipants.NOT_SPECIFIED => TB("Please select how many participants are expected"),
NumberParticipants.NOT_SPECIFIED => TA("Please select how many participants are expected"),
NumberParticipants.PEER_TO_PEER => TB("2 (peer to peer)"),
@@ -20,16 +20,16 @@
@if (this.HasSettingsPanel)
{
<MudIconButton Variant="Variant.Text" Icon="@Icons.Material.Filled.Settings" OnClick="@(async () => await this.OpenSettingsDialog())"/>
<MudIconButton Variant="Variant.Text" Icon="@AppIcons.SETTINGS" OnClick="@(async () => await this.OpenSettingsDialog())"/>
}
</MudStack>
<InnerScrolling>
<ChildContent>
<MudForm @ref="@(this.Form)" @bind-IsValid="@(this.InputIsValid)" @bind-Errors="@(this.InputIssues)" FieldChanged="@this.TriggerFormChange" Class="pr-2">
<MudText Typo="Typo.body1" Align="Align.Justify" Class="mb-2">
<MudJustifiedText Typo="Typo.body1" Class="mb-2">
@this.Description
</MudText>
</MudJustifiedText>
@if (this.Body is not null)
{
@@ -48,7 +48,7 @@
@if (this.IsProcessing)
{
<MudTooltip Text="@TB("Stop generation")">
<MudIconButton Variant="Variant.Filled" Icon="@Icons.Material.Filled.Stop" Color="Color.Error" OnClick="@(async () => await this.CancelStreaming())"/>
<MudIconButton Variant="Variant.Filled" Icon="@AppIcons.STOP" Color="Color.Error" OnClick="@(async () => await this.CancelStreaming())"/>
</MudTooltip>
}
</MudStack>
@@ -127,7 +127,7 @@
{
@if (this.ShowSendTo && this.VisibleSendToAssistants.Count > 0)
{
<MudMenu AnchorOrigin="Origin.TopLeft" TransformOrigin="Origin.BottomLeft" StartIcon="@Icons.Material.Filled.Apps" EndIcon="@Icons.Material.Filled.KeyboardArrowDown" Label="@TB("Send to ...")" Variant="Variant.Filled" Style="@this.GetSendToColor()" Class="rounded" MaxHeight="@MenuDefaults.MAX_HEIGHT">
<MudMenu AnchorOrigin="Origin.TopLeft" TransformOrigin="Origin.BottomLeft" StartIcon="@AppIcons.SEND_TO" EndIcon="@AppIcons.DROPDOWN_MENU" Label="@TB("Send to ...")" Variant="Variant.Filled" Style="@this.GetSendToColor()" Class="rounded" MaxHeight="@MenuDefaults.MAX_HEIGHT">
@foreach (var assistant in this.VisibleSendToAssistants)
{
<MudMenuItem OnClick="@(async () => await this.SendToAssistant(assistant, new()))">
@@ -159,7 +159,7 @@
case SendToButton sendToButton:
@if (this.VisibleSendToAssistants.Count > 0)
{
<MudMenu AnchorOrigin="Origin.TopLeft" TransformOrigin="Origin.BottomLeft" StartIcon="@Icons.Material.Filled.Apps" EndIcon="@Icons.Material.Filled.KeyboardArrowDown" Label="@TB("Send to ...")" Variant="Variant.Filled" Style="@this.GetSendToColor()" Class="rounded" MaxHeight="@MenuDefaults.MAX_HEIGHT">
<MudMenu AnchorOrigin="Origin.TopLeft" TransformOrigin="Origin.BottomLeft" StartIcon="@AppIcons.SEND_TO" EndIcon="@AppIcons.DROPDOWN_MENU" Label="@TB("Send to ...")" Variant="Variant.Filled" Style="@this.GetSendToColor()" Class="rounded" MaxHeight="@MenuDefaults.MAX_HEIGHT">
@foreach (var assistant in this.VisibleSendToAssistants)
{
<MudMenuItem OnClick="@(async () => await this.SendToAssistant(assistant, sendToButton))">
@@ -174,19 +174,19 @@
@if (this.ShowCopyResult)
{
<MudButton Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.ContentCopy" OnClick="@(async () => await this.CopyToClipboard())">
<MudButton Variant="Variant.Filled" StartIcon="@AppIcons.COPY" OnClick="@(async () => await this.CopyToClipboard())">
@TB("Copy result")
</MudButton>
}
@if (this.ShowReset)
{
<MudButton Variant="Variant.Filled" Style="@this.GetResetColor()" StartIcon="@Icons.Material.Filled.Refresh" Disabled="@this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner)" OnClick="@(async () => await this.InnerResetForm())">
<MudButton Variant="Variant.Filled" Style="@this.GetResetColor()" StartIcon="@AppIcons.RESET" Disabled="@this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner)" OnClick="@(async () => await this.InnerResetForm())">
@TB("Reset")
</MudButton>
}
@if (this.SettingsManager.ConfigurationData.Confidence.ShowProviderConfidence)
@if (this.ShowsProviderConfidence)
{
<ConfidenceInfo LLMProvider="@this.ProviderSettings.UsedLLMProvider"/>
}
@@ -1,4 +1,6 @@
using AIStudio.Chat;
using AIStudio.Chat.Compression;
using AIStudio.Dialogs;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
@@ -52,6 +54,9 @@ public abstract partial class AssistantBase<TSettings> : AssistantLowerBase wher
[Inject]
private AssistantLaunchService AssistantLaunchService { get; init; } = null!;
[Inject]
private ConversationTokenCounter TokenCounter { get; init; } = null!;
/// <summary>
/// Gets the job service used to run assistant-created chats independently from the assistant UI.
/// </summary>
@@ -133,6 +138,16 @@ public abstract partial class AssistantBase<TSettings> : AssistantLowerBase wher
protected virtual bool ShowReset => true;
/// <summary>
/// Whether the footer shows the confidence card of the selected provider, and the submit button its confidence,
/// when the user wants to see confidences, see DataConfidence.ShowProviderConfidence.
/// </summary>
/// <remarks>
/// An assistant which works with several providers at once turns this off: the footer would show only one of them.
/// It shows the confidence next to each provider selection instead, see ProviderSelectionWithConfidence.
/// </remarks>
protected virtual bool ShowProviderConfidence => true;
/// <summary>
/// Whether the system prompt starts with the current date and time.
/// </summary>
@@ -254,6 +269,12 @@ public abstract partial class AssistantBase<TSettings> : AssistantLowerBase wher
private MediaImportOwner CurrentMediaImportOwner => MediaImportOwner.ForAssistant(this.assistantSessionKey);
private Guid? assistantSessionId;
/// <summary>
/// Whether the user decided already in this run to send a request which nearly fills the context window, see
/// ConfirmContextWindowAsync; reset whenever a run starts.
/// </summary>
private bool askedAboutContextWindow;
/// <summary>
/// When the running session started, which the time below the progress bar counts from; null while
/// no session runs. It comes from the session, so an instance which returns to a running session
@@ -354,18 +375,26 @@ public abstract partial class AssistantBase<TSettings> : AssistantLowerBase wher
private string TB(string fallbackEN) => this.T(fallbackEN, typeof(AssistantBase<>).Namespace, nameof(AssistantBase<>));
private string SubmitButtonStyle => this.SettingsManager.ConfigurationData.Confidence.ShowProviderConfidence ? this.ProviderSettings.UsedLLMProvider.GetConfidence(this.SettingsManager).StyleBorder(this.SettingsManager) : string.Empty;
/// <summary>
/// Gets a text of this base class which addresses the reader; the collector files it under AssistantBase, not
/// under the assistant which derives from it.
/// </summary>
private new string TA(string fallbackEN) => this.TA(fallbackEN, typeof(AssistantBase<>).Namespace, nameof(AssistantBase<>));
private bool ShowsProviderConfidence => this.ShowProviderConfidence && this.SettingsManager.ConfigurationData.Confidence.ShowProviderConfidence;
private string SubmitButtonStyle => this.ShowsProviderConfidence ? this.ProviderSettings.UsedLLMProvider.GetConfidence(this.SettingsManager).StyleBorder(this.SettingsManager) : string.Empty;
private IReadOnlyList<Tools.Components> VisibleSendToAssistants => this.AssistantLaunchService.GetDestinationsFor(this.Component);
protected string? ValidatingProvider(AIStudio.Settings.Provider provider)
{
if(provider.UsedLLMProvider == LLMProviders.NONE)
return this.TB("Please select a provider.");
return this.TA("Please select a provider.");
// A provider which nothing else rules out may still be kept from the text sent here, because of where it came from:
if (!this.transferredRestrictions.IsLLMProviderAllowed(provider) && ChatRestrictions.NONE.IsLLMProviderAllowed(provider))
return this.TB("This provider may not see the text sent to this assistant, because of where the text came from. Please select another provider.");
return this.TA("This provider may not see the text sent to this assistant, because of where the text came from. Please select another provider.");
return null;
}
@@ -395,6 +424,7 @@ public abstract partial class AssistantBase<TSettings> : AssistantLowerBase wher
this.CancellationTokenSource = new();
this.IsProcessing = true;
this.askedAboutContextWindow = false;
var startedSession = await this.AssistantSessionService.TryBeginAsync(this.assistantSessionKey, this.Title, this.CancellationTokenSource, this.ChatThread, this.CaptureAssistantSessionState(), this);
if (startedSession.IsActive is not true || startedSession.Key != this.assistantSessionKey)
{
@@ -425,14 +455,14 @@ public abstract partial class AssistantBase<TSettings> : AssistantLowerBase wher
sessionStatus = AssistantSessionStatus.FAILED;
errorMessage = e.UserMessage;
this.Logger.LogError(e, "The provider request failed for assistant '{AssistantTitle}'. Status={StatusCode}, Reason='{ReasonPhrase}', Body='{ResponseBody}'", this.Title, e.StatusCode, e.ReasonPhrase, e.ResponseBody);
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.CloudOff, e.UserMessage));
await MessageBus.INSTANCE.SendError(new(AppIcons.PROVIDER_ERROR, e.UserMessage));
}
catch (Exception e)
{
sessionStatus = AssistantSessionStatus.FAILED;
errorMessage = e.Message;
this.Logger.LogError(e, "The assistant session '{AssistantTitle}' failed.", this.Title);
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.Stream, string.Format(this.TB("The assistant failed. The message is: '{0}'"), e.Message)));
await MessageBus.INSTANCE.SendError(new(AppIcons.ANSWER_STREAM, string.Format(this.TB("The assistant failed. The message is: '{0}'"), e.Message)));
}
finally
{
@@ -672,9 +702,13 @@ public abstract partial class AssistantBase<TSettings> : AssistantLowerBase wher
/// <param name="useSelectedTools">Whether the model may use the tools the user selected. False for a request
/// which must rely on what the conversation holds already, e.g., one which reconciles results the tools
/// gathered before.</param>
/// <returns>The answer, or an empty string when the provider failed.</returns>
/// <returns>The answer, or an empty string when the provider failed or the user kept the request from being
/// sent, see ConfirmContextWindowAsync.</returns>
protected async Task<string> AddAIResponseAsync(DateTimeOffset time, bool hideContentFromUser = false, bool useSelectedTools = true)
{
if (!await this.ConfirmContextWindowAsync(time))
return string.Empty;
var manageCancellationLocally = this.CancellationTokenSource is null;
this.CancellationTokenSource ??= new CancellationTokenSource();
@@ -769,7 +803,7 @@ public abstract partial class AssistantBase<TSettings> : AssistantLowerBase wher
catch (ProviderRequestException e)
{
this.Logger.LogError(e, "The provider request failed for assistant '{AssistantTitle}'. Status={StatusCode}, Reason='{ReasonPhrase}', Body='{ResponseBody}'", this.Title, e.StatusCode, e.ReasonPhrase, e.ResponseBody);
await MessageBus.INSTANCE.SendError(new(Icons.Material.Filled.CloudOff, e.UserMessage));
await MessageBus.INSTANCE.SendError(new(AppIcons.PROVIDER_ERROR, e.UserMessage));
if (this.ResultingContentBlock is not null && string.IsNullOrWhiteSpace(aiText.Text))
{
@@ -799,6 +833,52 @@ public abstract partial class AssistantBase<TSettings> : AssistantLowerBase wher
}
}
/// <summary>
/// Asks the user what to do when the request about to be sent nearly fills the context window of the model, or no
/// longer fits into it, e.g., because of its files.
/// </summary>
/// <remarks>
/// Without it, the user hears only afterward that the request was too long, from the error of the provider, or not
/// at all, when the provider leaves out a part of it. It asks from the share on from which the chat asks as well,
/// see ConversationTokens.AsksBeforeSending, and only where the model states its window. The count takes the
/// conversation of the assistant with its files and the system prompt it stores, but neither what the request adds
/// to the system prompt nor the tools; it is an estimate, which rather asks too late than too early. A file which
/// the counter has not read yet is read for it once, so the first request with a large file waits a little longer.
/// <br/><br/>
///
/// It asks at most once per run: a run with several requests which goes on after the user chose to send anyway
/// would otherwise ask again with every request. When the user does not send, the request leaves the conversation,
/// and the run stops as if the user had stopped it, so that no later request of the run goes out instead.
/// <br/><br/>
///
/// Requests which do not go through AddAIResponseAsync are not covered: the SWOT analysis, the stages of the
/// Visual Briefing, the hidden requests of the BeyondFacts Lab, the batch processing, and the generation of
/// assistant plugins send on their own. The chats of assistants decide for themselves, see
/// EmbeddedChat.ShowsContextWindow.
/// </remarks>
/// <param name="time">When the request was added, see AddUserRequest.</param>
/// <returns>True when the request is to be sent.</returns>
private async Task<bool> ConfirmContextWindowAsync(DateTimeOffset time)
{
if (this.askedAboutContextWindow || this.ChatThread is not { } thread)
return true;
var parts = ConversationParts.Of(thread, thread.SystemPrompt, string.Empty, null, this.ProviderSettings.SupportsImageInput(), null);
var tokens = await this.TokenCounter.CountAsync(this.ProviderSettings, parts, thread.ReportedHistoryFor(this.ProviderSettings.Model), this.CancellationTokenSource?.Token ?? CancellationToken.None);
if (!tokens.AsksBeforeSending)
return true;
this.askedAboutContextWindow = true;
if (await ContextWindowFullDialog.ShowAsync(this.DialogService, tokens, ContextWindowFullSubject.ASSISTANT_REQUEST, ChatCompressionOffer.NONE) is ContextWindowFullDecision.SEND_ANYWAY)
return true;
thread.Blocks.RemoveAll(block => block.Role is ChatRole.USER && block.Time == time);
if (this.CancellationTokenSource is { } cancellation)
await cancellation.CancelAsync();
return false;
}
/// <summary>
/// Starts the current assistant chat thread as a regular background-capable chat generation job.
/// </summary>
@@ -1090,23 +1170,23 @@ public abstract partial class AssistantBase<TSettings> : AssistantLowerBase wher
if (outcome.Failures.Count > 0)
{
var message = string.Join(Environment.NewLine, outcome.Failures.Select(failure => $"{failure.FileName}: {failure.UserMessage}"));
await this.MessageBus.SendError(new(Icons.Material.Filled.VoiceChat, message));
var message = string.Join('\n',outcome.Failures.Select(failure => $"{failure.FileName}: {failure.UserMessage}"));
await this.MessageBus.SendError(new(AppIcons.VOICE_TRANSCRIPTION, message));
}
else if (outcome.Status is MediaImportStatus.FAILED)
{
await this.MessageBus.SendError(new(Icons.Material.Filled.VoiceChat, this.TB("The media file could not be transcribed.")));
await this.MessageBus.SendError(new(AppIcons.VOICE_TRANSCRIPTION, this.TB("The media file could not be transcribed.")));
}
if (outcome.Warnings.Count > 0)
{
var message = string.Join(Environment.NewLine, outcome.Warnings.Select(warning => $"{warning.FileName}: {warning.UserMessage}"));
await this.MessageBus.SendWarning(new(Icons.Material.Filled.VoiceChat, message));
var message = string.Join('\n',outcome.Warnings.Select(warning => $"{warning.FileName}: {warning.UserMessage}"));
await this.MessageBus.SendWarning(new(AppIcons.VOICE_TRANSCRIPTION, message));
}
if (outcome.Status is MediaImportStatus.CANCELLED)
{
await this.MessageBus.SendWarning(new(Icons.Material.Filled.VoiceChat, this.TB("The media transcription was canceled.")));
await this.MessageBus.SendWarning(new(AppIcons.VOICE_TRANSCRIPTION, this.TB("The media transcription was canceled.")));
}
}
@@ -7,7 +7,7 @@
@T("Input")
</MudText>
<SelectDirectory Label="@T("Folder containing your documents")" DirectoryDialogTitle="@T("Select the folder containing your documents")" @bind-Directory="@this.inputDirectory" Validation="@this.ValidateInputDirectory" EnableDragDrop="true" Disabled="@this.isProcessingBatch"/>
<SelectDirectory Label="@TA("Folder containing your documents")" DirectoryDialogTitle="@TA("Select the folder containing your documents")" @bind-Directory="@this.inputDirectory" Validation="@this.ValidateInputDirectory" EnableDragDrop="true" Disabled="@this.isProcessingBatch"/>
<MudTextSwitch Label="@T("Include subfolders?")" Disabled="@this.isProcessingBatch" Value="@this.includeSubdirectories" ValueChanged="@(v => this.includeSubdirectories = v)" LabelOn="@T("Yes, process files in subfolders as well")" LabelOff="@T("No, only process files in the selected folder")"/>
@@ -21,7 +21,7 @@
<div class="mt-6">
<FilePatternSelection>
<AllowedContent>
<MudTextField T="string" @bind-Text="@this.filePatterns" Validation="@this.ValidateFilePatterns" Immediate="@true" Disabled="@this.isProcessingBatch" Label="@T("Files to include")" AdornmentIcon="@Icons.Material.Filled.Restore" Adornment="Adornment.End" OnAdornmentClick="@this.RestoreDefaultFilePatterns" AdornmentAriaLabel="@T("Restore default patterns")" Lines="1" Sizing="InputSizing.Auto" MaxLines="@FilePatternSelection.MAX_FIELD_LINES" Class="pattern-text-field" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudTextField T="string" @bind-Text="@this.filePatterns" Validation="@this.ValidateFilePatterns" Immediate="@true" Disabled="@this.isProcessingBatch" Label="@T("Files to include")" AdornmentIcon="@AppIcons.RESTORE_DEFAULT" Adornment="Adornment.End" OnAdornmentClick="@this.RestoreDefaultFilePatterns" AdornmentAriaLabel="@T("Restore default patterns")" Lines="1" Sizing="InputSizing.Auto" MaxLines="@FilePatternSelection.MAX_FIELD_LINES" Class="pattern-text-field" Variant="Variant.Outlined" Margin="Margin.Dense" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
</AllowedContent>
</FilePatternSelection>
</div>
@@ -31,11 +31,11 @@
</MudJustifiedText>
<MudJustifiedText Typo="Typo.body2" Class="mb-3">
@T("Images in JPG, PNG, WebP, GIF, BMP, or TIFF format are given to the model as images, so you need a model that understands images. If the selected model cannot read images, remove the image patterns, such as *.jpg or *.png, before you start.")
@TA("Images in JPG, PNG, WebP, GIF, BMP, or TIFF format are given to the model as images, so you need a model that understands images. If the selected model cannot read images, remove the image patterns, such as *.jpg or *.png, before you start.")
</MudJustifiedText>
<MudStack Class="mb-3">
<MudButton OnClick="@this.ToggleExpertSettings" Variant="Variant.Text" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Tune">
<MudButton OnClick="@this.ToggleExpertSettings" Variant="Variant.Text" Color="Color.Primary" StartIcon="@AppIcons.ADVANCED_SETTINGS">
@(this.showExpertSettings ? T("Hide Expert Settings") : T("Show Expert Settings"))
</MudButton>
<MudDivider/>
@@ -59,7 +59,7 @@
@T("Instructions")
</MudText>
<MudSelect T="BatchProcessingPromptSource" Value="@this.promptSource" ValueChanged="@this.PromptSourceChanged" Disabled="@this.isProcessingBatch" AdornmentIcon="@Icons.Material.Filled.EditNote" Adornment="Adornment.Start" Label="@T("Source of the instructions")" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3">
<MudSelect T="BatchProcessingPromptSource" Value="@this.promptSource" ValueChanged="@this.PromptSourceChanged" Disabled="@this.isProcessingBatch" AdornmentIcon="@AppIcons.PROMPT" Adornment="Adornment.Start" Label="@T("Source of the instructions")" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3">
@foreach (var source in Enum.GetValues<BatchProcessingPromptSource>())
{
<MudSelectItem Value="@source">
@@ -81,7 +81,7 @@
}
else if (this.promptSource is BatchProcessingPromptSource.FILE_IMPORT)
{
<ReadFileContent Text="@T("Select the file with your instructions")" @bind-FileContent="@this.ImportedPrompt" Filter="@([FileTypes.MARKDOWN])" ShowAttachedDocumentState="@true" EnableDragDrop="true" Disabled="@this.isProcessingBatch"/>
<ReadFileContent Text="@TA("Select the file with your instructions")" @bind-FileContent="@this.ImportedPrompt" Filter="@([FileTypes.MARKDOWN])" ShowAttachedDocumentState="@true" EnableDragDrop="true" Disabled="@this.isProcessingBatch"/>
@if (!string.IsNullOrWhiteSpace(this.promptFilePath))
{
@@ -103,13 +103,13 @@ else
{
@if (this.ConfiguredPolicyIsMissing)
{
<MudAlert Severity="Severity.Warning" Dense="true" Class="mb-3">@T("The configured default policy no longer exists. Please select another document analysis policy.")</MudAlert>
<MudAlert Severity="Severity.Warning" Dense="true" Class="mb-3">@TA("The configured default policy no longer exists. Please select another document analysis policy.")</MudAlert>
}
@if (this.SettingsManager.ConfigurationData.DocumentAnalysis.Policies.Count is 0)
{
<MudJustifiedText Typo="Typo.body1" Class="mb-3">
@T("You have not yet created any document analysis policies. Please use the Document Analysis Assistant to create a policy first.")
@TA("You have not yet created any document analysis policies. Please use the Document Analysis Assistant to create a policy first.")
</MudJustifiedText>
<MudButton Href="@Routes.ASSISTANT_DOCUMENT_ANALYSIS" Variant="Variant.Filled" Color="Color.Primary" Class="mb-3">
@T("Open the Document Analysis Assistant")
@@ -117,7 +117,7 @@ else
}
else
{
<MudSelect T="DataDocumentAnalysisPolicy" Value="@this.selectedPolicy" ValueChanged="@this.SelectedPolicyChanged" Disabled="@this.isProcessingBatch" AdornmentIcon="@Icons.Material.Filled.Policy" Adornment="Adornment.Start" Label="@T("Document analysis policy")" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3">
<MudSelect T="DataDocumentAnalysisPolicy" Value="@this.selectedPolicy" ValueChanged="@this.SelectedPolicyChanged" Disabled="@this.isProcessingBatch" AdornmentIcon="@AppIcons.ANALYSIS_POLICY" Adornment="Adornment.Start" Label="@T("Document analysis policy")" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3">
@foreach (var policy in this.SettingsManager.ConfigurationData.DocumentAnalysis.Policies)
{
<MudSelectItem Value="@policy">
@@ -145,7 +145,7 @@ else
@T("Output")
</MudText>
<MudSelect T="BatchProcessingOutputMode" @bind-Value="@this.outputMode" Disabled="@this.isProcessingBatch" AdornmentIcon="@Icons.Material.Filled.Output" Adornment="Adornment.Start" Label="@T("Output mode")" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3">
<MudSelect T="BatchProcessingOutputMode" @bind-Value="@this.outputMode" Disabled="@this.isProcessingBatch" AdornmentIcon="@AppIcons.OUTPUT" Adornment="Adornment.Start" Label="@T("Output mode")" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3">
@foreach (var mode in Enum.GetValues<BatchProcessingOutputMode>())
{
<MudSelectItem Value="@mode">
@@ -156,7 +156,7 @@ else
@if (this.outputMode is BatchProcessingOutputMode.INDIVIDUAL_FILES)
{
<MudSelect T="FileExportFormat" @bind-Value="@this.resultFileFormat" Disabled="@this.isProcessingBatch" AdornmentIcon="@Icons.Material.Filled.Description" Adornment="Adornment.Start" Label="@T("File format")" HelperText="@T("Choose the format of the result files. Everything except Markdown is converted by Pandoc, which AI Studio offers to install when it is missing.")" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3">
<MudSelect T="FileExportFormat" @bind-Value="@this.resultFileFormat" Disabled="@this.isProcessingBatch" AdornmentIcon="@AppIcons.DOCUMENT" Adornment="Adornment.Start" Label="@T("File format")" HelperText="@TA("Choose the format of the result files. Everything except Markdown is converted by Pandoc, which AI Studio offers to install when it is missing.")" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3">
@foreach (var format in FileExportFormat.AnswerFormats)
{
<MudSelectItem Value="@format">
@@ -171,11 +171,11 @@ else
}
else
{
<MudTextField T="string" @bind-Text="@this.csvFileName" Validation="@this.ValidateCsvFileName" Immediate="@true" Disabled="@this.isProcessingBatch" Label="@T("Name of the results table (optional)")" HelperText="@T("The file name of the CSV results table. We add the ending .csv when it is missing. When left empty, we use 'batch-results.csv'.")" AdornmentIcon="@Icons.Material.Filled.Description" Adornment="Adornment.Start" Variant="Variant.Outlined" Margin="Margin.Normal" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudTextField T="string" @bind-Text="@this.csvFileName" Validation="@this.ValidateCsvFileName" Immediate="@true" Disabled="@this.isProcessingBatch" Label="@T("Name of the results table (optional)")" HelperText="@TA("The file name of the CSV results table. We add the ending .csv when it is missing. When left empty, we use 'batch-results.csv'.")" AdornmentIcon="@AppIcons.DOCUMENT" Adornment="Adornment.Start" Variant="Variant.Outlined" Margin="Margin.Normal" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudTextField T="string" @bind-Text="@this.resultColumnHeader" Disabled="@this.isProcessingBatch" Label="@T("Header of the result column (optional)")" HelperText="@T("The results table contains one row per document, starting with the file name. Here you can name the column that holds the AI answer, e.g., Summary. When left empty, we use 'Result'.")" AdornmentIcon="@Icons.Material.Filled.TableChart" Adornment="Adornment.Start" Variant="Variant.Outlined" Margin="Margin.Normal" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudTextField T="string" @bind-Text="@this.resultColumnHeader" Disabled="@this.isProcessingBatch" Label="@T("Header of the result column (optional)")" HelperText="@TA("The results table contains one row per document, starting with the file name. Here you can name the column that holds the AI answer, e.g., Summary. When left empty, we use 'Result'.")" AdornmentIcon="@AppIcons.RESULT_COLUMN" Adornment="Adornment.Start" Variant="Variant.Outlined" Margin="Margin.Normal" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudSelect T="BatchProcessingCsvSeparator" @bind-Value="@this.csvSeparator" Disabled="@this.isProcessingBatch" AdornmentIcon="@Icons.Material.Filled.FormatListBulleted" Adornment="Adornment.Start" Label="@T("Column separator")" HelperText="@T("Choose which character separates the columns of the results table.")" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3">
<MudSelect T="BatchProcessingCsvSeparator" @bind-Value="@this.csvSeparator" Disabled="@this.isProcessingBatch" AdornmentIcon="@AppIcons.CSV_SEPARATOR" Adornment="Adornment.Start" Label="@T("Column separator")" HelperText="@TA("Choose which character separates the columns of the results table.")" Variant="Variant.Outlined" Margin="Margin.Dense" Class="mb-3">
@foreach (var separator in Enum.GetValues<BatchProcessingCsvSeparator>())
{
<MudSelectItem Value="@separator">
@@ -186,14 +186,14 @@ else
@if (this.csvSeparator is BatchProcessingCsvSeparator.CUSTOM)
{
<MudTextField T="string" @bind-Text="@this.customCsvSeparator" Validation="@this.ValidateCustomCsvSeparator" Immediate="@true" Disabled="@this.isProcessingBatch" Label="@T("Custom column separator")" HelperText="@T("Enter one punctuation or symbol character.")" AdornmentIcon="@Icons.Material.Filled.Edit" Adornment="Adornment.Start" Variant="Variant.Outlined" Margin="Margin.Normal" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
<MudTextField T="string" @bind-Text="@this.customCsvSeparator" Validation="@this.ValidateCustomCsvSeparator" Immediate="@true" Disabled="@this.isProcessingBatch" Label="@T("Custom column separator")" HelperText="@TA("Enter one punctuation or symbol character.")" AdornmentIcon="@AppIcons.CSV_SEPARATOR" Adornment="Adornment.Start" Variant="Variant.Outlined" Margin="Margin.Normal" Class="mb-3" UserAttributes="@USER_INPUT_ATTRIBUTES"/>
}
}
<SelectDirectory Label="@T("Output folder (optional)")" DirectoryDialogTitle="@T("Select the output folder")" @bind-Directory="@this.outputDirectory" EnableDragDrop="true" Disabled="@this.isProcessingBatch"/>
<SelectDirectory Label="@T("Output folder (optional)")" DirectoryDialogTitle="@TA("Select the output folder")" @bind-Directory="@this.outputDirectory" EnableDragDrop="true" Disabled="@this.isProcessingBatch"/>
<MudJustifiedText Typo="Typo.body2" Class="mb-3">
@T("We always write a semicolon-separated log named log.csv, which lists every document with its processing time, the model, the status, and the details of any error. When you start another run on the same output folder, we ask you whether to continue that run: documents which failed or are missing in the log are then processed again. When no output folder is selected, everything is written to the subfolder 'ai-results' within the input folder.")
@TA("We always write a semicolon-separated log named log.csv, which lists every document with its processing time, the model, the status, and the details of any error. When you start another run on the same output folder, we ask you whether to continue that run: documents which failed or are missing in the log are then processed again. When no output folder is selected, everything is written to the subfolder 'ai-results' within the input folder.")
</MudJustifiedText>
<MudText Typo="Typo.h6" Class="mb-3 mt-6">
@@ -203,7 +203,7 @@ else
@if (MinimumDelayIsManaged)
{
<MudAlert Severity="Severity.Info" Dense="true" Class="mb-3">
@(string.Format(T("Your organization requires a pause of at least {0} seconds between files."), this.ManagedMinimumDelaySeconds))
@(string.Format(TA("Your organization requires a pause of at least {0} seconds between files."), this.ManagedMinimumDelaySeconds))
</MudAlert>
}
else
@@ -219,7 +219,7 @@ else
@if (this.pauseBeforeNextFileSeconds > 0)
{
<MudAlert Severity="Severity.Info" Icon="@Icons.Material.Filled.HourglassTop" Dense="true" Class="mb-3">
<MudAlert Severity="Severity.Info" Icon="@AppIcons.PENDING" Dense="true" Class="mb-3">
@(string.Format(T("Waiting {0} seconds before starting the next file."), this.pauseBeforeNextFileSeconds))
</MudAlert>
}
@@ -248,7 +248,7 @@ else
@if (this.isProcessingBatch)
{
<MudButton OnClick="@this.CancelBatchProcessingAsync" Variant="Variant.Filled" Color="Color.Error" StartIcon="@Icons.Material.Filled.Cancel" Class="mb-3">
<MudButton OnClick="@this.CancelBatchProcessingAsync" Variant="Variant.Filled" Color="Color.Error" StartIcon="@AppIcons.CANCEL" Class="mb-3">
@T("Cancel the batch run")
</MudButton>
}
@@ -269,7 +269,7 @@ else
@switch (fileResult.Status)
{
case BatchProcessingFileStatus.QUEUED:
<MudIcon Icon="@Icons.Material.Filled.Schedule" Size="Size.Small" Title="@T("Queued")"/>
<MudIcon Icon="@AppIcons.PENDING" Size="Size.Small" Title="@T("Queued")"/>
break;
case BatchProcessingFileStatus.PROCESSING:
@@ -277,15 +277,15 @@ else
break;
case BatchProcessingFileStatus.DONE:
<MudIcon Icon="@Icons.Material.Filled.CheckCircle" Color="Color.Success" Size="Size.Small" Title="@T("Done")"/>
<MudIcon Icon="@AppIcons.SUCCESS" Color="Color.Success" Size="Size.Small" Title="@T("Done")"/>
break;
case BatchProcessingFileStatus.FAILED:
<MudIcon Icon="@Icons.Material.Filled.Error" Color="Color.Error" Size="Size.Small" Title="@T("Failed")"/>
<MudIcon Icon="@AppIcons.ERROR" Color="Color.Error" Size="Size.Small" Title="@T("Failed")"/>
break;
case BatchProcessingFileStatus.CANCELED:
<MudIcon Icon="@Icons.Material.Filled.Cancel" Color="Color.Warning" Size="Size.Small" Title="@T("Canceled")"/>
<MudIcon Icon="@AppIcons.CANCELED" Color="Color.Warning" Size="Size.Small" Title="@T("Canceled")"/>
break;
}
</td>
@@ -58,7 +58,7 @@ public partial class AssistantBatchProcessing
{
if (!this.ProviderSettings.SupportsImageInput())
{
this.FinishFileResult(fileResult, BatchProcessingFileStatus.FAILED, T("The selected model cannot read images. Select a model with image support to process this image."));
this.FinishFileResult(fileResult, BatchProcessingFileStatus.FAILED, TA("The selected model cannot read images. Select a model with image support to process this image."));
return null;
}
@@ -128,13 +128,13 @@ public partial class AssistantBatchProcessing
if (extraction.Outcome is FileExtractionOutcome.PARTIAL)
{
this.Logger.LogWarning("Parts of the batch file '{FilePath}' could not be read: pages={FailedPages}.", fileResult.FilePath, string.Join(", ", extraction.FailedPages));
await this.MessageBus.SendWarning(new(Icons.Material.Filled.Description, extraction.ToPartialUserMessage(fileResult.FileName)));
await this.MessageBus.SendWarning(new(AppIcons.DOCUMENT, extraction.ToPartialUserMessage(fileResult.FileName)));
}
if (extraction.HasExtensionMismatch)
{
this.Logger.LogWarning("The batch file '{FilePath}' is actually a '{DetectedFormat}'.", fileResult.FilePath, extraction.DetectedFormat);
await this.MessageBus.SendWarning(new(Icons.Material.Filled.RuleFolder, extraction.ToExtensionMismatchUserMessage(fileResult.FileName)));
await this.MessageBus.SendWarning(new(AppIcons.FILE_TYPE_MISMATCH, extraction.ToExtensionMismatchUserMessage(fileResult.FileName)));
}
if (!string.IsNullOrWhiteSpace(extraction.Content))
@@ -106,9 +106,9 @@ public partial class AssistantBatchProcessing
private async Task WriteLogAsync(string resolvedOutputDirectory)
{
var sb = new StringBuilder();
sb.AppendLine(CsvWriter.ToRow(LOG_SEPARATOR, T("File"), T("Time"), T("Model"), T("Status"), T("Details"), T("Tools used")));
sb.Append(CsvWriter.ToRow(LOG_SEPARATOR, T("File"), T("Time"), T("Model"), T("Status"), T("Details"), T("Tools used"))).Append(CsvWriter.ROW_END);
foreach (var fileResult in this.fileResults.Where(x => x.Status is not BatchProcessingFileStatus.QUEUED and not BatchProcessingFileStatus.PROCESSING))
sb.AppendLine(CsvWriter.ToRow(LOG_SEPARATOR, fileResult.RelativePath, fileResult.ProcessedAt.ToString(TIME_FORMAT, CultureInfo.InvariantCulture), fileResult.ModelName, fileResult.Status.ToString(), fileResult.Message, fileResult.UsedTools));
sb.Append(CsvWriter.ToRow(LOG_SEPARATOR, fileResult.RelativePath, fileResult.ProcessedAt.ToString(TIME_FORMAT, CultureInfo.InvariantCulture), fileResult.ModelName, fileResult.Status.ToString(), fileResult.Message, fileResult.UsedTools)).Append(CsvWriter.ROW_END);
await this.WriteCsvFileAsync(Path.Join(resolvedOutputDirectory, LOG_FILENAME), sb.ToString());
}
@@ -120,41 +120,29 @@ public partial class AssistantBatchProcessing
{
var separator = this.csvSeparator.Character(this.customCsvSeparator);
var sb = new StringBuilder();
sb.AppendLine(CsvWriter.ToRow(separator, T("File"), this.ResultColumnHeader));
sb.Append(CsvWriter.ToRow(separator, T("File"), this.ResultColumnHeader)).Append(CsvWriter.ROW_END);
foreach (var fileResult in this.fileResults.Where(x => x.Status is BatchProcessingFileStatus.DONE))
sb.AppendLine(CsvWriter.ToRow(separator, fileResult.RelativePath, fileResult.ResultText));
sb.Append(CsvWriter.ToRow(separator, fileResult.RelativePath, fileResult.ResultText)).Append(CsvWriter.ROW_END);
await this.WriteCsvFileAsync(Path.Join(resolvedOutputDirectory, this.ResolveResultsFileName()), sb.ToString());
}
private async Task WriteCsvFileAsync(string targetFilePath, string content)
{
// Write to a sibling file first, then rename. This way, an aborted
// write can never destroy the results of the previous files:
var tempFilePath = targetFilePath + ".tmp";
try
{
// We write the CSV file with a byte order mark, so that spreadsheet
// applications recognize the UTF-8 encoding of, e.g., umlauts:
await File.WriteAllTextAsync(tempFilePath, content, new UTF8Encoding(true), CancellationToken.None);
File.Move(tempFilePath, targetFilePath, true);
// AtomicFile writes to a sibling file first, then renames it. This way, an aborted
// write can never destroy the results of the previous files. It also removes the
// sibling file when the write fails, so that it neither looks like a result to the
// user nor piles up over several runs. We write the CSV file with a byte order
// mark, so that spreadsheet applications recognize the UTF-8 encoding of, e.g.,
// umlauts:
await AtomicFile.WriteTextAsync(targetFilePath, content, new UTF8Encoding(true), CancellationToken.None, logger: this.Logger);
}
catch (Exception e)
{
this.Logger.LogError(e, "Was not able to write the batch output file '{TargetFilePath}'.", targetFilePath);
// Remove our leftover: a failing rename keeps the temporary file in
// the output folder, where it looks like a result to the user and
// piles up over several runs.
try
{
File.Delete(tempFilePath);
}
catch (Exception deleteError)
{
this.Logger.LogWarning(deleteError, "Was not able to remove the temporary file '{TempFilePath}'.", tempFilePath);
}
// A failing write repeats for every document. We report it once per
// run: without any message, the UI would show a successful run
// while the files on disk stay behind.
@@ -162,7 +150,7 @@ public partial class AssistantBatchProcessing
return;
this.hasReportedWriteFailure = true;
await this.MessageBus.SendError(new(Icons.Material.Filled.SaveAs, string.Format(T("Was not able to write '{0}'. Please make sure that the file is not opened in another application. The results of this run are incomplete on disk. The message is: '{1}'"), Path.GetFileName(targetFilePath), e.Message)));
await this.MessageBus.SendError(new(AppIcons.SAVE_FAILED, string.Format(TA("Was not able to write '{0}'. Please make sure that the file is not opened in another application. The results of this run are incomplete on disk. The message is: '{1}'"), Path.GetFileName(targetFilePath), e.Message)));
}
}
@@ -195,7 +183,7 @@ public partial class AssistantBatchProcessing
// Without this message, continuing the run would silently process
// every document again, because we recognize nothing as completed:
await this.MessageBus.SendWarning(new(Icons.Material.Filled.Warning, T("Was not able to read the log of the previous run. Continuing the run would process all documents again.")));
await this.MessageBus.SendWarning(new(AppIcons.WARNING, T("Was not able to read the log of the previous run. Continuing the run would process all documents again.")));
}
return entries;
@@ -227,7 +215,7 @@ public partial class AssistantBatchProcessing
catch (Exception e)
{
this.Logger.LogWarning(e, "Was not able to read the results table of the previous batch run at '{ResultsFilePath}'.", resultsFilePath);
await this.MessageBus.SendWarning(new(Icons.Material.Filled.Warning, T("Was not able to read the results table of the previous run. Its completed documents cannot be restored and will be processed again.")));
await this.MessageBus.SendWarning(new(AppIcons.WARNING, T("Was not able to read the results table of the previous run. Its completed documents cannot be restored and will be processed again.")));
}
return results;
@@ -109,7 +109,7 @@ public partial class AssistantBatchProcessing
? T("The selected model cannot read images, so the image among the selected files will fail. All other files are processed as usual.")
: string.Format(T("The selected model cannot read images, so the {0} images among the selected files will fail. All other files are processed as usual."), numImages);
await this.MessageBus.SendWarning(new(Icons.Material.Filled.ImageNotSupported, warning));
await this.MessageBus.SendWarning(new(AppIcons.IMAGE_NOT_SUPPORTED, warning));
}
/// <summary>
@@ -196,9 +196,9 @@ public partial class AssistantBatchProcessing
if (failedFiles > 0)
{
var failureMessage = failedFiles == 1
? T("The batch run finished, but one file could not be processed. See the progress table and log for details.")
: string.Format(T("The batch run finished, but {0} files could not be processed. See the progress table and log for details."), failedFiles);
await this.MessageBus.SendError(new(Icons.Material.Filled.Error, failureMessage));
? TA("The batch run finished, but one file could not be processed. See the progress table and log for details.")
: string.Format(TA("The batch run finished, but {0} files could not be processed. See the progress table and log for details."), failedFiles);
await this.MessageBus.SendError(new(AppIcons.ERROR, failureMessage));
}
}
}
@@ -8,7 +8,7 @@ public partial class AssistantBatchProcessing
private string? ValidateInputDirectory(string directory)
{
if (string.IsNullOrWhiteSpace(directory))
return T("Please select the folder that contains the documents you want to process.");
return TA("Please select the folder that contains the documents you want to process.");
if (!Directory.Exists(directory))
return T("The selected folder does not exist.");
@@ -24,7 +24,7 @@ public partial class AssistantBatchProcessing
return null;
if (fileName.Trim().IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
return T("Please provide a file name without a path, e.g., my-results.csv");
return TA("Please provide a file name without a path, e.g., my-results.csv");
return null;
}
@@ -36,7 +36,7 @@ public partial class AssistantBatchProcessing
return null;
if (!BatchProcessingCsvSeparator.IsValidCustomSeparator(separator))
return T("Please enter exactly one punctuation or symbol character. Letters, numbers, spaces, quotation marks, and line breaks cannot be used as CSV separators.");
return TA("Please enter exactly one punctuation or symbol character. Letters, numbers, spaces, quotation marks, and line breaks cannot be used as CSV separators.");
return null;
}
@@ -44,7 +44,7 @@ public partial class AssistantBatchProcessing
private string? ValidateFreePrompt(string prompt)
{
if (this.promptSource is BatchProcessingPromptSource.FREE_PROMPT && string.IsNullOrWhiteSpace(prompt))
return T("Please describe what the AI should do with each document.");
return TA("Please describe what the AI should do with each document.");
return null;
}
@@ -54,10 +54,10 @@ public partial class AssistantBatchProcessing
/// </summary>
private string? ValidateInstructionSource() => this.promptSource switch
{
BatchProcessingPromptSource.POLICY when this.ConfiguredPolicyIsMissing => T("The configured default policy no longer exists. Please select another document analysis policy."),
BatchProcessingPromptSource.POLICY when this.selectedPolicy is null => T("Please select a document analysis policy."),
BatchProcessingPromptSource.POLICY when this.ConfiguredPolicyIsMissing => TA("The configured default policy no longer exists. Please select another document analysis policy."),
BatchProcessingPromptSource.POLICY when this.selectedPolicy is null => TA("Please select a document analysis policy."),
BatchProcessingPromptSource.FILE_IMPORT when !string.IsNullOrWhiteSpace(this.promptFileLoadIssue) => this.promptFileLoadIssue,
BatchProcessingPromptSource.FILE_IMPORT when string.IsNullOrWhiteSpace(this.importedPrompt) => T("Please select the file which contains your instructions."),
BatchProcessingPromptSource.FILE_IMPORT when string.IsNullOrWhiteSpace(this.importedPrompt) => TA("Please select the file which contains your instructions."),
_ => null,
};
@@ -165,7 +165,7 @@ public partial class AssistantBatchProcessing
if (files.Count == 0)
{
this.AddInputIssue(this.numTooLargeFiles > 0
? string.Format(T("Every matching file in the selected folder is larger than {0}. Raise the size limit to process them."), FolderFileSelection.MegabytesToBytes(this.maxFileSizeMegabytes).FileSize())
? string.Format(TA("Every matching file in the selected folder is larger than {0}. Raise the size limit to process them."), FolderFileSelection.MegabytesToBytes(this.maxFileSizeMegabytes).FileSize())
: T("No matching files were found in the selected folder."));
return null;
}
@@ -173,7 +173,7 @@ public partial class AssistantBatchProcessing
var requiresTranscription = files.Any(file => IsTranscribableMedia(file) && !HasReusableTranscript(file));
if (requiresTranscription && !this.MediaTranscriptionService.HasUsableTranscriptionProvider)
{
this.AddInputIssue(T("The selected files include audio or video without an existing transcript, but no usable transcription provider is configured. Configure one in the transcription settings or remove the media patterns."));
this.AddInputIssue(TA("The selected files include audio or video without an existing transcript, but no usable transcription provider is configured. Configure one in the transcription settings or remove the media patterns."));
return null;
}
@@ -184,7 +184,7 @@ public partial class AssistantBatchProcessing
//
if (files.All(IsImage) && !this.ProviderSettings.SupportsImageInput())
{
this.AddInputIssue(T("All selected files are images, but the selected model cannot read images. Select a model with image support."));
this.AddInputIssue(TA("All selected files are images, but the selected model cannot read images. Select a model with image support."));
return null;
}
@@ -54,7 +54,7 @@ public partial class AssistantBatchProcessing : AssistantBaseCore<SettingsDialog
protected override string Title => T("Batch Processing Assistant");
protected override string Description => T("Process all documents and media files of a folder in one batch run: documents are converted to Markdown, while audio and video files are transcribed automatically, before their content is sent to the AI along with your instructions. You choose whether each answer is stored as its own Markdown file or whether all answers are collected in one CSV results table. A log records what happened to every file, so a run which was interrupted or produced errors can be continued later. A single failing file never stops the entire run.");
protected override string Description => TA("Process all documents and media files of a folder in one batch run: documents are converted to Markdown, while audio and video files are transcribed automatically, before their content is sent to the AI along with your instructions. You choose whether each answer is stored as its own Markdown file or whether all answers are collected in one CSV results table. A log records what happened to every file, so a run which was interrupted or produced errors can be continued later. A single failing file never stops the entire run.");
// The results of this assistant go into files, so no chat continues its conversations:
protected override ChatSystemPromptChoice ChatSystemPrompt => ChatSystemPromptChoice.AI_STUDIO_DEFAULT;
@@ -0,0 +1,216 @@
@attribute [Route(Routes.ASSISTANT_BEYOND_FACTS_LAB)]
@inherits MSGComponentBase
<CascadingValue Value="Components.BEYOND_FACTS_LAB_ASSISTANT">
@* The lab does not inherit AssistantBase, so it sets up the inner scrolling itself, the way the
Visual Briefing assistant does, and is a drop area of its own: a document dropped anywhere on
the page lands in the material of the open preparation. *@
<PathDropZone IsArea="@true" Class="inner-scrolling-context">
<PreviewPrototype ApplyInnerScrollingFix="true"/>
<MudStack Row="true" AlignItems="AlignItems.Center" Class="mb-3 mr-3" StretchItems="StretchItems.Start">
<MudText Typo="Typo.h3">@T("BeyondFacts Lab")</MudText>
<MudSpacer/>
<MudIconButton Variant="Variant.Text" Icon="@AppIcons.SETTINGS" OnClick="@this.OpenSettingsDialogAsync"/>
</MudStack>
<InnerScrolling>
@* How to work with the lab opens by itself while there is no preparation yet. The guidelines of the
organization appear only when a configuration plugin sets them, and open with every visit. *@
<MudExpansionPanels MultiExpansion="@true" Class="mb-6 mr-3">
<ExpansionPanel HeaderIcon="@AppIcons.INTRODUCTION" HeaderText="@T("Working with the lab")" IsExpanded="@this.introductionExpanded" ExpandedChanged="@this.IntroductionExpandedChanged">
<BflIntroduction/>
</ExpansionPanel>
<ExpansionPanel HeaderIcon="@AppIcons.HELP" HeaderText="@T("Is the lab right for my task?")">
<BflOnboarding/>
</ExpansionPanel>
@if (!string.IsNullOrWhiteSpace(this.OrganizationRules))
{
<ExpansionPanel HeaderIcon="@AppIcons.ORGANIZATION" HeaderText="@TA("Guidelines from your organization")" IsExpanded="@this.organizationRulesExpanded" ExpandedChanged="@this.OrganizationRulesExpandedChanged">
<MudText Typo="Typo.body2" Class="mb-3">@string.Format(Culture, TA("Your organization has set these guidelines for public appearances. The conversations of the steps know them as well, and the material '{0}' ends with them."), BflResultKind.OPEN_POINTS.Title)</MudText>
<MudMarkdown Value="@this.OrganizationRules" Props="Markdown.DefaultConfig" MarkdownPipeline="Markdown.SAFE_MARKDOWN_PIPELINE"/>
</ExpansionPanel>
}
</MudExpansionPanels>
<MudText Typo="Typo.h5" Class="mb-1">@TA("Your preparations")</MudText>
@if (this.projects.Count == 0)
{
<MudText Typo="Typo.body2" Class="mb-3">@TA("You have no preparations yet. Create one for the event you want to prepare for.")</MudText>
}
else
{
<MudList T="Guid"
Color="Color.Primary"
Class="mb-1"
SelectedValue="@(this.selectedProject?.ProjectId ?? Guid.Empty)"
SelectedValueChanged="@this.SelectProjectAsync">
@foreach (var project in this.projects)
{
<MudListItem T="Guid" @key="project.ProjectId" Value="@project.ProjectId" Icon="@ProjectIcon(project)">
<MudStack Spacing="0">
<MudText Typo="Typo.body1">@this.ProjectDisplayName(project)</MudText>
<MudText Typo="Typo.caption">@this.ProjectCaption(project)</MudText>
@if (this.projectsWithMissingDetails.Contains(project.ProjectId))
{
<MudText Typo="Typo.caption" Color="Color.Warning">@T("Details missing")</MudText>
}
@if (!project.IsAvailable)
{
<MudText Typo="Typo.caption" Color="Color.Error">@this.ProjectStatusName(project.Status)</MudText>
}
</MudStack>
</MudListItem>
}
</MudList>
}
<MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@AppIcons.ADD" OnClick="@this.CreateProjectAsync" Disabled="@this.isBusy" Class="mt-1">
@T("New preparation")
</MudButton>
<MudDivider Style="height: 0.25ch; margin: 1rem 0;" Class="mt-6"/>
@if (this.selectedProject is { IsAvailable: false } unavailableProject)
{
<MudPaper Outlined="true" Class="pa-6 mr-3">
<MudStack Spacing="3">
<MudText Typo="Typo.h4">@this.ProjectDisplayName(unavailableProject)</MudText>
<MudAlert Severity="Severity.Error" Variant="Variant.Outlined">
@this.ProjectRecoveryMessage(unavailableProject.Status)
</MudAlert>
<MudText Typo="Typo.body1">@T("AI Studio has left the files of this preparation unchanged. A future update may make it accessible again.")</MudText>
<MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1" Wrap="Wrap.Wrap">
<MudText Typo="Typo.body2"><strong>@T("Preparation ID"):</strong> @unavailableProject.ProjectId.ToString("D")</MudText>
<MudCopyClipboardButton TooltipMessage="@T("Copy preparation ID")" StringContent="@unavailableProject.ProjectId.ToString("D")"/>
</MudStack>
<MudStack Row="true" Spacing="1" Wrap="Wrap.Wrap">
<MudButton Variant="Variant.Filled" StartIcon="@AppIcons.DELETE" Color="Color.Error" OnClick="@this.DeleteProjectAsync" Disabled="@this.isBusy">@T("Delete")</MudButton>
</MudStack>
</MudStack>
</MudPaper>
}
else if (this.selectedProject?.Project is { } project)
{
@* Stays at the top while the person scrolls, like the header of the workspaces: the preparation, its
provider, and the steps remain in view, and only the list of preparations scrolls away. The empty
anchor before it marks where the header sits in the flow, to scroll back there for another step.
Its background is that of the page, which lies on the paper of MainLayout: the background of the
palette is darker in the dark mode. *@
<div @ref="@this.stickyHeaderAnchor"></div>
<div @ref="@this.stickyHeader" class="mr-3" style="position: sticky; top: 0; z-index: 2; background-color: var(--mud-palette-surface);">
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center" Wrap="Wrap.Wrap" Class="mb-3">
<MudStack Spacing="0">
<MudText Typo="Typo.h4">@project.Name</MudText>
@if (project.HappenedAtUtc is { } happenedAtUtc)
{
<MudText Typo="Typo.caption">@string.Format(Culture, T("Marked on {0}."), happenedAtUtc.ToLocalTime().ToString("d", Culture))</MudText>
}
</MudStack>
<MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1" Wrap="Wrap.Wrap">
<MudSwitch T="bool" Value="@(project.HappenedAtUtc is not null)" ValueChanged="@this.SetHappenedAsync" Disabled="@this.isBusy" Color="Color.Primary" Class="mr-2">
@T("The event has taken place")
</MudSwitch>
<MudButton StartIcon="@AppIcons.SHARE_WITH_RESEARCH" OnClick="@this.ShareAsync" Disabled="@this.isBusy">@T("Share with the research team")</MudButton>
<MudButton StartIcon="@AppIcons.RENAME" OnClick="@this.RenameProjectAsync" Disabled="@this.isBusy">@T("Rename")</MudButton>
<MudButton StartIcon="@AppIcons.DELETE" Color="Color.Error" OnClick="@this.DeleteProjectAsync" Disabled="@this.isBusy">@T("Delete")</MudButton>
</MudStack>
</MudStack>
<ProviderSelection ProviderSettings="@this.providerSettings" ProviderSettingsChanged="@this.SelectProviderAsync" ValidateProvider="@this.ValidateProvider" Disabled="@this.isBusy"/>
@* The steps have no content of their own: only the navigation of the stepper stays in view, and the
step shown follows below. *@
<MudStepperWithoutActions NonLinear="@true" ActiveIndex="@this.ActiveStepIndex" ActiveIndexChanged="@this.SelectStepAsync">
<ChildContent>
@foreach (var step in BflStep.All)
{
<MudStep @key="step" Title="@step.Title" SecondaryText="@this.StepSecondaryText(step)" Completed="@this.IsStepCompleted(step)"/>
}
</ChildContent>
</MudStepperWithoutActions>
</div>
@* The material stands beside the step, as it applies to all steps, and below it on a narrow window. It
stays out of the key of the step, so that reading a document goes on when the person picks another step.
Beside the step, it stays in view below the header, see the scoped CSS of this page. *@
<div class="mr-3">
<MudGrid Spacing="3">
<MudItem xs="12" lg="8">
<div @key="@this.activeStep" class="px-6">
@* It checks the test folder anew for every step, as the key of the step recreates it: *@
<BflPromptOverrideNotice Class="mt-2 mb-2"/>
<MudText Typo="Typo.h5" Class="mt-2">@this.activeStep.Title</MudText>
<MudText Typo="Typo.body2" Class="mb-4">@this.activeStep.Description</MudText>
<MudText Typo="Typo.h6" Class="mb-2">@TA("Your details")</MudText>
@if (this.forms.TryGetValue(this.activeStep, out var form))
{
var step = this.activeStep;
<BflStepForm Step="@step" Form="@form" FormChanged="@(() => this.SaveFormAsync(step))"/>
@if (step is BflStep.TEST_SITUATION)
{
<BflSimulationChoice ProjectId="@project.ProjectId"
Forms="@this.forms"
Form="@form"
FormChanged="@(() => this.SaveFormAsync(step))"
Provider="@this.providerSettings"
Class="mt-3"/>
}
}
else
{
<MudAlert Severity="Severity.Error" Variant="Variant.Outlined">
@TA("AI Studio cannot open your details for this step. Their file may be damaged, or a newer version of AI Studio stored it. AI Studio leaves the file unchanged.")
</MudAlert>
}
@if (this.activeStep is BflStep.STRATEGY)
{
<BflResearchPanel ProjectId="@project.ProjectId"
Forms="@this.forms"
ResearchStored="@this.ProjectStoredAsync"
Provider="@this.providerSettings"
ProviderIssue="@this.ValidateProvider(this.providerSettings)"/>
}
<BflChat Location="@(new BflStepThreadLocation(project.ProjectId, this.activeStep))" Provider="@this.providerSettings" ProviderIssue="@this.ValidateProvider(this.providerSettings)" DetailsVersion="@this.ChatDetailsVersion"/>
<BflWorkStatePanel Location="@(new BflStepThreadLocation(project.ProjectId, this.activeStep))"
WorkStates="@this.workStates"
Forms="@this.forms"
FormChanged="@(() => this.SaveFormAsync(this.activeStep))"
WorkStateStored="@this.ProjectStoredAsync"
WorkStateConfirmed="@this.WorkStateConfirmedAsync"
Provider="@this.providerSettings"
ProviderIssue="@this.ValidateProvider(this.providerSettings)"/>
@if (this.activeStep is BflStep.RESULTS)
{
<BflResults ProjectId="@project.ProjectId"
ProjectName="@project.Name"
WorkStates="@this.workStates"
Forms="@this.forms"
ResultStored="@this.ProjectStoredAsync"
Provider="@this.providerSettings"
ProviderIssue="@this.ValidateProvider(this.providerSettings)"/>
}
</div>
</MudItem>
<MudItem xs="12" lg="4">
<div class="bfl-material-column">
<BflMaterials ProjectId="@project.ProjectId" Step="@this.activeStep" Provider="@this.providerSettings" ProviderIssue="@this.ValidateProvider(this.providerSettings)"/>
<BflConfirmedWorkStates WorkStates="@this.workStates" Forms="@this.forms" Class="mt-3"/>
</div>
</MudItem>
</MudGrid>
</div>
}
else
{
<MudPaper Outlined="true" Class="pa-6 mr-3">
<MudText Typo="Typo.h5">@TA("Create a preparation to begin.")</MudText>
</MudPaper>
}
</InnerScrolling>
</PathDropZone>
</CascadingValue>
@@ -0,0 +1,280 @@
using System.Globalization;
using AIStudio.Chat;
using AIStudio.Dialogs;
using DialogOptions = AIStudio.Dialogs.DialogOptions;
namespace AIStudio.Assistants.BeyondFactsLab;
public partial class BeyondFactsLabAssistant
{
/// <summary>
/// The preparations, the one changed last first.
/// </summary>
private IReadOnlyList<BflProjectEntry> projects = [];
/// <summary>
/// The preparation shown, or null when there is none.
/// </summary>
private BflProjectEntry? selectedProject;
/// <summary>
/// Whether a change of the preparations is running.
/// </summary>
private bool isBusy;
/// <summary>
/// The IDs of the preparations which lack key details.
/// </summary>
private HashSet<Guid> projectsWithMissingDetails = [];
/// <summary>
/// Gets the culture of the active language plugin, for dates.
/// </summary>
private static CultureInfo Culture => Tools.PluginSystem.I18N.I.Culture;
/// <summary>
/// Reads the preparations again and chooses the one to show.
/// </summary>
/// <param name="preferredId">The preparation to show, or null to keep the one shown so far.</param>
private async Task ReloadProjectsAsync(Guid? preferredId)
{
this.projects = await this.Store.ListProjectsAsync();
var withMissingDetails = new HashSet<Guid>();
foreach (var project in this.projects.Where(project => project.IsAvailable))
{
if (BflMissingDetails.StepsOf(await this.Store.LoadFormsAsync(project.ProjectId)).Count > 0)
withMissingDetails.Add(project.ProjectId);
}
this.projectsWithMissingDetails = withMissingDetails;
await this.ShowProjectAsync(BflProjectSelection.Choose(this.projects, preferredId ?? this.selectedProject?.ProjectId, this.Store.LastSelectedProjectId));
}
/// <summary>
/// Shows the preparation the person selected and remembers it for the next time.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
private async Task SelectProjectAsync(Guid projectId)
{
if (this.selectedProject?.ProjectId == projectId)
return;
var project = this.projects.FirstOrDefault(candidate => candidate.ProjectId == projectId);
if (project is null)
return;
await this.RunStoreActionAsync(async () =>
{
await this.ShowProjectAsync(project);
await this.Store.RememberSelectionAsync(projectId);
});
}
/// <summary>
/// Asks for a name and creates a preparation.
/// </summary>
private async Task CreateProjectAsync()
{
var name = await this.AskForNameAsync(T("New preparation"), TA("Name the event you want to prepare for, e.g., the title of a panel discussion."), string.Empty, T("Create"));
if (name is null)
return;
await this.RunStoreActionAsync(async () =>
{
var project = await this.Store.CreateAsync(name);
await this.Store.RememberSelectionAsync(project.ProjectId);
await this.ReloadProjectsAsync(project.ProjectId);
// The new preparation comes into view:
this.introductionExpanded = false;
});
}
/// <summary>
/// Asks for a new name and renames the preparation shown.
/// </summary>
private async Task RenameProjectAsync()
{
if (this.selectedProject?.Project is not { } project)
return;
var name = await this.AskForNameAsync(T("Rename preparation"), TA("Enter a new name for this preparation."), project.Name, T("Rename"));
if (name is null)
return;
await this.RunStoreActionAsync(async () =>
{
await this.Store.RenameAsync(project.ProjectId, name);
await this.ReloadProjectsAsync(project.ProjectId);
});
}
/// <summary>
/// Deletes the preparation shown, after the person confirmed it.
/// </summary>
private async Task DeleteProjectAsync()
{
if (this.selectedProject is not { } project)
return;
var parameters = new DialogParameters<ConfirmDialog>
{
{
dialog => dialog.Message,
project.IsAvailable
? string.Format(TA("Permanently delete the preparation '{0}' with all of its steps, chats, material, and work states?"), project.Name)
: TA("This preparation cannot be opened. Permanently delete it with all of its files?")
},
};
var reference = await this.DialogService.ShowAsync<ConfirmDialog>(T("Delete preparation permanently"), parameters, DialogOptions.FULLSCREEN);
var result = await reference.Result;
if (result is null || result.Canceled)
return;
await this.RunStoreActionAsync(async () =>
{
// An answer which still runs would otherwise end after the preparation is gone:
var chatIds = await this.ConversationService.ForgetProjectAsync(project.ProjectId);
await this.Store.DeleteAsync(project.ProjectId);
// What the chats received goes along with them; whatever this misses, the cleanup at the next start removes:
await ChatProvenance.ForgetChatsAsync(chatIds);
this.selectedProject = null;
await this.ReloadProjectsAsync(null);
});
}
/// <summary>
/// Marks the event of the preparation shown as having taken place, or takes that back.
/// </summary>
/// <param name="happened">Whether the event has taken place.</param>
private async Task SetHappenedAsync(bool happened)
{
if (this.selectedProject?.Project is not { } project)
return;
await this.RunStoreActionAsync(async () =>
{
await this.Store.SetHappenedAsync(project.ProjectId, happened ? DateTimeOffset.UtcNow : null);
await this.ReloadProjectsAsync(project.ProjectId);
});
}
/// <summary>
/// Asks for the name of a preparation.
/// </summary>
/// <param name="title">The title of the dialog.</param>
/// <param name="message">What the dialog asks for.</param>
/// <param name="currentName">The name to start with.</param>
/// <param name="confirmText">The text of the button which confirms.</param>
/// <returns>The name entered, or null when the person canceled.</returns>
private async Task<string?> AskForNameAsync(string title, string message, string currentName, string confirmText)
{
var parameters = new DialogParameters<SingleInputDialog>
{
{ dialog => dialog.Message, message },
{ dialog => dialog.InputHeaderText, T("Name of the preparation") },
{ dialog => dialog.UserInput, currentName },
{ dialog => dialog.ConfirmText, confirmText },
{ dialog => dialog.ConfirmColor, Color.Primary },
{ dialog => dialog.AllowEmptyInput, false },
{ dialog => dialog.EmptyInputErrorMessage, TA("Please enter a name.") },
};
var reference = await this.DialogService.ShowAsync<SingleInputDialog>(title, parameters, DialogOptions.FULLSCREEN);
var result = await reference.Result;
if (result is null || result.Canceled || result.Data is not string name || string.IsNullOrWhiteSpace(name))
return null;
return name;
}
/// <summary>
/// Runs a change of the preparations, and tells the person when it fails.
/// </summary>
/// <param name="action">The change.</param>
private async Task RunStoreActionAsync(Func<Task> action)
{
this.isBusy = true;
try
{
await action();
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidDataException or ArgumentException)
{
this.Logger.LogError(exception, "A change of the preparations of the BeyondFacts Lab failed.");
await this.MessageBus.SendError(new(AppIcons.ASSISTANT_BEYOND_FACTS_LAB, TA("AI Studio could not save the change to your preparations. Please try again.")));
await this.ReloadAfterFailureAsync();
}
finally
{
this.isBusy = false;
}
}
/// <summary>
/// Reads the preparations again after a change failed, so the page shows what is stored.
/// </summary>
private async Task ReloadAfterFailureAsync()
{
try
{
await this.ReloadProjectsAsync(null);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
this.Logger.LogError(exception, "The preparations of the BeyondFacts Lab could not be read.");
}
}
/// <summary>
/// Gets the icon of a preparation in the list.
/// </summary>
/// <param name="project">The preparation.</param>
private static string ProjectIcon(BflProjectEntry project) => project switch
{
{ IsAvailable: false } => AppIcons.WARNING,
{ Project.HappenedAtUtc: not null } => AppIcons.EVENT_TOOK_PLACE,
_ => AppIcons.EVENT,
};
/// <summary>
/// Gets the name of a preparation in the list, also when it cannot be read.
/// </summary>
/// <param name="project">The preparation.</param>
private string ProjectDisplayName(BflProjectEntry project) => string.IsNullOrWhiteSpace(project.Name) ? T("Unavailable preparation") : project.Name;
/// <summary>
/// Gets the line below the name of a preparation in the list: when it changed, and whether its event has taken place.
/// </summary>
/// <param name="project">The preparation.</param>
private string ProjectCaption(BflProjectEntry project)
{
var changed = string.Format(Culture, T("Changed on {0}"), project.ModifiedAtUtc.ToLocalTime().ToString("g", Culture));
return project.Project?.HappenedAtUtc is null ? changed : $"{changed} · {T("The event has taken place")}";
}
/// <summary>
/// Gets the short reason why a preparation cannot be opened.
/// </summary>
/// <param name="status">The status of the preparation.</param>
private string ProjectStatusName(BflProjectLoadStatus status) => status switch
{
BflProjectLoadStatus.NEWER_VERSION => T("Requires a newer AI Studio version"),
_ => T("Cannot be opened"),
};
/// <summary>
/// Explains why a preparation cannot be opened.
/// </summary>
/// <param name="status">The status of the preparation.</param>
private string ProjectRecoveryMessage(BflProjectLoadStatus status) => status switch
{
BflProjectLoadStatus.NEWER_VERSION => TA("A newer version of AI Studio stored this preparation. This version cannot open it. Please update AI Studio."),
_ => T("AI Studio cannot read this preparation. Its files may be damaged."),
};
}
@@ -0,0 +1,69 @@
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Settings;
namespace AIStudio.Assistants.BeyondFactsLab;
public partial class BeyondFactsLabAssistant
{
/// <summary>
/// The provider for the chats of the preparation shown, or none.
/// </summary>
private AIStudio.Settings.Provider providerSettings = AIStudio.Settings.Provider.NONE;
/// <summary>
/// Chooses the provider of a preparation as it opens: the one the person chose for it, as long as its confidence
/// is still high enough, otherwise the preselected one.
/// </summary>
/// <param name="project">The preparation, or null when none is shown.</param>
private void ResolveProvider(BflProject? project)
{
this.providerSettings = project is null
? AIStudio.Settings.Provider.NONE
: this.SettingsManager.GetPreselectedProvider(Tools.Components.BEYOND_FACTS_LAB_ASSISTANT, project.ProviderId);
}
/// <summary>
/// Takes over the provider the person chose and remembers it for the preparation.
/// </summary>
/// <param name="provider">The provider.</param>
private async Task SelectProviderAsync(AIStudio.Settings.Provider provider)
{
this.providerSettings = provider;
if (provider == AIStudio.Settings.Provider.NONE || this.ValidateProvider(provider) is not null)
return;
if (this.selectedProject?.Project is not { } project || project.ProviderId == provider.Id)
return;
try
{
this.ReplaceProject(await this.Store.SetProviderAsync(project.ProjectId, provider.Id));
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidDataException)
{
// The choice holds while the page is open; only the next opening falls back to the preselected provider:
this.Logger.LogWarning(exception, "Could not remember the provider of a preparation in the BeyondFacts Lab.");
}
}
/// <summary>
/// Checks whether a provider can run the chats of the lab.
/// </summary>
/// <remarks>
/// The confidence is checked before: the selection offers only providers whose confidence is high enough.
/// </remarks>
/// <param name="provider">The provider.</param>
/// <returns>Why the provider cannot run the chats, or null when it can.</returns>
private string? ValidateProvider(AIStudio.Settings.Provider provider)
{
if (provider.UsedLLMProvider is LLMProviders.NONE)
return TA("Please select a provider.");
var contextWindow = provider.GetModelProfile().Context;
if (!BflModelRequirements.HasEnoughContext(contextWindow))
return string.Format(Culture, TA("The model of this provider reads at most {0} tokens at once. The lab needs at least {1}, because its guide alone takes about 20,000. Please select another provider."), TokenAmount.Format(contextWindow.DefaultTokens, Culture), TokenAmount.Format(BflModelRequirements.MINIMUM_CONTEXT_TOKENS, Culture));
return null;
}
}
@@ -0,0 +1,51 @@
using DialogOptions = AIStudio.Dialogs.DialogOptions;
namespace AIStudio.Assistants.BeyondFactsLab;
public partial class BeyondFactsLabAssistant
{
/// <summary>
/// Opens the dialog with which the person shares the preparation shown with the research team of the lab.
/// </summary>
private Task ShareAsync() => this.ShowShareDialogAsync(false);
/// <summary>
/// Offers to share the preparation once the person confirmed the work state of the last step for the first time,
/// as the lab is done then; confirming it again later asks no more.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
private async Task OfferSharingAsync(Guid projectId)
{
try
{
var workState = await this.Store.LoadWorkStateAsync(projectId, BflStep.RESULTS);
if (workState is not { LastRevision: 1, Confirmed: not null })
return;
}
catch (InvalidDataException exception)
{
this.Logger.LogWarning(exception, "Could not read the work state of the last step of a preparation in the BeyondFacts Lab.");
return;
}
await this.ShowShareDialogAsync(true);
}
/// <summary>
/// Shows the dialog with which the person shares the preparation shown.
/// </summary>
/// <param name="afterCompletion">Whether the lab asks right after the last step, so that it thanks the person first.</param>
private async Task ShowShareDialogAsync(bool afterCompletion)
{
if (this.selectedProject?.Project is not { } project)
return;
var parameters = new DialogParameters<BflShareDialog>
{
{ dialog => dialog.ProjectId, project.ProjectId },
{ dialog => dialog.AfterCompletion, afterCompletion },
};
await this.DialogService.ShowAsync<BflShareDialog>(T("Share with the research team"), parameters, DialogOptions.FULLSCREEN);
}
}
@@ -0,0 +1,223 @@
namespace AIStudio.Assistants.BeyondFactsLab;
public partial class BeyondFactsLabAssistant
{
/// <summary>
/// The forms of the preparation shown, by their steps. A step missing here has a form this version cannot open.
/// </summary>
private Dictionary<BflStep, BflStepFormData> forms = [];
/// <summary>
/// The work states of the preparation shown, by their steps. A step missing here has a work state this version
/// cannot open.
/// </summary>
private Dictionary<BflStep, BflWorkState> workStates = [];
/// <summary>
/// The step shown.
/// </summary>
private BflStep activeStep = BflStep.FRAMEWORK;
/// <summary>
/// Gets the position of the step shown in the stepper, which lists the steps in the order of their values.
/// </summary>
private int ActiveStepIndex => (int)this.activeStep;
/// <summary>
/// Gets a number which changes whenever the person chooses others to simulate in the step "Test situation", whose
/// research the prompt of its conversation carries, so that the conversation counts its tokens anew.
/// </summary>
private int ChatDetailsVersion => this.activeStep is BflStep.TEST_SITUATION && this.forms.GetValueOrDefault(BflStep.TEST_SITUATION)?.Simulation is { } simulation
? HashCode.Combine(simulation.Mode, string.Join('\n', simulation.People))
: 0;
/// <summary>
/// Shows a preparation with its forms, at the step the person looked at last.
/// </summary>
/// <param name="project">The preparation, or null to show none.</param>
private async Task ShowProjectAsync(BflProjectEntry? project)
{
this.selectedProject = project;
this.ResolveProvider(project?.Project);
if (project?.Project is { } openedProject)
{
this.forms = new(await this.Store.LoadFormsAsync(openedProject.ProjectId));
this.workStates = new(await this.Store.LoadWorkStatesAsync(openedProject.ProjectId));
this.activeStep = openedProject.CurrentStep;
}
else
{
this.forms = [];
this.workStates = [];
this.activeStep = BflStep.FRAMEWORK;
}
}
/// <summary>
/// Shows the new time of change of a preparation after a work state or a result of it was stored.
/// </summary>
/// <param name="project">The preparation with its new time of change.</param>
private Task ProjectStoredAsync(BflProject project)
{
this.ReplaceProject(project);
return Task.CompletedTask;
}
/// <summary>
/// Starts the research once the person confirmed the event details, on every topic without one and on every topic
/// whose public details changed since, and tells the person. Once the person confirmed the last step for the first
/// time, the lab offers to share the preparation with its research team instead.
/// </summary>
/// <remarks>
/// Nothing starts for an event which is not public, nor while the work state suggests whether the event is public
/// and the person has not decided yet; the person hears why. Taking over the suggestion changes the details, so
/// that the person confirms the work state again, and the research starts then if the event is public.
/// </remarks>
/// <param name="step">The step whose work state the person confirmed.</param>
private async Task WorkStateConfirmedAsync(BflStep step)
{
if (step is BflStep.RESULTS && this.selectedProject?.Project is { } finishedProject)
{
await this.OfferSharingAsync(finishedProject.ProjectId);
return;
}
if (step is not BflStep.FRAMEWORK || this.selectedProject?.Project is not { } project || this.ValidateProvider(this.providerSettings) is not null)
return;
if (BflEventVisibility.IsNotPublic(this.forms))
{
await this.MessageBus.SendInfo(new(AppIcons.NOT_PUBLIC, BflEventVisibility.NotPublicMessage));
return;
}
if (BflEventVisibility.IsSuggestionPending(this.workStates, this.forms))
{
await this.MessageBus.SendInfo(new(AppIcons.WEB_RESEARCH, string.Format(TA("The lab has not started the research on the web yet. First, decide on the suggestion below the work state whether the event is public. Afterward, you can start the research in the step '{0}'."), BflStep.STRATEGY.Title)));
return;
}
var started = await this.ResearchRunner.StartWhenDueAsync(project.ProjectId, this.providerSettings, this.forms);
if (started.Count > 0)
await this.MessageBus.SendInfo(new(AppIcons.WEB_RESEARCH, string.Format(TA("The lab now researches the event on the web, with the public details about it only. You find the result in the step '{0}'."), BflStep.STRATEGY.Title)));
}
/// <summary>
/// Reads the work states of the preparation shown again once the generator started, ended, or stored a draft.
/// </summary>
/// <param name="location">The step whose work state changed.</param>
private Task OnWorkStateChangedAsync(BflStepThreadLocation location)
{
if (this.selectedProject?.ProjectId != location.ProjectId)
return Task.CompletedTask;
return this.InvokeAsync(async () =>
{
this.workStates = new(await this.Store.LoadWorkStatesAsync(location.ProjectId));
if (await this.Store.LoadAsync(location.ProjectId) is { } project)
this.ReplaceProject(project);
this.StateHasChanged();
});
}
/// <summary>
/// Shows the step the person chose in the stepper, and remembers it for the next time.
/// </summary>
/// <param name="index">The position of the step in the stepper.</param>
private async Task SelectStepAsync(int index)
{
var steps = BflStep.All;
if (index < 0 || index >= steps.Count || steps[index] == this.activeStep)
return;
this.activeStep = steps[index];
this.scrollToActiveStep = true;
if (this.selectedProject?.Project is not { } project)
return;
try
{
this.ReplaceProject(await this.Store.SetCurrentStepAsync(project.ProjectId, this.activeStep));
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidDataException)
{
// Only the step to open next time is lost, which is not worth bothering the person with:
this.Logger.LogWarning(exception, "Could not remember the step shown last in the BeyondFacts Lab.");
}
}
/// <summary>
/// Stores the form of a step after the person changed a value.
/// </summary>
/// <remarks>
/// Unlike the other changes, saving leaves the page usable: the fields stay enabled, so that the next field
/// keeps the focus while the previous one is stored.
/// </remarks>
/// <param name="step">The step.</param>
private async Task SaveFormAsync(BflStep step)
{
if (this.selectedProject?.Project is not { } project || !this.forms.TryGetValue(step, out var form))
return;
try
{
this.ReplaceProject(await this.Store.SaveFormAsync(project.ProjectId, step, form));
if (BflMissingDetails.StepsOf(this.forms).Count > 0)
this.projectsWithMissingDetails.Add(project.ProjectId);
else
this.projectsWithMissingDetails.Remove(project.ProjectId);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidDataException)
{
this.Logger.LogError(exception, "Could not save the details of a step in the BeyondFacts Lab.");
await this.MessageBus.SendError(new(AppIcons.ASSISTANT_BEYOND_FACTS_LAB, TA("AI Studio could not save your details. Please try again.")));
}
}
/// <summary>
/// Puts a preparation the store just wrote into the list, without reading the list again.
/// </summary>
/// <param name="project">The preparation.</param>
private void ReplaceProject(BflProject project)
{
var entry = BflProjectEntry.FromProject(project);
this.projects = [.. this.projects.Select(candidate => candidate.ProjectId == project.ProjectId ? entry : candidate).OrderByDescending(candidate => candidate.ModifiedAtUtc)];
if (this.selectedProject?.ProjectId == project.ProjectId)
this.selectedProject = entry;
}
/// <summary>
/// Gets the line below the title of a step in the stepper.
/// </summary>
/// <param name="step">The step.</param>
private string StepSecondaryText(BflStep step)
{
if (!this.forms.TryGetValue(step, out var form))
return T("Cannot be opened");
var notes = new List<string>(2);
if (BflMissingDetails.Of(step, form).Count > 0)
notes.Add(T("Details missing"));
switch (BflStaleness.Of(step, this.workStates, this.forms))
{
case BflWorkStateStatus.OUTDATED:
notes.Add(T("Outdated"));
break;
case BflWorkStateStatus.DETAILS_CHANGED:
notes.Add(T("Details changed"));
break;
}
return string.Join(" · ", notes);
}
/// <summary>
/// Tells whether the stepper shows a step as done: the person confirmed its work state, and no earlier step changed
/// since.
/// </summary>
/// <param name="step">The step.</param>
private bool IsStepCompleted(BflStep step) => BflStaleness.Of(step, this.workStates, this.forms) is BflWorkStateStatus.CONFIRMED or BflWorkStateStatus.DETAILS_CHANGED;
}
@@ -0,0 +1,224 @@
using AIStudio.Components;
using AIStudio.Dialogs.Settings;
using Microsoft.AspNetCore.Components;
using DialogOptions = AIStudio.Dialogs.DialogOptions;
namespace AIStudio.Assistants.BeyondFactsLab;
/// <summary>
/// The page of the BeyondFacts Lab, which guides researchers through the preparation of a challenging appearance.
/// </summary>
/// <remarks>
/// The lab keeps several preparations, each with steps of their own, so it does not inherit AssistantBase,
/// which knows one input and one result. Like the Visual Briefing assistant, it checks by itself whether it
/// may be opened.
/// </remarks>
public partial class BeyondFactsLabAssistant : MSGComponentBase
{
[Inject]
private IDialogService DialogService { get; init; } = null!;
[Inject]
private NavigationManager NavigationManager { get; init; } = null!;
[Inject]
private BeyondFactsLabStore Store { get; init; } = null!;
[Inject]
private BflConversationService ConversationService { get; init; } = null!;
[Inject]
private BflMaterialService MaterialService { get; init; } = null!;
[Inject]
private BflWorkStateGenerator WorkStateGenerator { get; init; } = null!;
[Inject]
private ILogger<BeyondFactsLabAssistant> Logger { get; init; } = null!;
[Inject]
private IJSRuntime JsRuntime { get; init; } = null!;
[Inject]
private BflResearchRunner ResearchRunner { get; init; } = null!;
/// <summary>
/// Whether the person may open the lab, so that the page did not send them away.
/// </summary>
private bool mayOpen;
/// <summary>
/// The empty element right before the header of the preparation, which marks where the header sits in the flow.
/// </summary>
private ElementReference stickyHeaderAnchor;
/// <summary>
/// The header of the preparation, which stays at the top while the person scrolls.
/// </summary>
private ElementReference stickyHeader;
/// <summary>
/// The ID of the header element whose height the page follows, so that only a new header element needs following.
/// </summary>
private string? followedStickyHeaderId;
/// <summary>
/// Whether the next render shows another step, which then starts at the top.
/// </summary>
private bool scrollToActiveStep;
/// <summary>
/// Whether the area which tells how to work with the lab is open.
/// </summary>
private bool introductionExpanded;
/// <summary>
/// Whether the area with the guidelines of the organization is open. It opens with every visit of the page, so
/// that the person has them in view while preparing.
/// </summary>
private bool organizationRulesExpanded = true;
/// <summary>
/// Gets the guidelines of the organization for public appearances, which only a configuration plugin sets; empty
/// without any.
/// </summary>
/// <remarks>
/// Read anew with every render, so that a reloaded configuration plugin shows right away.
/// </remarks>
private string OrganizationRules => this.SettingsManager.ConfigurationData.BeyondFactsLab.OrganizationRules;
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
if (!BflAccess.CanOpen(this.SettingsManager, T("BeyondFacts Lab")))
{
this.NavigationManager.NavigateTo(Routes.ASSISTANTS);
return;
}
this.ApplyFilters([], [Event.CONFIGURATION_CHANGED]);
this.MaterialService.MaterialsChanged += this.OnMaterialsChangedAsync;
this.WorkStateGenerator.WorkStateChanged += this.OnWorkStateChangedAsync;
this.mayOpen = true;
await this.RunStoreActionAsync(() => this.ReloadProjectsAsync(null));
// Whoever has no preparation yet needs to know how the lab works first:
this.introductionExpanded = this.projects.Count is 0;
}
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (this.scrollToActiveStep)
{
// The person scrolled down in one step and chose another one; it starts right under the header:
this.scrollToActiveStep = false;
await this.stickyHeaderAnchor.ScrollToStickyHeaderAsync(this.JsRuntime);
}
//
// The material sticks right below the header, so the page has to know how tall the header is. Opening a
// preparation after none, or after one which is unavailable, renders a new header element:
//
if (this.stickyHeader.Id is { } headerId && headerId != this.followedStickyHeaderId)
{
this.followedStickyHeaderId = headerId;
await this.stickyHeader.FollowStickyHeaderAsync(this.JsRuntime);
}
if (firstRender && this.mayOpen)
await this.ShowNoticeIfNeededAsync();
}
/// <summary>
/// Shows the notes of the lab, unless the person confirmed them as they are now.
/// </summary>
private async Task ShowNoticeIfNeededAsync()
{
var notice = BflNotice.Text;
var currentHash = BflNotice.ComputeHash(notice);
if (BflNotice.IsAccepted(this.SettingsManager.ConfigurationData.BeyondFactsLab.AcceptedNoticeHash, currentHash))
return;
var parameters = new DialogParameters<BflNoticeDialog> { { dialog => dialog.Notice, notice } };
var reference = await this.DialogService.ShowAsync<BflNoticeDialog>(T("BeyondFacts Lab"), parameters, DialogOptions.BLOCKING_FULLSCREEN);
var result = await reference.Result;
if (result is null || result.Canceled)
return;
this.SettingsManager.ConfigurationData.BeyondFactsLab.AcceptedNoticeHash = currentHash;
await this.SettingsManager.StoreSettings();
}
/// <inheritdoc />
protected override async Task ProcessIncomingMessage<T>(ComponentBase? sendingComponent, Event triggeredEvent, T? data) where T : default
{
if (triggeredEvent is Event.CONFIGURATION_CHANGED)
{
// An organization may hide the lab, or the person may switch its preview feature off, while the page is open:
if (!BflAccess.CanOpen(this.SettingsManager))
{
this.NavigationManager.NavigateTo(Routes.ASSISTANTS);
return;
}
// A changed option, such as the form of address in the options of the lab, shows right away:
this.StateHasChanged();
}
await base.ProcessIncomingMessage(sendingComponent, triggeredEvent, data);
}
/// <inheritdoc />
protected override void DisposeResources()
{
this.MaterialService.MaterialsChanged -= this.OnMaterialsChangedAsync;
this.WorkStateGenerator.WorkStateChanged -= this.OnWorkStateChangedAsync;
base.DisposeResources();
}
/// <summary>
/// Shows a preparation as changed once its material changed: material is work on the preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation whose material changed.</param>
private Task OnMaterialsChangedAsync(Guid projectId)
{
if (this.projects.All(project => project.ProjectId != projectId))
return Task.CompletedTask;
return this.InvokeAsync(async () =>
{
if (await this.Store.LoadAsync(projectId) is not { } project)
return;
this.ReplaceProject(project);
this.StateHasChanged();
});
}
/// <summary>
/// Remembers whether the person opened or closed the area which tells how to work with the lab.
/// </summary>
/// <param name="isExpanded">Whether the area is open now.</param>
private Task IntroductionExpandedChanged(bool isExpanded)
{
this.introductionExpanded = isExpanded;
return Task.CompletedTask;
}
/// <summary>
/// Remembers whether the person opened or closed the area with the guidelines of the organization.
/// </summary>
/// <param name="isExpanded">Whether the area is open now.</param>
private Task OrganizationRulesExpandedChanged(bool isExpanded)
{
this.organizationRulesExpanded = isExpanded;
return Task.CompletedTask;
}
private async Task OpenSettingsDialogAsync() => await this.DialogService.ShowAsync<SettingsDialogBeyondFactsLab>(null, new DialogParameters(), DialogOptions.FULLSCREEN);
}
@@ -0,0 +1,18 @@
/*
* Beside the step, which the grid allows from the breakpoint lg of MudBlazor on, the material stays in view right
* below the sticky header while the person scrolls through the conversation of the step. A long list of material
* scrolls on its own, so that its end stays reachable. The variables come from followStickyHeader in app.js. On a
* narrower window, the material stands below the step and scrolls with the page.
*
* The space above the material keeps its border clear of the header while it sticks, and lines it up with the title
* of the step beside it.
*/
@media (min-width: 1280px) {
.bfl-material-column {
position: sticky;
top: var(--sticky-header-height, 0px);
max-height: var(--sticky-space-below-header, none);
overflow-y: auto;
padding-top: 8px;
}
}
@@ -0,0 +1,31 @@
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace AIStudio.Assistants.BeyondFactsLab;
/// <summary>
/// The JSON options of the files of the BeyondFacts Lab.
/// </summary>
internal static class BeyondFactsLabJson
{
/// <summary>
/// The options with which the lab writes and reads its files.
/// </summary>
/// <remarks>
/// The files stay readable for people who look into the data folder: indented, enums by name, and umlauts
/// as they are rather than as escapes. The relaxed encoder is fine here, because nothing embeds these files
/// into HTML. A field this version does not know makes a file unreadable rather than letting a save drop
/// it; such a preparation is listed as one of a newer version or as unavailable, and nothing writes it.
/// </remarks>
internal static readonly JsonSerializerOptions PERSISTENCE = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = false,
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
Converters = { new JsonStringEnumConverter() },
TypeInfoResolver = BeyondFactsLabJsonContext.Default,
}.AsReadOnly();
}
@@ -0,0 +1,23 @@
using System.Text.Json.Serialization;
namespace AIStudio.Assistants.BeyondFactsLab;
/// <summary>
/// The contracts with which System.Text.Json reads and writes the files of the BeyondFacts Lab, built at compile time.
/// </summary>
[JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(BflProject))]
[JsonSerializable(typeof(BflStepFormData))]
[JsonSerializable(typeof(BflMaterial))]
[JsonSerializable(typeof(BflWorkState))]
[JsonSerializable(typeof(BflResult))]
[JsonSerializable(typeof(BflResearch))]
[JsonSerializable(typeof(BflPersonResearch))]
[JsonSerializable(typeof(BflParticipantSelection))]
// The value deck, which comes with the app:
[JsonSerializable(typeof(BflValueDeck))]
// The preparation selected last:
[JsonSerializable(typeof(Guid?))]
internal sealed partial class BeyondFactsLabJsonContext : JsonSerializerContext;
@@ -0,0 +1,147 @@
using System.Text.Json;
namespace AIStudio.Assistants.BeyondFactsLab;
public sealed partial class BeyondFactsLabStore
{
/// <summary>
/// The folder of a preparation which holds a folder for each step.
/// </summary>
private const string STEPS_DIRECTORY_NAME = "steps";
/// <summary>
/// The file of a step which holds its form "Your details".
/// </summary>
private const string FORM_FILE_NAME = "form.json";
/// <summary>
/// Loads the form of a step.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="step">The step.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The form, or an empty one when the person entered nothing yet.</returns>
/// <exception cref="InvalidDataException">This version cannot open the form.</exception>
public async Task<BflStepFormData> LoadFormAsync(Guid projectId, BflStep step, CancellationToken token = default)
{
await this.InitializeAsync(token);
return await this.LoadFormWithoutInitializeAsync(projectId, step, token);
}
/// <summary>
/// Loads the forms of every step of a preparation, e.g., to find missing details.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The forms this version can open, by their steps.</returns>
public async Task<IReadOnlyDictionary<BflStep, BflStepFormData>> LoadFormsAsync(Guid projectId, CancellationToken token = default)
{
await this.InitializeAsync(token);
var forms = new Dictionary<BflStep, BflStepFormData>();
foreach (var step in BflStep.All)
{
try
{
forms[step] = await this.LoadFormWithoutInitializeAsync(projectId, step, token);
}
catch (InvalidDataException exception)
{
logger.LogWarning(exception, "Could not open the form of the step '{Step}' of the preparation '{ProjectId}' of the BeyondFacts Lab.", step, projectId);
}
}
return forms;
}
/// <summary>
/// Stores the form of a step and counts it as a change of the preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="step">The step.</param>
/// <param name="form">The form.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The preparation with its new time of change.</returns>
/// <exception cref="FileNotFoundException">The preparation does not exist.</exception>
/// <exception cref="InvalidDataException">This version cannot open the preparation or the stored form, so it does not write them either.</exception>
public async Task<BflProject> SaveFormAsync(Guid projectId, BflStep step, BflStepFormData form, CancellationToken token = default)
{
await this.InitializeAsync(token);
var gate = this.GetLock(projectId);
await gate.WaitAsync(token);
try
{
var project = await this.LoadRequiredWithoutInitializeAsync(projectId, token);
// A form which a newer version stored, or which is damaged, stays as it is:
await this.LoadFormWithoutInitializeAsync(projectId, step, token);
form.SchemaVersion = BflStepFormData.CURRENT_SCHEMA_VERSION;
await WriteTextAtomicAsync(this.FormPath(projectId, step), JsonSerializer.Serialize(form, JSON_OPTIONS), token);
project.ModifiedAtUtc = DateTimeOffset.UtcNow;
await this.StoreProjectAsync(project, token);
return project;
}
finally
{
gate.Release();
}
}
/// <summary>
/// Reads the form of a step without the first start of the store.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="step">The step.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The form, or an empty one when there is no file.</returns>
/// <exception cref="InvalidDataException">This version cannot open the form.</exception>
private async Task<BflStepFormData> LoadFormWithoutInitializeAsync(Guid projectId, BflStep step, CancellationToken token)
{
var path = this.FormPath(projectId, step);
if (!File.Exists(path))
return new BflStepFormData();
BflStepFormData? form;
try
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65_536, true);
form = await JsonSerializer.DeserializeAsync<BflStepFormData>(stream, JSON_OPTIONS, token);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException)
{
throw new InvalidDataException("This version of AI Studio cannot open the form.", exception);
}
if (form is null || form.SchemaVersion is < 1 or > BflStepFormData.CURRENT_SCHEMA_VERSION || IsNull(form.Values) || form.CardSort is { } cardSort && IsBroken(cardSort) || form.Simulation is { } simulation && IsBroken(simulation))
throw new InvalidDataException("This version of AI Studio cannot open the form.");
return form;
}
/// <summary>
/// Tells whether a stored simulation lacks one of its parts, which JSON can make null, or names a mode this version
/// does not know.
/// </summary>
/// <param name="simulation">The simulation.</param>
private static bool IsBroken(BflSimulation simulation) => !Enum.IsDefined(simulation.Mode) || IsNull(simulation.People) || simulation.People.Any(IsNull);
/// <summary>
/// Tells whether a stored card sort lacks one of its parts, which JSON can make null.
/// </summary>
/// <param name="cardSort">The card sort.</param>
private static bool IsBroken(BflCardSort cardSort) => IsNull(cardSort.Categories) || IsNull(cardSort.OwnValues) || IsNull(cardSort.Focus) || cardSort.Focus.Any(IsNull) || cardSort.OwnValues.Any(value => IsNull(value) || IsNull(value.Id) || IsNull(value.Name) || IsNull(value.Definition));
/// <summary>
/// Gets the file of the form of a step.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="step">The step.</param>
private string FormPath(Guid projectId, BflStep step) => Path.Combine(this.ProjectDirectory(projectId), STEPS_DIRECTORY_NAME, step.FolderName, FORM_FILE_NAME);
/// <summary>
/// Checks for null a value which the type system says cannot be null, but which JSON can make null.
/// </summary>
/// <param name="value">The value.</param>
private static bool IsNull<T>(T? value) => value is null;
}
@@ -0,0 +1,381 @@
using System.Text;
using System.Text.Json;
namespace AIStudio.Assistants.BeyondFactsLab;
public sealed partial class BeyondFactsLabStore
{
/// <summary>
/// The folder of a preparation which holds its materials.
/// </summary>
private const string MATERIALS_DIRECTORY_NAME = "materials";
/// <summary>
/// The extension of the file which describes a material.
/// </summary>
private const string MATERIAL_FILE_EXTENSION = ".json";
/// <summary>
/// The extension of the file which holds the text of a material.
/// </summary>
private const string MATERIAL_TEXT_FILE_EXTENSION = ".md";
/// <summary>
/// How many characters a read of the text of a material takes at once.
/// </summary>
private const int MATERIAL_TEXT_READ_BLOCK = 65_536;
/// <summary>
/// Lists the materials of a preparation, also those this version cannot open, in the order the person added them.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The materials; those this version cannot open come last.</returns>
public async Task<IReadOnlyList<BflMaterialEntry>> ListMaterialsAsync(Guid projectId, CancellationToken token = default)
{
await this.InitializeAsync(token);
return await this.ListMaterialsWithoutInitializeAsync(projectId, token);
}
/// <summary>
/// Adds a document or a recording to a preparation, unless it has a material with the same content already, and
/// counts that as a change of the preparation.
/// </summary>
/// <remarks>
/// The store gives the material its ID, the time it was added, and the length of its text. It keeps only the
/// name of the file, never a path, even when the name passed contains one.
/// </remarks>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="material">What the lab knows about the file: its kind, name, size, hash, and how it was read.</param>
/// <param name="text">The text of the document or the transcript of the recording, after the prompt injection filter.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The new material, or the one with the same content which the preparation had already.</returns>
/// <exception cref="ArgumentException">The name, the hash, or the text is empty, or the material is an image.</exception>
/// <exception cref="FileNotFoundException">The preparation does not exist.</exception>
/// <exception cref="InvalidDataException">This version cannot open the preparation, so it does not write it either.</exception>
public Task<BflMaterialAddition> AddMaterialAsync(Guid projectId, BflMaterial material, string text, CancellationToken token = default)
{
if (material.Kind is not (BflMaterialKind.DOCUMENT or BflMaterialKind.RECORDING) || material.Image is not null)
throw new ArgumentException("Only a document or a recording has a text; an image needs AddImageMaterialAsync.", nameof(material));
if (string.IsNullOrWhiteSpace(text))
throw new ArgumentException("A material needs a text.", nameof(text));
return this.AddAsync(projectId, material, text.Length, (stored, writeToken) => WriteTextAtomicAsync(this.MaterialTextPath(projectId, stored.MaterialId), text, writeToken), token);
}
/// <summary>
/// Adds an image to a preparation, unless it has a material with the same content already, and counts that as a
/// change of the preparation.
/// </summary>
/// <remarks>
/// The store gives the material its ID and the time it was added. It keeps only the name of the file, never a
/// path, even when the name passed contains one.
/// </remarks>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="material">What the lab knows about the file: its name, size, hash, and the description of the copy.</param>
/// <param name="image">The copy of the image, prepared for models.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The new material, or the one with the same content which the preparation had already.</returns>
/// <exception cref="ArgumentException">The name, the hash, or the copy is empty, or the material is no image.</exception>
/// <exception cref="FileNotFoundException">The preparation does not exist.</exception>
/// <exception cref="InvalidDataException">This version cannot open the preparation, so it does not write it either.</exception>
public Task<BflMaterialAddition> AddImageMaterialAsync(Guid projectId, BflMaterial material, ReadOnlyMemory<byte> image, CancellationToken token = default)
{
if (material.Kind is not BflMaterialKind.IMAGE || !BflMaterialImage.IsValid(material.Image))
throw new ArgumentException("An image material needs the description of its copy.", nameof(material));
if (image.IsEmpty)
throw new ArgumentException("An image material needs its copy.", nameof(image));
return this.AddAsync(projectId, material, 0, (stored, writeToken) => WriteBytesAtomicAsync(this.MaterialImagePath(projectId, stored.MaterialId, stored.Image!.Extension), image, writeToken), token);
}
/// <summary>
/// Gets the copy of an image which the lab keeps as material.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="material">The material, an image.</param>
/// <returns>The path of the copy.</returns>
/// <exception cref="ArgumentException">The material is no image.</exception>
public string MaterialImagePath(Guid projectId, BflMaterial material)
{
if (material.Kind is not BflMaterialKind.IMAGE || !BflMaterialImage.IsValid(material.Image))
throw new ArgumentException("Only an image material has a copy of an image.", nameof(material));
return this.MaterialImagePath(projectId, material.MaterialId, material.Image!.Extension);
}
/// <summary>
/// Adds a material to a preparation, unless it has one with the same content already.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="material">What the lab knows about the file.</param>
/// <param name="textLength">How many characters the text of the material has; 0 for an image.</param>
/// <param name="writeContent">Writes the text or the copy of the image for the stored material.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The new material, or the one with the same content which the preparation had already.</returns>
private async Task<BflMaterialAddition> AddAsync(Guid projectId, BflMaterial material, int textLength, Func<BflMaterial, CancellationToken, Task> writeContent, CancellationToken token)
{
var name = MaterialName(material.Name);
if (name.Length is 0)
throw new ArgumentException("A material needs a name.", nameof(material));
if (string.IsNullOrWhiteSpace(material.SourceHash))
throw new ArgumentException("A material needs the hash of its file.", nameof(material));
await this.InitializeAsync(token);
var gate = this.GetLock(projectId);
await gate.WaitAsync(token);
try
{
var project = await this.LoadRequiredWithoutInitializeAsync(projectId, token);
var existing = await this.ListMaterialsWithoutInitializeAsync(projectId, token);
if (existing.FirstOrDefault(entry => string.Equals(entry.Material?.SourceHash, material.SourceHash, StringComparison.OrdinalIgnoreCase))?.Material is { } duplicate)
return new(duplicate, IsDuplicate: true);
var stored = new BflMaterial
{
MaterialId = Guid.NewGuid(),
Name = name,
Kind = material.Kind,
Image = material.Image is { } image ? new() { Extension = image.Extension, Width = image.Width, Height = image.Height } : null,
AddedAtUtc = DateTimeOffset.UtcNow,
SourceBytes = Math.Max(0, material.SourceBytes),
SourceHash = material.SourceHash.ToLowerInvariant(),
TextLength = textLength,
IsIncomplete = material.IsIncomplete,
IsShortened = material.IsShortened,
FailedPages = [.. material.FailedPages],
FilteredPassages = Math.Max(0, material.FilteredPassages),
};
// The content comes first: a material whose description exists always has its content, even after a crash in between.
await writeContent(stored, token);
await WriteTextAtomicAsync(this.MaterialPath(projectId, stored.MaterialId), JsonSerializer.Serialize(stored, JSON_OPTIONS), token);
project.ModifiedAtUtc = DateTimeOffset.UtcNow;
await this.StoreProjectAsync(project, token);
return new(stored, IsDuplicate: false);
}
finally
{
gate.Release();
}
}
/// <summary>
/// Deletes a material of a preparation, also when this version cannot open it, and counts that as a change of the
/// preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="materialId">The ID of the material.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The preparation with its new time of change.</returns>
/// <exception cref="FileNotFoundException">The preparation does not exist.</exception>
/// <exception cref="InvalidDataException">This version cannot open the preparation, so it does not write it either.</exception>
public async Task<BflProject> DeleteMaterialAsync(Guid projectId, Guid materialId, CancellationToken token = default)
{
await this.InitializeAsync(token);
var gate = this.GetLock(projectId);
await gate.WaitAsync(token);
try
{
var project = await this.LoadRequiredWithoutInitializeAsync(projectId, token);
// The description goes first: content left behind by a crash in between belongs to no material and is never read.
DeleteIfExists(this.MaterialPath(projectId, materialId));
DeleteIfExists(this.MaterialTextPath(projectId, materialId));
// Also when the description is damaged, every copy of an image goes with it:
foreach (var extension in BflMaterialImage.EXTENSIONS)
DeleteIfExists(this.MaterialImagePath(projectId, materialId, extension));
project.ModifiedAtUtc = DateTimeOffset.UtcNow;
await this.StoreProjectAsync(project, token);
return project;
}
finally
{
gate.Release();
}
static void DeleteIfExists(string path)
{
if (File.Exists(path))
File.Delete(path);
}
}
/// <summary>
/// Reads the beginning of the text of a material, at most as many characters as given.
/// </summary>
/// <remarks>
/// Only what a prompt takes is read, never more: a long document would otherwise lie in memory as a whole with
/// every request.
/// </remarks>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="materialId">The ID of the material.</param>
/// <param name="maxCharacters">How many characters to read at most.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The beginning of the text; the whole text when it is not longer.</returns>
/// <exception cref="InvalidDataException">The text cannot be read, e.g., because the person deleted the material meanwhile.</exception>
public async Task<string> ReadMaterialTextAsync(Guid projectId, Guid materialId, int maxCharacters, CancellationToken token = default)
{
if (maxCharacters <= 0)
return string.Empty;
await this.InitializeAsync(token);
try
{
await using var stream = new FileStream(this.MaterialTextPath(projectId, materialId), FileMode.Open, FileAccess.Read, FileShare.Read, 65_536, true);
using var reader = new StreamReader(stream, new UTF8Encoding(false));
var buffer = new char[Math.Min(maxCharacters, MATERIAL_TEXT_READ_BLOCK)];
var text = new StringBuilder();
while (text.Length < maxCharacters)
{
var read = await reader.ReadAsync(buffer.AsMemory(0, Math.Min(buffer.Length, maxCharacters - text.Length)), token);
if (read is 0)
break;
text.Append(buffer, 0, read);
}
return text.ToString();
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
throw new InvalidDataException("AI Studio cannot read the text of the material.", exception);
}
}
/// <summary>
/// Lists the materials of a preparation without the first start of the store.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">The cancellation token.</param>
private async Task<IReadOnlyList<BflMaterialEntry>> ListMaterialsWithoutInitializeAsync(Guid projectId, CancellationToken token)
{
var directory = this.MaterialsDirectory(projectId);
if (!Directory.Exists(directory))
return [];
List<BflMaterialEntry> materials = [];
foreach (var path in Directory.EnumerateFiles(directory, $"*{MATERIAL_FILE_EXTENSION}"))
{
token.ThrowIfCancellationRequested();
if (!Guid.TryParseExact(Path.GetFileNameWithoutExtension(path), "D", out var materialId))
continue;
materials.Add(new(materialId, await this.LoadMaterialAsync(projectId, materialId, path, token)));
}
return
[
.. materials
.OrderBy(entry => entry.IsAvailable ? 0 : 1)
.ThenBy(entry => entry.Material?.AddedAtUtc ?? DateTimeOffset.MaxValue)
.ThenBy(entry => entry.MaterialId)
];
}
/// <summary>
/// Reads the description of a material.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="materialId">The ID the file names.</param>
/// <param name="path">The file of the description.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The material, or null when it is damaged, has no content, or a newer version stored it.</returns>
private async Task<BflMaterial?> LoadMaterialAsync(Guid projectId, Guid materialId, string path, CancellationToken token)
{
try
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65_536, true);
var material = await JsonSerializer.DeserializeAsync<BflMaterial>(stream, JSON_OPTIONS, token);
if (material is not null && IsValidMaterial(material, materialId) && File.Exists(this.MaterialContentPath(projectId, material)))
return material;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException)
{
logger.LogWarning(exception, "Could not open the material '{MaterialId}' of the preparation '{ProjectId}' of the BeyondFacts Lab.", materialId, projectId);
return null;
}
logger.LogWarning("The material '{MaterialId}' of the preparation '{ProjectId}' of the BeyondFacts Lab is not valid, or its content is missing.", materialId, projectId);
return null;
}
/// <summary>
/// Checks a material which was read from a file.
/// </summary>
/// <param name="material">The material.</param>
/// <param name="expectedMaterialId">The ID its file names.</param>
private static bool IsValidMaterial(BflMaterial material, Guid expectedMaterialId) =>
material.SchemaVersion is >= 1 and <= BflMaterial.CURRENT_SCHEMA_VERSION &&
material.MaterialId == expectedMaterialId &&
!string.IsNullOrWhiteSpace(material.Name) &&
!string.IsNullOrWhiteSpace(material.SourceHash) &&
material is { SourceBytes: >= 0, TextLength: >= 0, FilteredPassages: >= 0 } &&
!IsNull(material.FailedPages) &&
material.Kind switch
{
BflMaterialKind.DOCUMENT or BflMaterialKind.RECORDING => material.Image is null,
BflMaterialKind.IMAGE => BflMaterialImage.IsValid(material.Image),
_ => false,
};
/// <summary>
/// Gets the name under which the lab keeps a document: its file name without any folder, cleaned like the name of
/// a preparation.
/// </summary>
/// <remarks>
/// Both kinds of separators count, whatever the system: a path from Windows on a Mac still names its folders.
/// </remarks>
/// <param name="name">The name of the document, possibly with a path.</param>
/// <returns>The cleaned name, empty when nothing remains.</returns>
internal static string MaterialName(string? name)
{
if (string.IsNullOrWhiteSpace(name))
return string.Empty;
return SanitizeName(name[(name.LastIndexOfAny(['/', '\\']) + 1)..]);
}
/// <summary>
/// Gets the folder of the materials of a preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
private string MaterialsDirectory(Guid projectId) => Path.Combine(this.ProjectDirectory(projectId), MATERIALS_DIRECTORY_NAME);
/// <summary>
/// Gets the file which describes a material.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="materialId">The ID of the material.</param>
private string MaterialPath(Guid projectId, Guid materialId) => Path.Combine(this.MaterialsDirectory(projectId), $"{materialId:D}{MATERIAL_FILE_EXTENSION}");
/// <summary>
/// Gets the file which holds the text of a material.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="materialId">The ID of the material.</param>
private string MaterialTextPath(Guid projectId, Guid materialId) => Path.Combine(this.MaterialsDirectory(projectId), $"{materialId:D}{MATERIAL_TEXT_FILE_EXTENSION}");
/// <summary>
/// Gets the file which holds the copy of an image.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="materialId">The ID of the material.</param>
/// <param name="extension">The file extension of the copy, without the dot.</param>
private string MaterialImagePath(Guid projectId, Guid materialId, string extension) => Path.Combine(this.MaterialsDirectory(projectId), $"{materialId:D}.{extension}");
/// <summary>
/// Gets the file which holds the content of a material: its text, or the copy of an image.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="material">A valid material.</param>
private string MaterialContentPath(Guid projectId, BflMaterial material) => material.Kind is BflMaterialKind.IMAGE
? this.MaterialImagePath(projectId, material)
: this.MaterialTextPath(projectId, material.MaterialId);
}
@@ -0,0 +1,234 @@
using System.Text.Json;
namespace AIStudio.Assistants.BeyondFactsLab;
public sealed partial class BeyondFactsLabStore
{
/// <summary>
/// The folder below the research of the step "Strategy" which holds the research on single people.
/// </summary>
private const string PERSON_RESEARCH_DIRECTORY_NAME = "participants";
/// <summary>
/// The file below the research of the step "Strategy" which holds whom of the list of participants the lab
/// researches in depth.
/// </summary>
private const string PARTICIPANT_SELECTION_FILE_NAME = "participant-selection.json";
/// <summary>
/// Loads whom of the list of participants of a preparation the lab researches in depth.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">Cancels the loading.</param>
/// <returns>The selection, or null when nobody chose yet.</returns>
/// <exception cref="InvalidDataException">The selection is damaged, or a newer version of AI Studio stored it.</exception>
public async Task<BflParticipantSelection?> LoadParticipantSelectionAsync(Guid projectId, CancellationToken token = default)
{
await this.InitializeAsync(token);
return await this.LoadParticipantSelectionWithoutInitializeAsync(projectId, token);
}
/// <summary>
/// Stores whom of the list of participants of a preparation the lab researches in depth, in place of the earlier
/// selection.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="selection">The selection.</param>
/// <param name="token">Cancels the storing.</param>
/// <returns>The preparation, with the time of its last change.</returns>
/// <exception cref="FileNotFoundException">The preparation does not exist.</exception>
/// <exception cref="InvalidDataException">The earlier selection is damaged, or a newer version of AI Studio stored it; it stays as it is.</exception>
public async Task<BflProject> SaveParticipantSelectionAsync(Guid projectId, BflParticipantSelection selection, CancellationToken token = default)
{
await this.InitializeAsync(token);
var gate = this.GetLock(projectId);
await gate.WaitAsync(token);
try
{
var project = await this.LoadRequiredWithoutInitializeAsync(projectId, token);
// A selection which a newer version stored, or which is damaged, stays as it is:
await this.LoadParticipantSelectionWithoutInitializeAsync(projectId, token);
selection.SchemaVersion = BflParticipantSelection.CURRENT_SCHEMA_VERSION;
await WriteTextAtomicAsync(this.ParticipantSelectionPath(projectId), JsonSerializer.Serialize(selection, JSON_OPTIONS), token);
project.ModifiedAtUtc = DateTimeOffset.UtcNow;
await this.StoreProjectAsync(project, token);
return project;
}
finally
{
gate.Release();
}
}
/// <summary>
/// Loads the research on one person of a preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="name">The name of the person.</param>
/// <param name="token">Cancels the loading.</param>
/// <returns>The research, or null when the person was not researched yet.</returns>
/// <exception cref="InvalidDataException">The research is damaged, or a newer version of AI Studio stored it.</exception>
public async Task<BflPersonResearch?> LoadPersonResearchAsync(Guid projectId, string name, CancellationToken token = default)
{
await this.InitializeAsync(token);
return await this.LoadPersonResearchWithoutInitializeAsync(this.PersonResearchPath(projectId, BflPersonId.Of(name)), token);
}
/// <summary>
/// Loads the research on every person of a preparation, including people who are no longer on the list of
/// participants. A research which cannot be opened is left out and stays as it is.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">Cancels the loading.</param>
/// <returns>The research on the people, in no particular order.</returns>
public async Task<IReadOnlyList<BflPersonResearch>> LoadAllPersonResearchAsync(Guid projectId, CancellationToken token = default)
{
await this.InitializeAsync(token);
var directory = this.PersonResearchDirectory(projectId);
if (!Directory.Exists(directory))
return [];
var research = new List<BflPersonResearch>();
foreach (var path in Directory.EnumerateFiles(directory, "*.json"))
{
// Only the files of people count, named by their IDs:
if (!Guid.TryParseExact(Path.GetFileNameWithoutExtension(path), "D", out _))
continue;
try
{
if (await this.LoadPersonResearchWithoutInitializeAsync(path, token) is { } found)
research.Add(found);
}
catch (InvalidDataException exception)
{
logger.LogWarning(exception, "Could not open the research on a person of the preparation '{ProjectId}' of the BeyondFacts Lab.", projectId);
}
}
return research;
}
/// <summary>
/// Stores the research on one person of a preparation, in place of the earlier one.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="research">The research.</param>
/// <param name="token">Cancels the storing.</param>
/// <returns>The preparation, with the time of its last change.</returns>
/// <exception cref="FileNotFoundException">The preparation does not exist.</exception>
/// <exception cref="InvalidDataException">The earlier research is damaged, or a newer version of AI Studio stored it; it stays as it is.</exception>
public async Task<BflProject> SavePersonResearchAsync(Guid projectId, BflPersonResearch research, CancellationToken token = default)
{
await this.InitializeAsync(token);
var gate = this.GetLock(projectId);
await gate.WaitAsync(token);
try
{
var project = await this.LoadRequiredWithoutInitializeAsync(projectId, token);
var path = this.PersonResearchPath(projectId, BflPersonId.Of(research.Name));
// A research which a newer version stored, or which is damaged, stays as it is:
await this.LoadPersonResearchWithoutInitializeAsync(path, token);
research.SchemaVersion = BflPersonResearch.CURRENT_SCHEMA_VERSION;
foreach (var stage in research.Stages)
stage.Research.SchemaVersion = BflResearch.CURRENT_SCHEMA_VERSION;
await WriteTextAtomicAsync(path, JsonSerializer.Serialize(research, JSON_OPTIONS), token);
project.ModifiedAtUtc = DateTimeOffset.UtcNow;
await this.StoreProjectAsync(project, token);
return project;
}
finally
{
gate.Release();
}
}
/// <summary>
/// Loads the research on one person from its file.
/// </summary>
/// <param name="path">The file.</param>
/// <param name="token">Cancels the loading.</param>
/// <returns>The research, or null when the file does not exist.</returns>
/// <exception cref="InvalidDataException">The research is damaged, belongs to another file, or a newer version of AI Studio stored it.</exception>
private async Task<BflPersonResearch?> LoadPersonResearchWithoutInitializeAsync(string path, CancellationToken token)
{
if (!File.Exists(path))
return null;
BflPersonResearch? research;
try
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65_536, true);
research = await JsonSerializer.DeserializeAsync<BflPersonResearch>(stream, JSON_OPTIONS, token);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException)
{
throw new InvalidDataException("This version of AI Studio cannot open the research on a person.", exception);
}
if (research is null || research.SchemaVersion is < 1 or > BflPersonResearch.CURRENT_SCHEMA_VERSION || IsNull(research.Name) || IsNull(research.Stages) || research.Stages.Any(stage => IsNull(stage) || IsNull(stage.Research) || IsBroken(stage.Research)))
throw new InvalidDataException("This version of AI Studio cannot open the research on a person.");
// The file of a person is named by the ID of their name; a research under another name is no research of theirs:
if (!string.Equals(Path.GetFileNameWithoutExtension(path), BflPersonId.Of(research.Name).ToString("D"), StringComparison.OrdinalIgnoreCase))
throw new InvalidDataException("The research on a person is stored under the name of another person.");
return research;
}
/// <summary>
/// Loads whom of the list of participants the lab researches in depth.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">Cancels the loading.</param>
/// <returns>The selection, or null when the file does not exist.</returns>
/// <exception cref="InvalidDataException">The selection is damaged, or a newer version of AI Studio stored it.</exception>
private async Task<BflParticipantSelection?> LoadParticipantSelectionWithoutInitializeAsync(Guid projectId, CancellationToken token)
{
var path = this.ParticipantSelectionPath(projectId);
if (!File.Exists(path))
return null;
BflParticipantSelection? selection;
try
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65_536, true);
selection = await JsonSerializer.DeserializeAsync<BflParticipantSelection>(stream, JSON_OPTIONS, token);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException)
{
throw new InvalidDataException("This version of AI Studio cannot open the selection of participants.", exception);
}
if (selection is null || selection.SchemaVersion is < 1 or > BflParticipantSelection.CURRENT_SCHEMA_VERSION || IsNull(selection.Names) || selection.Names.Any(IsNull))
throw new InvalidDataException("This version of AI Studio cannot open the selection of participants.");
return selection;
}
/// <summary>
/// Gets the file with the selection of participants of a preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
private string ParticipantSelectionPath(Guid projectId) => Path.Combine(this.ProjectDirectory(projectId), STEPS_DIRECTORY_NAME, BflStep.STRATEGY.FolderName, RESEARCH_DIRECTORY_NAME, PARTICIPANT_SELECTION_FILE_NAME);
/// <summary>
/// Gets the folder with the research on the people of a preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
private string PersonResearchDirectory(Guid projectId) => Path.Combine(this.ProjectDirectory(projectId), STEPS_DIRECTORY_NAME, BflStep.STRATEGY.FolderName, RESEARCH_DIRECTORY_NAME, PERSON_RESEARCH_DIRECTORY_NAME);
/// <summary>
/// Gets the file with the research on one person.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="personId">The ID of the person, see BflPersonId.</param>
private string PersonResearchPath(Guid projectId, Guid personId) => Path.Combine(this.PersonResearchDirectory(projectId), $"{personId:D}.json");
}
@@ -0,0 +1,449 @@
using System.Text.Json;
namespace AIStudio.Assistants.BeyondFactsLab;
public sealed partial class BeyondFactsLabStore
{
/// <summary>
/// Gets the preparation the person selected last, or null when there is none or it does not exist anymore.
/// </summary>
public Guid? LastSelectedProjectId { get; private set; }
/// <summary>
/// Lists every preparation, also those this version cannot open, the one changed last first.
/// </summary>
/// <param name="token">The cancellation token.</param>
/// <returns>The preparations.</returns>
public async Task<IReadOnlyList<BflProjectEntry>> ListProjectsAsync(CancellationToken token = default)
{
await this.InitializeAsync(token);
List<BflProjectEntry> projects = [];
foreach (var directory in Directory.EnumerateDirectories(this.RootDirectory))
{
token.ThrowIfCancellationRequested();
if (!Guid.TryParseExact(Path.GetFileName(directory), "D", out var projectId))
continue;
projects.Add(await this.LoadProjectEntryAsync(projectId, directory, token));
}
return [.. projects.OrderByDescending(project => project.ModifiedAtUtc)];
}
/// <summary>
/// Loads a preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The preparation, or null when it does not exist or this version cannot open it.</returns>
public async Task<BflProject?> LoadAsync(Guid projectId, CancellationToken token = default)
{
await this.InitializeAsync(token);
try
{
return await this.LoadWithoutInitializeAsync(projectId, token);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException)
{
this.LogUnavailableProject(projectId, exception);
return null;
}
}
/// <summary>
/// Creates a preparation.
/// </summary>
/// <param name="name">The name the person gave it.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The new preparation.</returns>
/// <exception cref="ArgumentException">The name is empty.</exception>
public async Task<BflProject> CreateAsync(string name, CancellationToken token = default)
{
var sanitizedName = RequireName(name);
await this.InitializeAsync(token);
var projectId = Guid.NewGuid();
var gate = this.GetLock(projectId);
await gate.WaitAsync(token);
try
{
var directory = this.ProjectDirectory(projectId);
if (Directory.Exists(directory))
throw new IOException($"A preparation with the ID '{projectId}' exists already.");
var now = DateTimeOffset.UtcNow;
var project = new BflProject
{
ProjectId = projectId,
Name = sanitizedName,
CreatedAtUtc = now,
ModifiedAtUtc = now,
};
await this.StoreProjectAsync(project, token);
return project;
}
finally
{
gate.Release();
}
}
/// <summary>
/// Renames a preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="name">The new name.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The renamed preparation.</returns>
/// <exception cref="ArgumentException">The name is empty.</exception>
public async Task<BflProject> RenameAsync(Guid projectId, string name, CancellationToken token = default)
{
var sanitizedName = RequireName(name);
return await this.MutateProjectAsync(projectId, project => project.Name = sanitizedName, token);
}
/// <summary>
/// Marks the event of a preparation as having taken place, or takes that back.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="happenedAtUtc">When the event took place, or null when it has not.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The changed preparation.</returns>
public async Task<BflProject> SetHappenedAsync(Guid projectId, DateTimeOffset? happenedAtUtc, CancellationToken token = default)
{
return await this.MutateProjectAsync(projectId, project => project.HappenedAtUtc = happenedAtUtc?.ToUniversalTime(), token);
}
/// <summary>
/// Deletes a preparation with everything it holds, also when this version cannot open it.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">The cancellation token.</param>
public async Task DeleteAsync(Guid projectId, CancellationToken token = default)
{
await this.InitializeAsync(token);
var gate = this.GetLock(projectId);
await gate.WaitAsync(token);
try
{
var directory = this.ProjectDirectory(projectId);
if (Directory.Exists(directory))
Directory.Delete(directory, recursive: true);
}
finally
{
gate.Release();
this.ForgetLock(projectId);
}
await this.ForgetSelectionAsync(projectId, token);
}
/// <summary>
/// Remembers the preparation the person selected, for the next time the lab opens.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">The cancellation token.</param>
public async Task RememberSelectionAsync(Guid projectId, CancellationToken token = default)
{
await this.InitializeAsync(token);
if (this.LastSelectedProjectId == projectId)
return;
await this.selectionLock.WaitAsync(token);
try
{
this.LastSelectedProjectId = projectId;
await WriteTextAtomicAsync(this.SelectionPath(), JsonSerializer.Serialize<Guid?>(projectId, JSON_OPTIONS), token);
}
finally
{
this.selectionLock.Release();
}
}
/// <summary>
/// Forgets the selection when it names the given preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">The cancellation token.</param>
private async Task ForgetSelectionAsync(Guid projectId, CancellationToken token)
{
if (this.LastSelectedProjectId != projectId)
return;
await this.selectionLock.WaitAsync(token);
try
{
if (this.LastSelectedProjectId != projectId)
return;
this.LastSelectedProjectId = null;
await WriteTextAtomicAsync(this.SelectionPath(), JsonSerializer.Serialize<Guid?>(null, JSON_OPTIONS), token);
}
finally
{
this.selectionLock.Release();
}
}
/// <summary>
/// Reads the preparation selected last, when it still exists.
/// </summary>
/// <param name="token">The cancellation token.</param>
private async Task LoadSelectionAsync(CancellationToken token)
{
var path = this.SelectionPath();
if (!File.Exists(path))
return;
try
{
var serialized = await File.ReadAllTextAsync(path, token);
var selected = JsonSerializer.Deserialize<Guid?>(serialized, JSON_OPTIONS);
this.LastSelectedProjectId = selected is not null && Directory.Exists(this.ProjectDirectory(selected.Value)) ? selected : null;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException)
{
logger.LogWarning(exception, "Could not read the preparation of the BeyondFacts Lab selected last.");
this.LastSelectedProjectId = null;
}
}
/// <summary>
/// Loads a preparation for the list, or an entry which says why it cannot be opened.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="directory">The folder of the preparation.</param>
/// <param name="token">The cancellation token.</param>
private async Task<BflProjectEntry> LoadProjectEntryAsync(Guid projectId, string directory, CancellationToken token)
{
var path = this.ProjectPath(projectId);
var fallbackModifiedAtUtc = LastWriteTimeUtc(path, directory);
if (!File.Exists(path))
return new(projectId, string.Empty, fallbackModifiedAtUtc, BflProjectLoadStatus.UNAVAILABLE, null);
string json;
try
{
json = await File.ReadAllTextAsync(path, token);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
this.LogUnavailableProject(projectId, exception);
return new(projectId, string.Empty, fallbackModifiedAtUtc, BflProjectLoadStatus.UNAVAILABLE, null);
}
try
{
var project = JsonSerializer.Deserialize<BflProject>(json, JSON_OPTIONS);
if (project is not null && IsValidProject(project, projectId))
return BflProjectEntry.FromProject(project);
}
catch (JsonException exception)
{
this.LogUnavailableProject(projectId, exception);
}
return ReadRecoveryEntry(projectId, json, fallbackModifiedAtUtc);
}
/// <summary>
/// Reads what the list can show about a preparation this version cannot open: its name, when it changed,
/// and whether a newer version stored it.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="json">The content of its file.</param>
/// <param name="fallbackModifiedAtUtc">When the file changed, for files without a readable date.</param>
private static BflProjectEntry ReadRecoveryEntry(Guid projectId, string json, DateTimeOffset fallbackModifiedAtUtc)
{
try
{
using var document = JsonDocument.Parse(json);
var root = document.RootElement;
if (root.ValueKind is not JsonValueKind.Object)
return new(projectId, string.Empty, fallbackModifiedAtUtc, BflProjectLoadStatus.UNAVAILABLE, null);
var name = root.TryGetProperty("name", out var nameElement) && nameElement.ValueKind is JsonValueKind.String ? SanitizeName(nameElement.GetString()) : string.Empty;
var modifiedAtUtc = root.TryGetProperty("modifiedAtUtc", out var modifiedElement) && modifiedElement.ValueKind is JsonValueKind.String && modifiedElement.TryGetDateTimeOffset(out var parsedModifiedAtUtc)
? parsedModifiedAtUtc
: fallbackModifiedAtUtc;
var isNewer = root.TryGetProperty("schemaVersion", out var versionElement) && versionElement.ValueKind is JsonValueKind.Number && versionElement.TryGetInt32(out var schemaVersion) && schemaVersion > BflProject.CURRENT_SCHEMA_VERSION;
return new(projectId, name, modifiedAtUtc, isNewer ? BflProjectLoadStatus.NEWER_VERSION : BflProjectLoadStatus.UNAVAILABLE, null);
}
catch (JsonException)
{
return new(projectId, string.Empty, fallbackModifiedAtUtc, BflProjectLoadStatus.UNAVAILABLE, null);
}
}
/// <summary>
/// Gets when the file of a preparation, or else its folder, changed last.
/// </summary>
/// <param name="projectPath">The file of the preparation.</param>
/// <param name="directory">The folder of the preparation.</param>
private static DateTimeOffset LastWriteTimeUtc(string projectPath, string directory)
{
try
{
var timestamp = File.Exists(projectPath) ? File.GetLastWriteTimeUtc(projectPath) : Directory.GetLastWriteTimeUtc(directory);
return new DateTimeOffset(timestamp);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
return DateTimeOffset.UnixEpoch;
}
}
/// <summary>
/// Remembers the step the person looked at last, without counting it as a change of the preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="step">The step.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The preparation.</returns>
public async Task<BflProject> SetCurrentStepAsync(Guid projectId, BflStep step, CancellationToken token = default)
{
return await this.MutateProjectAsync(projectId, project => project.CurrentStep = step, token, isChange: false);
}
/// <summary>
/// Remembers the provider the person chose for the chats of a preparation, without counting it as a change of
/// the preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="providerId">The ID of the provider.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The preparation.</returns>
public async Task<BflProject> SetProviderAsync(Guid projectId, string providerId, CancellationToken token = default)
{
return await this.MutateProjectAsync(projectId, project => project.ProviderId = providerId, token, isChange: false);
}
/// <summary>
/// Changes a preparation under its lock and stores it.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="mutation">The change.</param>
/// <param name="token">The cancellation token.</param>
/// <param name="isChange">Whether the list shows the preparation as changed now.</param>
/// <returns>The changed preparation.</returns>
/// <exception cref="FileNotFoundException">The preparation does not exist.</exception>
/// <exception cref="InvalidDataException">This version cannot open the preparation, so it does not write it either.</exception>
private async Task<BflProject> MutateProjectAsync(Guid projectId, Action<BflProject> mutation, CancellationToken token, bool isChange = true)
{
await this.InitializeAsync(token);
var gate = this.GetLock(projectId);
await gate.WaitAsync(token);
try
{
var project = await this.LoadRequiredWithoutInitializeAsync(projectId, token);
mutation(project);
if (isChange)
project.ModifiedAtUtc = DateTimeOffset.UtcNow;
await this.StoreProjectAsync(project, token);
return project;
}
finally
{
gate.Release();
}
}
/// <summary>
/// Reads a preparation which has to exist and has to be one this version can open, without the first start of the store.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The preparation.</returns>
/// <exception cref="FileNotFoundException">The preparation does not exist.</exception>
/// <exception cref="InvalidDataException">This version cannot open the preparation.</exception>
private async Task<BflProject> LoadRequiredWithoutInitializeAsync(Guid projectId, CancellationToken token)
{
var path = this.ProjectPath(projectId);
if (!File.Exists(path))
throw new FileNotFoundException("The preparation does not exist.", path);
BflProject? project;
try
{
project = await this.LoadWithoutInitializeAsync(projectId, token);
}
catch (JsonException exception)
{
throw new InvalidDataException("This version of AI Studio cannot open the preparation.", exception);
}
return project ?? throw new InvalidDataException("This version of AI Studio cannot open the preparation.");
}
/// <summary>
/// Reads a preparation without the first start of the store.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The preparation, or null when it does not exist or is not valid.</returns>
private async Task<BflProject?> LoadWithoutInitializeAsync(Guid projectId, CancellationToken token)
{
var path = this.ProjectPath(projectId);
if (!File.Exists(path))
return null;
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65_536, true);
var project = await JsonSerializer.DeserializeAsync<BflProject>(stream, JSON_OPTIONS, token);
return project is not null && IsValidProject(project, projectId) ? project : null;
}
/// <summary>
/// Writes a preparation in the form of this version.
/// </summary>
/// <param name="project">The preparation.</param>
/// <param name="token">The cancellation token.</param>
private async Task StoreProjectAsync(BflProject project, CancellationToken token)
{
project.SchemaVersion = BflProject.CURRENT_SCHEMA_VERSION;
var json = JsonSerializer.Serialize(project, JSON_OPTIONS);
await WriteTextAtomicAsync(this.ProjectPath(project.ProjectId), json, token);
}
/// <summary>
/// Checks a preparation which was read from a file.
/// </summary>
/// <param name="project">The preparation.</param>
/// <param name="expectedProjectId">The ID its folder names.</param>
private static bool IsValidProject(BflProject project, Guid expectedProjectId) =>
project.SchemaVersion is >= 1 and <= BflProject.CURRENT_SCHEMA_VERSION &&
project.ProjectId != Guid.Empty &&
project.ProjectId == expectedProjectId &&
!string.IsNullOrWhiteSpace(project.Name) &&
Enum.IsDefined(project.CurrentStep) &&
!IsNull(project.ProviderId);
/// <summary>
/// Cleans a name and refuses one which is empty afterward.
/// </summary>
/// <param name="name">The name as entered.</param>
/// <returns>The cleaned name.</returns>
/// <exception cref="ArgumentException">The name is empty.</exception>
private static string RequireName(string name)
{
var sanitizedName = SanitizeName(name);
if (sanitizedName.Length == 0)
throw new ArgumentException("A preparation needs a name.", nameof(name));
return sanitizedName;
}
/// <summary>
/// Logs why a preparation cannot be opened.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="exception">What went wrong.</param>
private void LogUnavailableProject(Guid projectId, Exception exception)
{
logger.LogWarning(exception, "Could not open the preparation '{ProjectId}' of the BeyondFacts Lab.", projectId);
}
}
@@ -0,0 +1,131 @@
using System.Text.Json;
namespace AIStudio.Assistants.BeyondFactsLab;
public sealed partial class BeyondFactsLabStore
{
/// <summary>
/// The folder of the step "Strategy" which holds the research, one file for each topic.
/// </summary>
private const string RESEARCH_DIRECTORY_NAME = "research";
/// <summary>
/// Loads the research of a preparation on one topic.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="topic">The topic of the research.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The research, or null while there is none.</returns>
/// <exception cref="InvalidDataException">This version cannot open the research.</exception>
public async Task<BflResearch?> LoadResearchAsync(Guid projectId, BflResearchTopic topic, CancellationToken token = default)
{
await this.InitializeAsync(token);
return await this.LoadResearchWithoutInitializeAsync(projectId, topic, token);
}
/// <summary>
/// Loads the research of a preparation on every topic.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The research this version can open, by its topics; a topic without research is missing.</returns>
public async Task<IReadOnlyDictionary<BflResearchTopic, BflResearch>> LoadAllResearchAsync(Guid projectId, CancellationToken token = default)
{
await this.InitializeAsync(token);
var research = new Dictionary<BflResearchTopic, BflResearch>();
foreach (var topic in BflResearchTopic.All)
{
try
{
if (await this.LoadResearchWithoutInitializeAsync(projectId, topic, token) is { } found)
research[topic] = found;
}
catch (InvalidDataException exception)
{
logger.LogWarning(exception, "Could not open the research '{Topic}' of the preparation '{ProjectId}' of the BeyondFacts Lab.", topic, projectId);
}
}
return research;
}
/// <summary>
/// Stores the research of a preparation on one topic, replacing an earlier one, and counts it as a change of the
/// preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="topic">The topic of the research.</param>
/// <param name="research">The research.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The preparation with its new time of change.</returns>
/// <exception cref="FileNotFoundException">The preparation does not exist.</exception>
/// <exception cref="InvalidDataException">This version cannot open the preparation or the stored research, so it does not write them either.</exception>
public async Task<BflProject> SaveResearchAsync(Guid projectId, BflResearchTopic topic, BflResearch research, CancellationToken token = default)
{
await this.InitializeAsync(token);
var gate = this.GetLock(projectId);
await gate.WaitAsync(token);
try
{
var project = await this.LoadRequiredWithoutInitializeAsync(projectId, token);
// A research which a newer version stored, or which is damaged, stays as it is:
await this.LoadResearchWithoutInitializeAsync(projectId, topic, token);
research.SchemaVersion = BflResearch.CURRENT_SCHEMA_VERSION;
await WriteTextAtomicAsync(this.ResearchPath(projectId, topic), JsonSerializer.Serialize(research, JSON_OPTIONS), token);
project.ModifiedAtUtc = DateTimeOffset.UtcNow;
await this.StoreProjectAsync(project, token);
return project;
}
finally
{
gate.Release();
}
}
/// <summary>
/// Reads the research of a preparation on one topic without the first start of the store.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="topic">The topic of the research.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The research, or null when there is no file.</returns>
/// <exception cref="InvalidDataException">This version cannot open the research.</exception>
private async Task<BflResearch?> LoadResearchWithoutInitializeAsync(Guid projectId, BflResearchTopic topic, CancellationToken token)
{
var path = this.ResearchPath(projectId, topic);
if (!File.Exists(path))
return null;
BflResearch? research;
try
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65_536, true);
research = await JsonSerializer.DeserializeAsync<BflResearch>(stream, JSON_OPTIONS, token);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException)
{
throw new InvalidDataException("This version of AI Studio cannot open the research.", exception);
}
if (research is null || IsBroken(research))
throw new InvalidDataException("This version of AI Studio cannot open the research.");
return research;
}
/// <summary>
/// Tells whether a stored research comes from a newer version of AI Studio, or lacks one of its parts.
/// </summary>
/// <param name="research">The research.</param>
private static bool IsBroken(BflResearch research) => research.SchemaVersion is < 1 or > BflResearch.CURRENT_SCHEMA_VERSION || IsNull(research.Text) || IsNull(research.Details) || IsNull(research.SearchQueries) || IsNull(research.Pages) || IsNull(research.Participants) || research.Participants.Any(participant => IsNull(participant) || IsNull(participant.Name) || IsNull(participant.Entry));
/// <summary>
/// Gets the file of the research of a preparation on one topic.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="topic">The topic of the research.</param>
private string ResearchPath(Guid projectId, BflResearchTopic topic) => Path.Combine(this.ProjectDirectory(projectId), STEPS_DIRECTORY_NAME, BflStep.STRATEGY.FolderName, RESEARCH_DIRECTORY_NAME, topic.FileName);
}
@@ -0,0 +1,129 @@
using System.Text.Json;
namespace AIStudio.Assistants.BeyondFactsLab;
public sealed partial class BeyondFactsLabStore
{
/// <summary>
/// The folder of a preparation which holds its results, one file for each kind.
/// </summary>
private const string RESULTS_DIRECTORY_NAME = "results";
/// <summary>
/// Loads a result of a preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="kind">The kind of result.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The result, or an empty one while the preparation has none.</returns>
/// <exception cref="InvalidDataException">This version cannot open the result.</exception>
public async Task<BflResult> LoadResultAsync(Guid projectId, BflResultKind kind, CancellationToken token = default)
{
await this.InitializeAsync(token);
return await this.LoadResultWithoutInitializeAsync(projectId, kind, token);
}
/// <summary>
/// Loads every result of a preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The results this version can open, by their kinds.</returns>
public async Task<IReadOnlyDictionary<BflResultKind, BflResult>> LoadResultsAsync(Guid projectId, CancellationToken token = default)
{
await this.InitializeAsync(token);
var results = new Dictionary<BflResultKind, BflResult>();
foreach (var kind in BflResultKind.All)
{
try
{
results[kind] = await this.LoadResultWithoutInitializeAsync(projectId, kind, token);
}
catch (InvalidDataException exception)
{
logger.LogWarning(exception, "Could not open the result '{Kind}' of the preparation '{ProjectId}' of the BeyondFacts Lab.", kind, projectId);
}
}
return results;
}
/// <summary>
/// Stores a result of a preparation and counts it as a change of the preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="kind">The kind of result.</param>
/// <param name="result">The result.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The preparation with its new time of change.</returns>
/// <exception cref="FileNotFoundException">The preparation does not exist.</exception>
/// <exception cref="InvalidDataException">This version cannot open the preparation or the stored result, so it does not write them either.</exception>
public async Task<BflProject> SaveResultAsync(Guid projectId, BflResultKind kind, BflResult result, CancellationToken token = default)
{
await this.InitializeAsync(token);
var gate = this.GetLock(projectId);
await gate.WaitAsync(token);
try
{
var project = await this.LoadRequiredWithoutInitializeAsync(projectId, token);
// A result which a newer version stored, or which is damaged, stays as it is:
await this.LoadResultWithoutInitializeAsync(projectId, kind, token);
result.SchemaVersion = BflResult.CURRENT_SCHEMA_VERSION;
await WriteTextAtomicAsync(this.ResultPath(projectId, kind), JsonSerializer.Serialize(result, JSON_OPTIONS), token);
project.ModifiedAtUtc = DateTimeOffset.UtcNow;
await this.StoreProjectAsync(project, token);
return project;
}
finally
{
gate.Release();
}
}
/// <summary>
/// Reads a result of a preparation without the first start of the store.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="kind">The kind of result.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The result, or an empty one when there is no file.</returns>
/// <exception cref="InvalidDataException">This version cannot open the result.</exception>
private async Task<BflResult> LoadResultWithoutInitializeAsync(Guid projectId, BflResultKind kind, CancellationToken token)
{
var path = this.ResultPath(projectId, kind);
if (!File.Exists(path))
return new BflResult();
BflResult? result;
try
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65_536, true);
result = await JsonSerializer.DeserializeAsync<BflResult>(stream, JSON_OPTIONS, token);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException)
{
throw new InvalidDataException("This version of AI Studio cannot open the result.", exception);
}
if (result is null || result.SchemaVersion is < 1 or > BflResult.CURRENT_SCHEMA_VERSION || !IsReadable(result.Draft) || !IsReadable(result.Confirmed))
throw new InvalidDataException("This version of AI Studio cannot open the result.");
return result;
}
/// <summary>
/// Tells whether a version of a result, which may be missing, has everything this version of AI Studio reads.
/// </summary>
/// <param name="version">The version, or null.</param>
private static bool IsReadable(BflResultVersion? version) => version is null || !IsNull(version.Text) && !IsNull(version.WorkStateRevisions);
/// <summary>
/// Gets the file of a result of a preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="kind">The kind of result.</param>
private string ResultPath(Guid projectId, BflResultKind kind) => Path.Combine(this.ProjectDirectory(projectId), RESULTS_DIRECTORY_NAME, kind.FileName);
}
@@ -0,0 +1,197 @@
using System.Text.Json;
using AIStudio.Chat;
namespace AIStudio.Assistants.BeyondFactsLab;
public sealed partial class BeyondFactsLabStore
{
/// <summary>
/// The file which holds a chat of the lab.
/// </summary>
private const string THREAD_FILE_NAME = "thread.json";
/// <summary>
/// The folder of the conversation about whether the lab fits a task. It is no ID, so no preparation can have it.
/// </summary>
private const string ONBOARDING_DIRECTORY_NAME = "onboarding";
/// <summary>
/// Guards the conversation about whether the lab fits a task, which belongs to no preparation.
/// </summary>
private readonly SemaphoreSlim onboardingLock = new(1, 1);
/// <summary>
/// Loads a chat of the lab.
/// </summary>
/// <param name="location">Where the chat belongs.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The chat, or null while there is none.</returns>
/// <exception cref="InvalidDataException">This version cannot open the chat.</exception>
public async Task<ChatThread?> LoadThreadAsync(BflThreadLocation location, CancellationToken token = default)
{
await this.InitializeAsync(token);
return await this.LoadThreadWithoutInitializeAsync(location, token);
}
/// <summary>
/// Stores a chat of the lab. The chat of a step counts as a change of its preparation.
/// </summary>
/// <param name="location">Where the chat belongs.</param>
/// <param name="thread">The chat.</param>
/// <param name="token">The cancellation token.</param>
/// <exception cref="FileNotFoundException">The preparation of the step does not exist, e.g., because the person deleted it while the model answered.</exception>
/// <exception cref="InvalidDataException">This version cannot open the preparation or the stored chat, so it does not write them either.</exception>
public async Task SaveThreadAsync(BflThreadLocation location, ChatThread thread, CancellationToken token = default)
{
if (thread.ChatId != location.ChatId)
throw new ArgumentException("The chat belongs to another place.", nameof(thread));
await this.InitializeAsync(token);
var gate = this.ThreadLock(location);
await gate.WaitAsync(token);
try
{
var project = location is BflStepThreadLocation stepLocation ? await this.LoadRequiredWithoutInitializeAsync(stepLocation.ProjectId, token) : null;
// A chat which a newer version stored, or which is damaged, stays as it is:
await this.LoadThreadWithoutInitializeAsync(location, token);
await WriteTextAtomicAsync(this.ThreadPath(location), JsonSerializer.Serialize(thread, WorkspaceBehaviour.JSON_OPTIONS), token);
if (project is null)
return;
project.ModifiedAtUtc = DateTimeOffset.UtcNow;
await this.StoreProjectAsync(project, token);
}
finally
{
gate.Release();
}
}
/// <summary>
/// Deletes a chat of the lab, so that its conversation starts over.
/// </summary>
/// <remarks>
/// Unlike the other files of a step, a chat which this version cannot open is deleted as well: the person asked
/// to start the conversation over, and nothing else refers to it.
/// </remarks>
/// <param name="location">Where the chat belongs.</param>
/// <param name="token">The cancellation token.</param>
public async Task DeleteThreadAsync(BflThreadLocation location, CancellationToken token = default)
{
await this.InitializeAsync(token);
var gate = this.ThreadLock(location);
await gate.WaitAsync(token);
try
{
var path = this.ThreadPath(location);
if (File.Exists(path))
File.Delete(path);
}
finally
{
gate.Release();
}
}
/// <summary>
/// Finds every chat of the lab on the disk, from the folders alone.
/// </summary>
/// <remarks>
/// For the cleanup of the provenance store at the start, which must know every chat which may refer to an entry,
/// also when the lab is switched off. A preparation this version cannot open keeps its chats as well.
/// </remarks>
/// <returns>The place of each chat, by the ID of the chat.</returns>
public IReadOnlyDictionary<Guid, BflThreadLocation> ReadAllThreadLocations()
{
var locations = new Dictionary<Guid, BflThreadLocation>();
if (!Directory.Exists(this.RootDirectory))
return locations;
AddWhenStored(BflOnboardingThreadLocation.INSTANCE);
foreach (var directory in Directory.EnumerateDirectories(this.RootDirectory))
{
if (!Guid.TryParse(Path.GetFileName(directory), out var projectId))
continue;
foreach (var step in BflStep.All)
AddWhenStored(new BflStepThreadLocation(projectId, step));
}
return locations;
void AddWhenStored(BflThreadLocation location)
{
if (File.Exists(this.ThreadPath(location)))
locations[location.ChatId] = location;
}
}
/// <summary>
/// Tells when a chat of the lab was last written.
/// </summary>
/// <param name="location">Where the chat belongs.</param>
/// <returns>The time, or null when there is no chat.</returns>
public DateTimeOffset? GetThreadWrittenAt(BflThreadLocation location)
{
var path = this.ThreadPath(location);
return File.Exists(path) ? new DateTimeOffset(File.GetLastWriteTimeUtc(path)) : null;
}
/// <summary>
/// Reads a chat of the lab without the first start of the store.
/// </summary>
/// <param name="location">Where the chat belongs.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The chat, or null when there is no file.</returns>
/// <exception cref="InvalidDataException">This version cannot open the chat.</exception>
private async Task<ChatThread?> LoadThreadWithoutInitializeAsync(BflThreadLocation location, CancellationToken token)
{
var path = this.ThreadPath(location);
if (!File.Exists(path))
return null;
ChatThread? thread;
try
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65_536, true);
thread = await JsonSerializer.DeserializeAsync<ChatThread>(stream, WorkspaceBehaviour.JSON_OPTIONS, token);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException)
{
throw new InvalidDataException("This version of AI Studio cannot open the chat.", exception);
}
// A chat copied into another place would mix up what the provenance store keeps for it:
if (thread is null || thread.ChatId != location.ChatId || IsNull(thread.Blocks))
throw new InvalidDataException("This version of AI Studio cannot open the chat.");
return thread;
}
/// <summary>
/// Gets the file of a chat of the lab.
/// </summary>
/// <param name="location">Where the chat belongs.</param>
private string ThreadPath(BflThreadLocation location) => location switch
{
BflStepThreadLocation stepLocation => Path.Combine(this.ProjectDirectory(stepLocation.ProjectId), STEPS_DIRECTORY_NAME, stepLocation.Step.FolderName, THREAD_FILE_NAME),
BflOnboardingThreadLocation => Path.Combine(this.RootDirectory, ONBOARDING_DIRECTORY_NAME, THREAD_FILE_NAME),
_ => throw new ArgumentOutOfRangeException(nameof(location), location, "The lab keeps no chat there.")
};
/// <summary>
/// Gets the lock which guards a chat of the lab: the chat of a step shares the lock of its preparation.
/// </summary>
/// <param name="location">Where the chat belongs.</param>
private SemaphoreSlim ThreadLock(BflThreadLocation location) => location switch
{
BflStepThreadLocation stepLocation => this.GetLock(stepLocation.ProjectId),
BflOnboardingThreadLocation => this.onboardingLock,
_ => throw new ArgumentOutOfRangeException(nameof(location), location, "The lab keeps no chat there.")
};
}
@@ -0,0 +1,123 @@
using System.Text.Json;
namespace AIStudio.Assistants.BeyondFactsLab;
public sealed partial class BeyondFactsLabStore
{
/// <summary>
/// The file of a step which holds its work state.
/// </summary>
private const string WORK_STATE_FILE_NAME = "work-state.json";
/// <summary>
/// Loads the work state of a step.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="step">The step.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The work state, or an empty one while the step has none.</returns>
/// <exception cref="InvalidDataException">This version cannot open the work state.</exception>
public async Task<BflWorkState> LoadWorkStateAsync(Guid projectId, BflStep step, CancellationToken token = default)
{
await this.InitializeAsync(token);
return await this.LoadWorkStateWithoutInitializeAsync(projectId, step, token);
}
/// <summary>
/// Loads the work states of every step of a preparation, e.g., to tell which ones are outdated.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The work states this version can open, by their steps.</returns>
public async Task<IReadOnlyDictionary<BflStep, BflWorkState>> LoadWorkStatesAsync(Guid projectId, CancellationToken token = default)
{
await this.InitializeAsync(token);
var workStates = new Dictionary<BflStep, BflWorkState>();
foreach (var step in BflStep.All)
{
try
{
workStates[step] = await this.LoadWorkStateWithoutInitializeAsync(projectId, step, token);
}
catch (InvalidDataException exception)
{
logger.LogWarning(exception, "Could not open the work state of the step '{Step}' of the preparation '{ProjectId}' of the BeyondFacts Lab.", step, projectId);
}
}
return workStates;
}
/// <summary>
/// Stores the work state of a step and counts it as a change of the preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="step">The step.</param>
/// <param name="workState">The work state.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The preparation with its new time of change.</returns>
/// <exception cref="FileNotFoundException">The preparation does not exist.</exception>
/// <exception cref="InvalidDataException">This version cannot open the preparation or the stored work state, so it does not write them either.</exception>
public async Task<BflProject> SaveWorkStateAsync(Guid projectId, BflStep step, BflWorkState workState, CancellationToken token = default)
{
await this.InitializeAsync(token);
var gate = this.GetLock(projectId);
await gate.WaitAsync(token);
try
{
var project = await this.LoadRequiredWithoutInitializeAsync(projectId, token);
// A work state which a newer version stored, or which is damaged, stays as it is:
await this.LoadWorkStateWithoutInitializeAsync(projectId, step, token);
workState.SchemaVersion = BflWorkState.CURRENT_SCHEMA_VERSION;
await WriteTextAtomicAsync(this.WorkStatePath(projectId, step), JsonSerializer.Serialize(workState, JSON_OPTIONS), token);
project.ModifiedAtUtc = DateTimeOffset.UtcNow;
await this.StoreProjectAsync(project, token);
return project;
}
finally
{
gate.Release();
}
}
/// <summary>
/// Reads the work state of a step without the first start of the store.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="step">The step.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The work state, or an empty one when there is no file.</returns>
/// <exception cref="InvalidDataException">This version cannot open the work state.</exception>
private async Task<BflWorkState> LoadWorkStateWithoutInitializeAsync(Guid projectId, BflStep step, CancellationToken token)
{
var path = this.WorkStatePath(projectId, step);
if (!File.Exists(path))
return new BflWorkState();
BflWorkState? workState;
try
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65_536, true);
workState = await JsonSerializer.DeserializeAsync<BflWorkState>(stream, JSON_OPTIONS, token);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException)
{
throw new InvalidDataException("This version of AI Studio cannot open the work state.", exception);
}
if (workState is null || workState.SchemaVersion is < 1 or > BflWorkState.CURRENT_SCHEMA_VERSION || IsNull(workState.FieldSuggestions) || workState.Confirmed is { } confirmed && (IsNull(confirmed.Sections) || IsNull(confirmed.UpstreamRevisions) || IsNull(confirmed.DetailsFingerprint)))
throw new InvalidDataException("This version of AI Studio cannot open the work state.");
return workState;
}
/// <summary>
/// Gets the file of the work state of a step.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
/// <param name="step">The step.</param>
private string WorkStatePath(Guid projectId, BflStep step) => Path.Combine(this.ProjectDirectory(projectId), STEPS_DIRECTORY_NAME, step.FolderName, WORK_STATE_FILE_NAME);
}
@@ -0,0 +1,184 @@
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using AIStudio.Settings;
namespace AIStudio.Assistants.BeyondFactsLab;
/// <summary>
/// Stores the preparations of the BeyondFacts Lab as files below the data directory.
/// </summary>
/// <remarks>
/// Each preparation lives in a folder named by its ID; the conversation about whether the lab fits a task, which
/// belongs to no preparation, lives in a folder of its own. The store keeps no paths: it derives every path from
/// IDs, so a backup works on another computer as well. It writes each file atomically, guards each preparation
/// with a lock of its own, and never deletes anything on its own; only the person deletes a preparation.
/// </remarks>
/// <param name="logger">The logger.</param>
/// <param name="storageOptions">Overrides the data directory, for tests.</param>
public sealed partial class BeyondFactsLabStore(ILogger<BeyondFactsLabStore> logger, BflStorageOptions? storageOptions = null)
{
/// <summary>
/// The name of the folder below the data directory.
/// </summary>
public const string ROOT_DIRECTORY_NAME = "beyondFactsLab";
/// <summary>
/// The longest name of a preparation the store keeps.
/// </summary>
public const int MAX_NAME_LENGTH = 200;
/// <summary>
/// The file of a preparation which holds its name and dates.
/// </summary>
private const string PROJECT_FILE_NAME = "project.json";
/// <summary>
/// The file which holds the preparation selected last.
/// </summary>
private const string SELECTION_FILE_NAME = "selection.json";
/// <summary>
/// The JSON options of all files of the lab.
/// </summary>
private static readonly JsonSerializerOptions JSON_OPTIONS = BeyondFactsLabJson.PERSISTENCE;
/// <summary>
/// The lock of each preparation.
/// </summary>
private readonly ConcurrentDictionary<Guid, SemaphoreSlim> projectLocks = [];
/// <summary>
/// Serializes the first start of the store.
/// </summary>
private readonly SemaphoreSlim initializationLock = new(1, 1);
/// <summary>
/// Serializes writing the selection.
/// </summary>
private readonly SemaphoreSlim selectionLock = new(1, 1);
/// <summary>
/// Whether the store cleaned up and read the selection already.
/// </summary>
private bool initialized;
/// <summary>
/// Gets the folder of the lab below the data directory.
/// </summary>
private string RootDirectory => Path.Combine(
storageOptions?.DataDirectory ??
SettingsManager.DataDirectory ??
throw new InvalidOperationException("The AI Studio data directory is not initialized."),
ROOT_DIRECTORY_NAME);
/// <summary>
/// Gets the folder whose files replace the prompts of the lab while the person allows it, see BflPromptOverrides.
/// </summary>
public string PromptOverridesDirectory => Path.Combine(this.RootDirectory, BflPromptOverrides.DIRECTORY_NAME);
/// <summary>
/// Writes a text file so that readers see either the old or the new content, never a part of it.
/// </summary>
/// <remarks>
/// The content reaches the disk before it replaces the file: a preparation is the work of hours, and a power
/// failure must not take it away.
/// </remarks>
/// <param name="targetPath">The file to write.</param>
/// <param name="content">The new content.</param>
/// <param name="token">The cancellation token.</param>
private static Task WriteTextAtomicAsync(string targetPath, string content, CancellationToken token)
{
Directory.CreateDirectory(Path.GetDirectoryName(targetPath)!);
return AtomicFile.WriteTextAsync(targetPath, content, new UTF8Encoding(false), token, flushToDisk: true);
}
/// <summary>
/// Writes a binary file so that readers see either the old or the new content, never a part of it.
/// </summary>
/// <remarks>
/// Like WriteTextAtomicAsync, the content reaches the disk before it replaces the file.
/// </remarks>
/// <param name="targetPath">The file to write.</param>
/// <param name="content">The new content.</param>
/// <param name="token">The cancellation token.</param>
private static Task WriteBytesAtomicAsync(string targetPath, ReadOnlyMemory<byte> content, CancellationToken token)
{
Directory.CreateDirectory(Path.GetDirectoryName(targetPath)!);
return AtomicFile.WriteAsync(targetPath, (stream, writeToken) => stream.WriteAsync(content, writeToken).AsTask(), token, flushToDisk: true);
}
/// <summary>
/// Removes control characters from a name, trims it, and cuts it to the longest name the store keeps.
/// </summary>
/// <param name="name">The name as entered or as read from a file.</param>
/// <returns>The cleaned name, empty when nothing remains.</returns>
internal static string SanitizeName(string? name)
{
if (string.IsNullOrWhiteSpace(name))
return string.Empty;
var sanitized = new string(name.Where(character => !char.IsControl(character)).ToArray()).Trim();
return sanitized.Length <= MAX_NAME_LENGTH ? sanitized : sanitized[..MAX_NAME_LENGTH].TrimEnd();
}
/// <summary>
/// Gets the lock of a preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
private SemaphoreSlim GetLock(Guid projectId) => this.projectLocks.GetOrAdd(projectId, _ => new(1, 1));
/// <summary>
/// Drops the lock of a preparation which does not exist anymore.
/// </summary>
/// <remarks>
/// The semaphore is not disposed: another operation might still wait on it.
/// </remarks>
/// <param name="projectId">The ID of the preparation.</param>
private void ForgetLock(Guid projectId) => this.projectLocks.TryRemove(projectId, out _);
/// <summary>
/// Gets the folder of a preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
private string ProjectDirectory(Guid projectId) => Path.Combine(this.RootDirectory, projectId.ToString("D"));
/// <summary>
/// Gets the file which holds the name and the dates of a preparation.
/// </summary>
/// <param name="projectId">The ID of the preparation.</param>
private string ProjectPath(Guid projectId) => Path.Combine(this.ProjectDirectory(projectId), PROJECT_FILE_NAME);
/// <summary>
/// Gets the file which holds the preparation selected last.
/// </summary>
private string SelectionPath() => Path.Combine(this.RootDirectory, SELECTION_FILE_NAME);
/// <summary>
/// Creates the folder of the lab, removes temporary files a crash left behind, and reads the selection.
/// </summary>
/// <param name="token">The cancellation token.</param>
private async Task InitializeAsync(CancellationToken token)
{
if (this.initialized)
return;
await this.initializationLock.WaitAsync(token);
try
{
if (this.initialized)
return;
Directory.CreateDirectory(this.RootDirectory);
AtomicFile.DeleteTemporaryFiles(this.RootDirectory, logger);
await this.LoadSelectionAsync(token);
this.initialized = true;
}
finally
{
this.initializationLock.Release();
}
}
}
@@ -0,0 +1,27 @@
using AIStudio.Settings;
using ComponentKind = AIStudio.Tools.Components;
namespace AIStudio.Assistants.BeyondFactsLab;
/// <summary>
/// Decides whether the BeyondFacts Lab may be opened.
/// </summary>
/// <remarks>
/// The lab is a prototype behind its own preview feature, and an organization can hide it like any other
/// assistant. The tile asks the same question through its required preview feature; the page asks here,
/// because somebody might reach its address without the tile, e.g., from a link or the browser history.
/// </remarks>
public static class BflAccess
{
/// <summary>
/// Checks whether the BeyondFacts Lab may be opened with the given settings.
/// </summary>
/// <param name="settingsManager">The settings to check.</param>
/// <param name="assistantName">The name of the lab for the log; without one, nothing gets logged.</param>
/// <returns>True, when the preview feature is switched on and no configuration hides the lab.</returns>
public static bool CanOpen(SettingsManager settingsManager, string assistantName = "") => settingsManager.IsAssistantVisible(
ComponentKind.BEYOND_FACTS_LAB_ASSISTANT,
assistantName: assistantName,
requiredPreviewFeature: ComponentKind.BEYOND_FACTS_LAB_ASSISTANT.RequiredPreviewFeature);
}
@@ -0,0 +1,30 @@
namespace AIStudio.Assistants.BeyondFactsLab;
/// <summary>
/// A text after the anonymizer of the BeyondFacts Lab ran over it, with what it replaced.
/// </summary>
/// <param name="Text">The anonymized text.</param>
/// <param name="Replacements">What the anonymizer replaced, in the order it first found each.</param>
public sealed record BflAnonymization(string Text, IReadOnlyList<BflReplacement> Replacements)
{
/// <summary>
/// Gets the result of a later run over the text, e.g., after the person edited it, together with what this run
/// replaced already.
/// </summary>
/// <param name="later">The later run.</param>
/// <returns>The text of the later run and the replacements of both runs, counted together.</returns>
public BflAnonymization CombinedWith(BflAnonymization later)
{
var combined = this.Replacements.ToList();
foreach (var replacement in later.Replacements)
{
var index = combined.FindIndex(candidate => candidate.Placeholder == replacement.Placeholder && candidate.Original == replacement.Original);
if (index < 0)
combined.Add(replacement);
else
combined[index] = combined[index] with { Count = combined[index].Count + replacement.Count };
}
return new BflAnonymization(later.Text, combined);
}
}
@@ -0,0 +1,485 @@
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace AIStudio.Assistants.BeyondFactsLab;
/// <summary>
/// Removes the personal details it recognizes from a session of the BeyondFacts Lab before the person shares it: links,
/// e-mail addresses, paths, phone numbers, and the names and terms the person lists.
/// </summary>
/// <remarks>
/// <para>
/// The anonymizer follows rules and asks no model, so it recognizes only what its rules describe. Names count only when
/// the person lists them; the lab suggests the ones it knows, see BflShareNames. A name is replaced in full, with its
/// titles, in the genitive, with umlauts written out or left out, and in the forms of web addresses, such as
/// "anna-mueller"; its first and its last name are replaced on their own as well, but only as they are written with a
/// capital letter, since many names are common words. A part which several people share becomes a placeholder
/// without a number.
/// </para>
/// <para>
/// Running the anonymizer again over its own result changes nothing: it leaves its placeholders alone, and the same
/// lists give the same numbers. That is why the person may edit the result and have it anonymized once more.
/// </para>
/// </remarks>
public static partial class BflAnonymizer
{
private static string TB(string fallbackEN) => Tools.PluginSystem.I18N.I.T(fallbackEN, typeof(BflAnonymizer).Namespace, nameof(BflAnonymizer));
/// <summary>
/// The fewest digits a phone number has; a shorter number may be anything.
/// </summary>
private const int MIN_PHONE_DIGITS = 7;
/// <summary>
/// The fewest letters a part of a name needs to be replaced on its own, so that an initial stays.
/// </summary>
private const int MIN_PART_LETTERS = 2;
/// <summary>
/// The titles which may stand before a name, longer ones first.
/// </summary>
private const string TITLE = @"(?:Professorin|Professor|Prof|Dr\.?-Ing|Dipl\.?-Ing|Dr|PD|Herrn|Herr|Frau|Mrs|Mr|Ms|Mx|Sir|Dame)";
/// <summary>
/// Any number of titles before a name, each followed by a period or a space, e.g., "Prof. Dr. ".
/// </summary>
private const string TITLES = $@"(?:{TITLE}(?:\.[ \t]*|[ \t]+))*";
/// <summary>
/// What may stand between the parts of a name: spaces, or the characters with which web addresses join words.
/// </summary>
private const string PART_SEPARATOR = @"(?:\s+|[._-])?";
/// <summary>
/// Where a name or a term may begin: not inside a word.
/// </summary>
private const string BEFORE = @"(?<![\p{L}\p{M}\p{N}_])";
/// <summary>
/// Where a name or a term may end: not inside a word.
/// </summary>
private const string AFTER = @"(?![\p{L}\p{M}\p{N}_])";
/// <summary>
/// Where a part of a name on its own may begin: neither inside a word nor after the hyphen of a double name.
/// </summary>
private const string BEFORE_PART = @"(?<![\p{L}\p{M}\p{N}_])(?<!\p{L}[-‐‑])";
/// <summary>
/// Where a part of a name on its own may end: neither inside a word nor before the hyphen of a double name.
/// </summary>
private const string AFTER_PART = @"(?![\p{L}\p{M}\p{N}_]|[-‐‑]\p{L})";
/// <summary>
/// The small words with which many last names begin, e.g., "von der Leyen".
/// </summary>
internal static readonly IReadOnlySet<string> NAME_PARTICLES = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"von", "vom", "van", "de", "der", "den", "del", "della", "di", "da", "du", "la", "le", "zu", "zum", "zur", "ten", "ter",
};
/// <summary>
/// Replaces the personal details the anonymizer recognizes.
/// </summary>
/// <param name="text">The text, e.g., a session of the lab in Markdown.</param>
/// <param name="people">The names of people to replace, one person each, e.g., "Prof. Dr. Anna Müller".</param>
/// <param name="terms">Further terms to replace, e.g., an institution or a place.</param>
/// <returns>The text with placeholders, and what was replaced.</returns>
public static BflAnonymization Anonymize(string text, IReadOnlyList<string> people, IReadOnlyList<string> terms)
{
var report = new List<BflReplacement>();
var link = Placeholder(TB("Link"));
var email = Placeholder(TB("E-mail address"));
var path = Placeholder(TB("Path"));
var phone = Placeholder(TB("Phone number"));
var result = text.Normalize(NormalizationForm.FormC);
// Links first, since an address may hold an e-mail address, a path, or a name:
result = MarkdownLinkPattern().Replace(result, match =>
{
Record(report, link, match.Groups["url"].Value);
var label = match.Groups["label"].Value.Trim();
return label.Length > 0 ? $"{label} {link}" : link;
});
result = AutoLinkPattern().Replace(result, match => Record(report, link, match.Groups["url"].Value));
result = UrlPattern().Replace(result, match => ReplaceWithoutEnd(report, link, match.Value));
result = EmailPattern().Replace(result, match => Record(report, email, match.Value));
result = PathPattern().Replace(result, match => ReplaceWithoutEnd(report, path, match.Value));
result = PhonePattern().Replace(result, match => IsPhoneNumber(match.Value) ? Record(report, phone, match.Value) : match.Value);
result = ReplaceNamesAndTerms(result, people, terms, report, [link, email, path, phone]);
return new BflAnonymization(result, report);
}
/// <summary>
/// Gets the parts of a name as the person listed it: without titles and remarks in parentheses, and in the order
/// first name, last name, also when the person wrote "Müller, Anna".
/// </summary>
/// <param name="name">The name.</param>
/// <returns>The parts, empty when nothing like a name remains.</returns>
internal static IReadOnlyList<string> PartsOfName(string name)
{
var cleaned = ParenthesesPattern().Replace(name.Normalize(NormalizationForm.FormC), " ").Replace("**", " ").Trim().Trim(',', ';', ':', '-', '–', '*', '_').Trim();
var commaParts = cleaned.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
if (commaParts.Length > 1)
{
// "Müller, Anna" names the last name first; "Anna Müller, TUM" adds a remark:
cleaned = commaParts.Length is 2 && !commaParts[0].Contains(' ') && !commaParts[1].Contains(' ') ? $"{commaParts[1]} {commaParts[0]}" : commaParts[0];
}
var parts = cleaned.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Select(part => part.Trim(',', ';', ':')).Where(part => part.Any(char.IsLetter)).ToList();
while (parts.Count > 0 && TitlePattern().IsMatch(parts[0]))
parts.RemoveAt(0);
return parts;
}
/// <summary>
/// Tells whether a word is a title which may stand before a name, e.g., "Prof." or "Dr.".
/// </summary>
/// <param name="word">The word.</param>
internal static bool IsTitle(string word) => TitlePattern().IsMatch(word);
/// <summary>
/// Replaces the names of people and the further terms.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="people">The names of people, one person each.</param>
/// <param name="terms">The further terms.</param>
/// <param name="report">What was replaced so far.</param>
/// <param name="fixedPlaceholders">The placeholders of links, e-mail addresses, paths, and phone numbers, which stay as they are.</param>
/// <returns>The text with placeholders.</returns>
private static string ReplaceNamesAndTerms(string text, IReadOnlyList<string> people, IReadOnlyList<string> terms, List<BflReplacement> report, IReadOnlyList<string> fixedPlaceholders)
{
var personLabel = TB("Person");
var termLabel = TB("Term");
var patterns = new List<BflNamePattern>();
var singleParts = new Dictionary<string, string>(StringComparer.Ordinal);
var ambiguous = Placeholder(personLabel);
var knownPeople = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var number = 0;
foreach (var name in people)
{
var parts = PartsOfName(name);
if (parts.Count is 0 || !knownPeople.Add(string.Join(' ', parts)))
continue;
var placeholder = Placeholder($"{personLabel} {++number}");
if (parts.Count is 1)
{
AddSinglePart(singleParts, parts[0], placeholder, ambiguous);
continue;
}
var first = parts[0];
var lastName = LastNameOf(parts);
patterns.Add(new(TITLES + string.Join(PART_SEPARATOR, parts.Select(PartPattern)), string.Join(' ', parts).Length, placeholder, true));
patterns.Add(new(PhrasePattern(lastName) + @"(?:,\s*|\s+|[._-])?" + PartPattern(first), lastName.Length + first.Length + 1, placeholder, true));
if (parts.Count > 2)
patterns.Add(new(TITLES + PartPattern(first) + PART_SEPARATOR + PhrasePattern(lastName), first.Length + lastName.Length + 1, placeholder, true));
AddSinglePart(singleParts, first, placeholder, ambiguous);
AddSinglePart(singleParts, lastName, placeholder, ambiguous);
if (lastName.Contains(' '))
AddSinglePart(singleParts, parts[^1], placeholder, ambiguous);
}
foreach (var (part, placeholder) in singleParts)
patterns.Add(new(TITLES + PhrasePattern(part), part.Length, placeholder, false));
var knownTerms = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
number = 0;
foreach (var term in terms)
{
var parts = term.Normalize(NormalizationForm.FormC).Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Where(part => part.Any(char.IsLetterOrDigit)).ToList();
if (parts.Count is 0 || !knownTerms.Add(string.Join(' ', parts)))
continue;
patterns.Add(new(string.Join(PART_SEPARATOR, parts.Select(PartPattern)), string.Join(' ', parts).Length, Placeholder($"{termLabel} {++number}"), true));
}
if (patterns.Count is 0)
return text;
// The longest names first, so that "Anna Schmidt-Weber" is not taken for "Anna Schmidt":
patterns = [.. patterns.OrderByDescending(pattern => pattern.Length)];
var expression = new StringBuilder();
expression.Append("(?<keep>");
foreach (var placeholder in fixedPlaceholders)
expression.Append(Regex.Escape(placeholder)).Append('|');
expression.Append(Regex.Escape($"[{personLabel}")).Append(@"(?: \d+)?\]|").Append(Regex.Escape($"[{termLabel}")).Append(@"(?: \d+)?\])");
for (var index = 0; index < patterns.Count; index++)
{
//
// A part of a name on its own must not be a part of a double name, e.g., "Schmidt" in "Müller-Schmidt",
// which may be somebody else. A full name or a term may stand in a longer word with a hyphen, e.g., in
// the address "anna-mueller-lab":
//
var pattern = patterns[index];
var groupIndex = index.ToString(CultureInfo.InvariantCulture);
expression.Append('|').Append(pattern.IgnoresCase ? BEFORE : BEFORE_PART);
expression.Append("(?<v").Append(groupIndex).Append('>').Append(pattern.IgnoresCase ? "(?i:" : "(?:").Append(pattern.Pattern).Append("))");
expression.Append("(?<s").Append(groupIndex).Append(">['’]s|['’]|s)?");
expression.Append(pattern.IgnoresCase ? AFTER : AFTER_PART);
}
var regex = new Regex(expression.ToString(), RegexOptions.CultureInvariant);
var nameGroups = Enumerable.Range(0, patterns.Count).Select(index => regex.GroupNumberFromName($"v{index.ToString(CultureInfo.InvariantCulture)}")).ToArray();
var suffixGroups = Enumerable.Range(0, patterns.Count).Select(index => regex.GroupNumberFromName($"s{index.ToString(CultureInfo.InvariantCulture)}")).ToArray();
return regex.Replace(text, match =>
{
if (match.Groups["keep"].Success)
return match.Value;
for (var index = 0; index < patterns.Count; index++)
{
// The genitive stays after the placeholder, e.g., "[Person 1]s":
var group = match.Groups[nameGroups[index]];
if (group.Success)
return Record(report, patterns[index].Placeholder, group.Value) + match.Groups[suffixGroups[index]].Value;
}
return match.Value;
});
}
/// <summary>
/// Gets the last name of a name with several parts: from its first particle on, e.g., "von der Leyen", otherwise
/// its last part.
/// </summary>
/// <param name="parts">The parts of the name, at least two.</param>
private static string LastNameOf(IReadOnlyList<string> parts)
{
for (var index = 1; index < parts.Count - 1; index++)
{
if (NAME_PARTICLES.Contains(parts[index]))
return string.Join(' ', parts.Skip(index));
}
return parts[^1];
}
/// <summary>
/// Adds a part of a name which the anonymizer replaces on its own; a part several people share gets the
/// placeholder without a number.
/// </summary>
/// <param name="singleParts">The parts so far, with their placeholders.</param>
/// <param name="part">The part, e.g., a first name.</param>
/// <param name="placeholder">The placeholder of the person.</param>
/// <param name="ambiguous">The placeholder without a number.</param>
private static void AddSinglePart(Dictionary<string, string> singleParts, string part, string placeholder, string ambiguous)
{
if (part.Count(char.IsLetter) < MIN_PART_LETTERS || NAME_PARTICLES.Contains(part))
return;
singleParts[part] = singleParts.TryGetValue(part, out var known) && known != placeholder ? ambiguous : placeholder;
}
/// <summary>
/// Gets the pattern of several parts of a name which stand one after the other, e.g., "von der Leyen".
/// </summary>
/// <param name="phrase">The parts, separated by spaces.</param>
private static string PhrasePattern(string phrase) => string.Join(@"\s+", phrase.Split(' ').Select(PartPattern));
/// <summary>
/// Gets the pattern of one part of a name: umlauts match their spellings with and without them, letters with
/// accents also without them, and the period of an initial may be missing.
/// </summary>
/// <param name="part">The part of the name.</param>
private static string PartPattern(string part)
{
var pattern = new StringBuilder();
for (var index = 0; index < part.Length; index++)
{
var character = part[index];
var next = index + 1 < part.Length ? part[index + 1] : '\0';
if (next is 'e' or 'E' && character is 'a' or 'o' or 'u' or 'A' or 'O' or 'U')
{
// A name written as "Mueller" also stands for "Müller":
pattern.Append("(?:").Append(Regex.Escape(part.Substring(index, 2))).Append('|').Append(UmlautOf(character)).Append(')');
index++;
continue;
}
if (character is 's' && next is 's')
{
pattern.Append("(?:ss|ß)");
index++;
continue;
}
pattern.Append(character switch
{
'ä' => "(?:ä|ae|a)",
'ö' => "(?:ö|oe|o)",
'ü' => "(?:ü|ue|u)",
'Ä' => "(?:Ä|Ae|AE|A)",
'Ö' => "(?:Ö|Oe|OE|O)",
'Ü' => "(?:Ü|Ue|UE|U)",
'ß' => "(?:ß|ss)",
// A double name may lose its hyphen in an address, e.g., "MuellerLuedenscheidt":
'-' or '‐' or '‑' => "[-‐‑._]?",
'\'' or '’' => "['’]",
'.' => @"\.?",
_ => LetterPattern(character),
});
}
return pattern.ToString();
}
/// <summary>
/// Gets the umlaut of a vowel, e.g., "ü" for "u".
/// </summary>
/// <param name="vowel">The vowel a, o, or u, in either case.</param>
private static string UmlautOf(char vowel) => vowel switch
{
'a' => "ä",
'o' => "ö",
'u' => "ü",
'A' => "Ä",
'O' => "Ö",
_ => "Ü",
};
/// <summary>
/// Gets the pattern of a letter, which matches a letter with an accent also without it.
/// </summary>
/// <param name="character">The letter.</param>
private static string LetterPattern(char character)
{
var decomposed = character.ToString().Normalize(NormalizationForm.FormD);
if (decomposed.Length > 1 && decomposed.Skip(1).All(mark => CharUnicodeInfo.GetUnicodeCategory(mark) is UnicodeCategory.NonSpacingMark))
return $"(?:{Regex.Escape(character.ToString())}|{Regex.Escape(decomposed[..1])})";
return Regex.Escape(character.ToString());
}
/// <summary>
/// Tells whether a run of digits is a phone number rather than a date, a time, or a decimal number.
/// </summary>
/// <param name="candidate">The run of digits, as the pattern found it.</param>
private static bool IsPhoneNumber(string candidate) => candidate.Count(char.IsDigit) >= MIN_PHONE_DIGITS && !NotAPhoneNumberPattern().IsMatch(candidate);
/// <summary>
/// Replaces an address or a path, but leaves the punctuation after it, which belongs to the sentence.
/// </summary>
/// <param name="report">What was replaced so far.</param>
/// <param name="placeholder">The placeholder.</param>
/// <param name="value">What the pattern found.</param>
/// <returns>The placeholder and the punctuation after it.</returns>
private static string ReplaceWithoutEnd(List<BflReplacement> report, string placeholder, string value)
{
var length = value.Length;
while (length > 0)
{
var last = value[length - 1];
var opened = value[..length].Count(character => character == OpeningOf(last));
var closed = value[..length].Count(character => character == last);
if (last is '.' or ',' or ';' or ':' or '!' or '?' or '*' or '_' or '\'' or '"' || last is ')' or ']' or '}' && closed > opened)
length--;
else
break;
}
return length is 0 ? value : Record(report, placeholder, value[..length]) + value[length..];
}
/// <summary>
/// Gets the opening bracket of a closing one, or a character no text holds.
/// </summary>
/// <param name="closing">The closing bracket.</param>
private static char OpeningOf(char closing) => closing switch
{
')' => '(',
']' => '[',
'}' => '{',
_ => '\0',
};
/// <summary>
/// Notes a replacement in the report.
/// </summary>
/// <param name="report">What was replaced so far.</param>
/// <param name="placeholder">The placeholder.</param>
/// <param name="original">What it replaces.</param>
/// <returns>The placeholder.</returns>
private static string Record(List<BflReplacement> report, string placeholder, string original)
{
var index = report.FindIndex(replacement => replacement.Placeholder == placeholder && replacement.Original == original);
if (index < 0)
report.Add(new BflReplacement(placeholder, original, 1));
else
report[index] = report[index] with { Count = report[index].Count + 1 };
return placeholder;
}
/// <summary>
/// Gets a placeholder, e.g., "[Person 1]".
/// </summary>
/// <param name="label">What it stands for.</param>
private static string Placeholder(string label) => $"[{label}]";
/// <summary>
/// A link in Markdown, whose text stays and whose address goes.
/// </summary>
[GeneratedRegex("""\[(?<label>[^\]\n]*)\]\(\s*<?(?<url>(?:[a-z][a-z0-9+.-]*:|www\.)[^\s<>()]*(?:\([^\s<>()]*\)[^\s<>()]*)*)>?(?:\s+"[^"\n]*")?\s*\)""", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex MarkdownLinkPattern();
/// <summary>
/// An address in angle brackets, e.g., "&lt;https://example.org&gt;".
/// </summary>
[GeneratedRegex(@"<(?<url>(?:https?|ftp|file|mailto):[^\s<>]+)>", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex AutoLinkPattern();
/// <summary>
/// An address of a web page or a file, with its scheme or beginning with "www.".
/// </summary>
[GeneratedRegex(@"(?<![\p{L}\p{N}@.])(?:(?:https?|ftp|file)://|www\.)[^\s<>""'`]+", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)]
private static partial Regex UrlPattern();
/// <summary>
/// An e-mail address.
/// </summary>
[GeneratedRegex(@"(?<![\p{L}\p{N}._%+-])[\p{L}\p{N}._%+-]+@[\p{L}\p{N}-]+(?:\.[\p{L}\p{N}-]+)*\.\p{L}{2,}", RegexOptions.CultureInvariant)]
private static partial Regex EmailPattern();
/// <summary>
/// A path of a file or a folder: on Windows with its drive or its server, otherwise beginning with "/" or "~" and
/// with at least two folders.
/// </summary>
[GeneratedRegex(@"(?<![\p{L}\p{N}])[A-Za-z]:[\\/][^\s""<>|*?]*|\\\\[^\s\\""<>|*?]+(?:\\[^\s""<>|*?]*)+|%[A-Za-z_]+%\\[^\s""<>|*?]*|(?<![\p{L}\p{M}\p{N}/.:~\\\])_-])(?:(?:~|\$HOME)(?:/[\p{L}\p{M}\p{N}._@+-]+)+|(?:/[\p{L}\p{M}\p{N}._@+-]+){2,})/?", RegexOptions.CultureInvariant)]
private static partial Regex PathPattern();
/// <summary>
/// A run which may be a phone number: beginning with "+" or "0", with spaces, periods, slashes, hyphens, or
/// parentheses between the digits; IsPhoneNumber decides.
/// </summary>
[GeneratedRegex(@"(?<![\p{L}\p{N}+(])\(?(?:\+|0)\d[\d \t./()-]{5,}\d(?![\p{L}\p{N}])", RegexOptions.CultureInvariant)]
private static partial Regex PhonePattern();
/// <summary>
/// What looks like a phone number but is not: a date, a span of time, or a decimal number.
/// </summary>
[GeneratedRegex(@"^\(?\d{1,2}\.\d{1,2}\.(?:\d{4}|\d{2})$|^\d{1,2}[.:]\d{2}\s*-\s*\d{1,2}[.:]\d{2}$|^0[.,]", RegexOptions.CultureInvariant)]
private static partial Regex NotAPhoneNumberPattern();
/// <summary>
/// A remark in parentheses after a name, e.g., "(TUM)".
/// </summary>
[GeneratedRegex(@"\([^)]*\)", RegexOptions.CultureInvariant)]
private static partial Regex ParenthesesPattern();
/// <summary>
/// A title on its own, e.g., "Prof." or "Dr.".
/// </summary>
[GeneratedRegex($@"^{TITLE}\.?$", RegexOptions.CultureInvariant)]
private static partial Regex TitlePattern();
}
@@ -0,0 +1,176 @@
using System.Text.Json.Serialization;
namespace AIStudio.Assistants.BeyondFactsLab;
/// <summary>
/// How the person sorted the values of the deck in the step "Values and perspectives" of the BeyondFacts Lab: a
/// category for each value, the values the deck misses, and the two or three values to look at more closely.
/// </summary>
/// <remarks>
/// The card sort belongs to the details of its step and is stored with them, see BflStepFormData.CardSort. Every part
/// is voluntary and stays changeable: a value without a category stays open, and the step can be finished without
/// any sorting. The methods keep the limits. A category or a choice whose value the deck does not know, e.g., one of
/// another version of the deck, stays stored but shows nowhere, see FocusIn.
/// </remarks>
public sealed class BflCardSort
{
/// <summary>
/// How many values of their own a person may add.
/// </summary>
public const int MAX_OWN_VALUES = 10;
/// <summary>
/// How many characters the name of an own value may have.
/// </summary>
public const int MAX_NAME_LENGTH = 60;
/// <summary>
/// How many characters the definition of an own value may have.
/// </summary>
public const int MAX_DEFINITION_LENGTH = 300;
/// <summary>
/// How many values a person may choose to look at more closely: two or three, after Lara Wüster's dialogue logic.
/// </summary>
public const int MAX_FOCUS = 3;
/// <summary>
/// Gets or sets the category of each value the person sorted, by the ID of the value in the deck.
/// </summary>
public Dictionary<string, BflValueCategory> Categories { get; set; } = new(StringComparer.Ordinal);
/// <summary>
/// Gets or sets the values the person added, in the order they added them.
/// </summary>
public List<BflOwnValue> OwnValues { get; set; } = [];
/// <summary>
/// Gets or sets the IDs of the values the person wants to look at more closely, of the deck or their own, in the
/// order they chose them. The order is no ranking.
/// </summary>
public List<string> Focus { get; set; } = [];
/// <summary>
/// Gets whether the person has neither sorted a value, nor added one, nor chosen one to look at more closely.
/// </summary>
[JsonIgnore]
public bool IsEmpty => this.Categories.Values.All(category => category is BflValueCategory.NONE) && this.OwnValues.Count is 0 && this.Focus.Count is 0;
/// <summary>
/// Gets whether the person may add another value of their own.
/// </summary>
[JsonIgnore]
public bool CanAddOwnValue => this.OwnValues.Count < MAX_OWN_VALUES;
/// <summary>
/// Gets the category of a value of the deck.
/// </summary>
/// <param name="valueId">The ID of the value.</param>
/// <returns>The category, or NONE when the person has not sorted the value.</returns>
public BflValueCategory CategoryOf(string valueId) => this.Categories.GetValueOrDefault(valueId, BflValueCategory.NONE);
/// <summary>
/// Sorts a value of the deck into a category; NONE leaves it open again.
/// </summary>
/// <param name="valueId">The ID of the value.</param>
/// <param name="category">The category.</param>
public void Sort(string valueId, BflValueCategory category)
{
if (category is BflValueCategory.NONE)
this.Categories.Remove(valueId);
else
this.Categories[valueId] = category;
}
/// <summary>
/// Adds a value which the deck misses.
/// </summary>
/// <param name="name">The name of the value; spaces around it do not count, and a longer name is cut.</param>
/// <param name="definition">What the value means to the person; it may be empty, and a longer one is cut.</param>
/// <returns>The value, or null when the name is empty or the person has added as many values as they may.</returns>
public BflOwnValue? AddOwnValue(string name, string definition)
{
var limitedName = Limit(name, MAX_NAME_LENGTH);
if (limitedName.Length is 0 || !this.CanAddOwnValue)
return null;
var value = new BflOwnValue { Id = Guid.NewGuid().ToString("N"), Name = limitedName, Definition = Limit(definition, MAX_DEFINITION_LENGTH) };
this.OwnValues.Add(value);
return value;
}
/// <summary>
/// Changes the name and the definition of a value of the person.
/// </summary>
/// <param name="valueId">The ID of the value.</param>
/// <param name="name">The new name; spaces around it do not count, and a longer name is cut.</param>
/// <param name="definition">The new definition; it may be empty, and a longer one is cut.</param>
/// <returns>True when the value changed; false when the person has no such value or the name is empty.</returns>
public bool ChangeOwnValue(string valueId, string name, string definition)
{
var limitedName = Limit(name, MAX_NAME_LENGTH);
if (limitedName.Length is 0 || this.OwnValues.FirstOrDefault(candidate => string.Equals(candidate.Id, valueId, StringComparison.Ordinal)) is not { } value)
return false;
value.Name = limitedName;
value.Definition = Limit(definition, MAX_DEFINITION_LENGTH);
return true;
}
/// <summary>
/// Removes a value of the person, also from the values to look at more closely.
/// </summary>
/// <param name="valueId">The ID of the value.</param>
public void RemoveOwnValue(string valueId)
{
this.OwnValues.RemoveAll(candidate => string.Equals(candidate.Id, valueId, StringComparison.Ordinal));
this.Focus.RemoveAll(candidate => string.Equals(candidate, valueId, StringComparison.Ordinal));
}
/// <summary>
/// Chooses the values to look at more closely. The values chosen before keep their place; of the new ones, only
/// as many are taken as fit within MAX_FOCUS.
/// </summary>
/// <param name="valueIds">The IDs of all values the person wants to look at more closely.</param>
public void ChooseFocus(IReadOnlyCollection<string> valueIds)
{
var focus = this.Focus.Where(valueIds.Contains).Distinct(StringComparer.Ordinal).ToList();
foreach (var valueId in valueIds)
{
if (focus.Count >= MAX_FOCUS)
break;
if (!focus.Contains(valueId, StringComparer.Ordinal))
focus.Add(valueId);
}
this.Focus = focus;
}
/// <summary>
/// Gets the values to look at more closely which exist, in the deck or among the values of the person, at most
/// MAX_FOCUS of them in the order the person chose them.
/// </summary>
/// <param name="deck">The deck the person sorted.</param>
/// <returns>The IDs of the values.</returns>
public IReadOnlyList<string> FocusIn(BflValueDeck deck) => [.. this.Focus.Distinct(StringComparer.Ordinal).Where(valueId => this.NameOf(valueId, deck) is not null).Take(MAX_FOCUS)];
/// <summary>
/// Gets the name of a value, of the deck or of the person.
/// </summary>
/// <param name="valueId">The ID of the value.</param>
/// <param name="deck">The deck the person sorted.</param>
/// <returns>The name, or null when neither the deck nor the person has such a value.</returns>
public string? NameOf(string valueId, BflValueDeck deck) => deck.Find(valueId)?.Name ?? this.OwnValues.FirstOrDefault(candidate => string.Equals(candidate.Id, valueId, StringComparison.Ordinal))?.Name;
/// <summary>
/// Trims a text and cuts it to a number of characters.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="maxLength">The number of characters.</param>
private static string Limit(string? text, int maxLength)
{
var trimmed = (text ?? string.Empty).Trim();
return trimmed.Length > maxLength ? trimmed[..maxLength].TrimEnd() : trimmed;
}
}
@@ -0,0 +1,21 @@
@inherits MSGComponentBase
<EmbeddedChat Store="@this.ConversationService.StoreOf(this.Location)"
Component="@Components.BEYOND_FACTS_LAB_ASSISTANT"
ChatId="@this.Location.ChatId"
CreateThread="@this.CreateThread"
Provider="@this.Provider"
PrepareAsync="@this.prepareAsync"
ProviderIssue="@this.ProviderIssue"
Heading="@(this.ShowHeading ? T("Conversation") : null)"
StartRequest="@BflConversationService.OpeningRequestFor(this.Location)"
Introduction="@this.Introduction"
ExportFileName="@this.ExportFileName"
AllowsReset="true"
ResetQuestion="@this.ResetQuestion"
AllowsAttachments="false"
ShowsContextWindow="true"
AllowsCompression="true"
SystemPromptForCountAsync="@this.systemPromptForCountAsync"
ContextVersion="@this.ContextVersion"
QuickMessage="@this.QuickMessage"/>
@@ -0,0 +1,187 @@
using AIStudio.Chat;
using AIStudio.Chat.Embedded;
using AIStudio.Components;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Assistants.BeyondFactsLab;
/// <summary>
/// A chat of the BeyondFacts Lab, such as the one of a step below its form "Your details".
/// </summary>
/// <remarks>
/// The embedded chat of assistants with what the lab decides for each of its places: the opening request, the
/// introduction, the question before starting over, and, for every request, the system prompt with the guide, the
/// details, and the material, and the guidelines of the organization in front of the first message, see
/// BflConversationService.PrepareAsync. The count of tokens shows how full the context
/// of the model is, since every request carries the guide. It offers no "send to": the lab neither receives content
/// from other assistants nor hands its answers on.
/// </remarks>
public partial class BflChat : MSGComponentBase
{
/// <summary>
/// Gets or sets where the chat to show belongs, e.g., to a step of a preparation.
/// </summary>
[Parameter, EditorRequired]
public BflThreadLocation Location { get; set; } = null!;
/// <summary>
/// Gets or sets whether the chat shows a heading of its own; it needs none where its place already names it.
/// </summary>
[Parameter]
public bool ShowHeading { get; set; } = true;
/// <summary>
/// Gets or sets the provider which answers.
/// </summary>
[Parameter, EditorRequired]
public AIStudio.Settings.Provider Provider { get; set; } = Settings.Provider.NONE;
/// <summary>
/// Gets or sets why the provider cannot answer, or null when it can.
/// </summary>
[Parameter]
public string? ProviderIssue { get; set; }
/// <summary>
/// Gets or sets a number which changes whenever a detail changes which takes much room in the next request, such as
/// whom the step "Test situation" simulates, whose research the prompt carries.
/// </summary>
[Parameter]
public int DetailsVersion { get; set; }
[Inject]
private BflConversationService ConversationService { get; init; } = null!;
[Inject]
private BflMaterialService MaterialService { get; init; } = null!;
[Inject]
private ILogger<BflChat> Logger { get; init; } = null!;
/// <summary>
/// Readies a request of the chat shown, with the provider chosen; made anew whenever either changes.
/// </summary>
private Func<ChatThread, Task<EmbeddedChatPreparation>> prepareAsync = _ => Task.FromResult(EmbeddedChatPreparation.REFUSED);
/// <summary>
/// Gets what the next request of the chat shown carries beside the conversation, for the count of tokens; made anew
/// whenever the chat or the provider changes.
/// </summary>
private Func<Task<string?>> systemPromptForCountAsync = () => Task.FromResult<string?>(null);
/// <summary>
/// Changes whenever the material of the preparation changes, since every request of a step carries it.
/// </summary>
private int materialsVersion;
/// <summary>
/// Gets a number which changes whenever what the next request carries beside the conversation changed: the
/// material, the guidelines of the organization after a configuration plugin was reloaded, or a detail which takes
/// much room, see DetailsVersion.
/// </summary>
private int ContextVersion => HashCode.Combine(this.materialsVersion, this.SettingsManager.ConfigurationData.BeyondFactsLab.OrganizationRules, this.DetailsVersion);
/// <summary>
/// Gets what the chat says before its conversation begins.
/// </summary>
private string Introduction => this.Location switch
{
BflOnboardingThreadLocation => TA("Tell the lab what you are preparing for. It tells you whether it fits your task and how to work with it. You can also let the lab begin."),
_ => TA("The lab opens the conversation of this step with what your details already say, and asks for what is missing. You can also write first.")
};
/// <summary>
/// Gets the name a message gets when the person exports it.
/// </summary>
private string ExportFileName => this.Location switch
{
BflStepThreadLocation stepLocation => stepLocation.Step.Title,
_ => T("Is the lab right for my task?")
};
/// <summary>
/// Gets the question before the conversation starts over.
/// </summary>
private string ResetQuestion => this.Location switch
{
BflStepThreadLocation => TA("Delete the conversation of this step and start it over? Your details stay as they are."),
_ => TA("Delete this conversation and start it over?")
};
/// <summary>
/// Gets the button with which the person ends an exercise of the step "Test situation" and asks for its evaluation,
/// see Prompts/steps/test.md; the other chats have none.
/// </summary>
private EmbeddedChatQuickMessage? QuickMessage => this.Location is BflStepThreadLocation { Step: BflStep.TEST_SITUATION }
? new(T("End and evaluate the exercise"), AppIcons.END_EXERCISE, T("I would like to end the exercise now and get its evaluation."), TA("This button ends the exercise, and the lab evaluates it. While the lab simulates people, it gives feedback only then; write 'Pause' to get brief feedback in between."))
: null;
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
this.MaterialService.MaterialsChanged += this.OnMaterialsChangedAsync;
await base.OnInitializedAsync();
}
/// <inheritdoc />
protected override async Task OnParametersSetAsync()
{
await base.OnParametersSetAsync();
// Bound to the chat and the provider shown now, so that a request never takes those of the next render:
var location = this.Location;
var provider = this.Provider;
this.prepareAsync = thread => this.ConversationService.PrepareAsync(location, provider, thread);
this.systemPromptForCountAsync = () => this.SystemPromptForCountAsync(location, provider);
}
/// <inheritdoc />
protected override void DisposeResources()
{
this.MaterialService.MaterialsChanged -= this.OnMaterialsChangedAsync;
base.DisposeResources();
}
/// <summary>
/// Creates the chat of the place shown, for a place which has no stored chat yet.
/// </summary>
private ChatThread CreateThread() => BflThreadFactory.Create(this.Location);
/// <summary>
/// Lets the chat count again when the material of the preparation changed.
/// </summary>
/// <param name="projectId">The ID of the preparation whose material changed.</param>
private Task OnMaterialsChangedAsync(Guid projectId)
{
if (this.Location is not BflStepThreadLocation stepLocation || stepLocation.ProjectId != projectId)
return Task.CompletedTask;
return this.InvokeAsync(() =>
{
this.materialsVersion++;
this.StateHasChanged();
});
}
/// <summary>
/// Puts together what the next request of a chat carries beside the conversation, for the count of tokens: the
/// system prompt, and the guidelines of the organization in front of the first message.
/// </summary>
/// <param name="location">Where the chat belongs.</param>
/// <param name="provider">The provider which answers.</param>
/// <returns>The text to count, or null when it cannot be put together now.</returns>
private async Task<string?> SystemPromptForCountAsync(BflThreadLocation location, AIStudio.Settings.Provider provider)
{
try
{
return await this.ConversationService.ComposeTextForCountAsync(location, provider);
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or FormatException)
{
// Sending reports the same problem; the count only stays unknown:
this.Logger.LogDebug(exception, "Could not count the tokens of a chat in the BeyondFacts Lab.");
return null;
}
}
}
@@ -0,0 +1,38 @@
using AIStudio.Chat;
using AIStudio.Chat.Embedded;
namespace AIStudio.Assistants.BeyondFactsLab;
/// <summary>
/// Lets the embedded chat of a place of the BeyondFacts Lab live where the lab keeps it, e.g., in the folder of a step
/// of a preparation.
/// </summary>
/// <remarks>
/// The ID of a chat of the lab follows from its place, see BflThreadId, so the store serves the one chat of its place
/// and refuses any other. Files, paths, and locks stay those of BeyondFactsLabStore, so chats stored before keep
/// working, and the cleanup of the provenance store still finds every chat, see
/// BeyondFactsLabStore.ReadAllThreadLocations.
/// </remarks>
/// <param name="store">The store of the lab.</param>
/// <param name="location">The place of the chat.</param>
public sealed class BflChatStore(BeyondFactsLabStore store, BflThreadLocation location) : IEmbeddedChatStore
{
/// <inheritdoc />
public Task<ChatThread?> LoadThreadAsync(Guid chatId, CancellationToken token = default) => store.LoadThreadAsync(this.LocationOf(chatId), token);
/// <inheritdoc />
public Task SaveThreadAsync(ChatThread thread, CancellationToken token = default) => store.SaveThreadAsync(this.LocationOf(thread.ChatId), thread, token);
/// <inheritdoc />
public Task DeleteThreadAsync(Guid chatId, CancellationToken token = default) => store.DeleteThreadAsync(this.LocationOf(chatId), token);
/// <summary>
/// Gets the place of a chat, which must be the place of this store.
/// </summary>
/// <param name="chatId">The ID of the chat.</param>
/// <returns>The place of the store.</returns>
/// <exception cref="ArgumentException">The chat belongs to another place.</exception>
private BflThreadLocation LocationOf(Guid chatId) => chatId == location.ChatId
? location
: throw new ArgumentException("The chat belongs to another place of the lab.", nameof(chatId));
}
Loaded 100 of 1395 files, more files were not shown because too many files have changed in this diff. Show more