Moved the background agents to AI operations (#1215)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-21 19:47:10 +01:00
1 parent 8a4a26503b
commit c50a93cd17
139 files changed
+4069 -2340

No files matched your search

@@ -10,7 +10,7 @@ namespace AIStudio.Tools;
/// The selected data sources are a subset of the allowed data sources.
///
/// The data sources waiting for a re-index are deliberately kept apart from the allowed ones rather
/// than mixed in. Everything reading the allowed list -- the data source selection agent above all
/// than mixed in. Everything reading the allowed list -- the data source selection above all
/// -- takes it to mean "may be used to answer with", and a source whose index is being rebuilt
/// cannot answer anything. It is listed separately so the user interface can still show it and say
/// why it is greyed out, instead of letting it vanish without a word.
+12 -12
View File
@@ -26,21 +26,12 @@ public static class AppIcons
/// <summary>Shows or hides advanced or expert settings.</summary>
public const string ADVANCED_SETTINGS = LucideIcons.SLIDERS_HORIZONTAL;
/// <summary>Marks an AI agent that works in the background, such as the security audit agent or the content cleaner when it has no usable provider.</summary>
public const string AGENT = LucideIcons.BOT;
/// <summary>Marks the agent that cleans text content, such as removing navigation and ads from a loaded web page.</summary>
public const string AGENT_CONTENT_CLEANER = LucideIcons.BRUSH_CLEANING;
/// <summary>Marks the agent that selects the data sources for a request.</summary>
public const string AGENT_DATA_SOURCE_SELECTION = LucideIcons.LIST_CHECKS;
/// <summary>Marks the agent that validates retrieval contexts.</summary>
public const string AGENT_RETRIEVAL_CONTEXT_VALIDATION = LucideIcons.LIST_CHECKS;
/// <summary>Marks the AI, such as its role in a chat.</summary>
public const string AI = LucideIcons.SPARKLES;
/// <summary>Marks a task which AI Studio hands to a model on its own, such as the security audit or the text content cleaner, e.g., when it has no usable provider.</summary>
public const string AI_OPERATION = LucideIcons.BOT;
/// <summary>Marks the data sources that the AI selected for a question.</summary>
public const string AI_SELECTED_DATA_SOURCES = LucideIcons.LIST_FILTER;
@@ -347,6 +338,9 @@ public static class AppIcons
/// <summary>Shows that the data sources need no attention, because nothing is indexing and nothing failed.</summary>
public const string DATA_SOURCES_UP_TO_DATE = LucideIcons.DATABASE_CHECK;
/// <summary>Marks the task in which a model selects the data sources for a request.</summary>
public const string DATA_SOURCE_SELECTION = LucideIcons.LIST_CHECKS;
/// <summary>Marks a single value in a data tree, such as a JSON value or another value of a plugin.</summary>
public const string DATA_VALUE = LucideIcons.VARIABLE;
@@ -983,6 +977,9 @@ public static class AppIcons
/// <summary>Transcribes an audio or video source again.</summary>
public const string RETRANSCRIBE = LucideIcons.AUDIO_LINES;
/// <summary>Marks the task in which a model validates the retrieval contexts for a request.</summary>
public const string RETRIEVAL_CONTEXT_VALIDATION = LucideIcons.LIST_CHECKS;
/// <summary>Reports that a data source could not be searched, so the search results are incomplete.</summary>
public const string RETRIEVAL_GAP = LucideIcons.SEARCH_EXCLAMATION_POINT;
@@ -1157,6 +1154,9 @@ public static class AppIcons
/// <summary>Marks the choice of how complex a text should be.</summary>
public const string TEXT_COMPLEXITY = LucideIcons.LAYERS;
/// <summary>Marks the task which cleans text content, such as removing navigation and ads from a loaded web page.</summary>
public const string TEXT_CONTENT_CLEANER = LucideIcons.BRUSH_CLEANING;
/// <summary>Marks a single-line text input, such as the text component of an assistant plugin.</summary>
public const string TEXT_INPUT = LucideIcons.TEXT_CURSOR_INPUT;
@@ -33,7 +33,7 @@ public static class ComponentsExtensions
/// <remarks>
/// This is the single place that maps a built-in assistant to its category. The assistants page
/// shows the assistant in the section of this category, and whatever offers assistants elsewhere
/// asks it, too. Components which are no assistant of their own, such as the chat or the agents,
/// asks it, too. Components which are no assistant of their own, such as the chat or the AI operations,
/// return PluginCategory.NONE.
/// </remarks>
/// <value>The category of the assistant.</value>
@@ -223,6 +223,11 @@ public static class ComponentsExtensions
Components.BATCH_PROCESSING_ASSISTANT => settingsManager.ConfigurationData.BatchProcessing.PreselectOptions ? settingsManager.ConfigurationData.BatchProcessing.MinimumProviderConfidence : default,
Components.MODEL_COMPARISON_ASSISTANT => settingsManager.ConfigurationData.ModelComparison.PreselectOptions ? settingsManager.ConfigurationData.ModelComparison.MinimumProviderConfidence : default,
Components.AGENT_TEXT_CONTENT_CLEANER => settingsManager.ConfigurationData.TextContentCleaner.PreselectAgentOptions ? settingsManager.ConfigurationData.TextContentCleaner.MinimumProviderConfidence : default,
Components.AGENT_DATA_SOURCE_SELECTION => settingsManager.ConfigurationData.AgentDataSourceSelection.PreselectAgentOptions ? settingsManager.ConfigurationData.AgentDataSourceSelection.MinimumProviderConfidence : default,
Components.AGENT_RETRIEVAL_CONTEXT_VALIDATION => settingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectAgentOptions ? settingsManager.ConfigurationData.AgentRetrievalContextValidation.MinimumProviderConfidence : default,
Components.AGENT_ASSISTANT_PLUGIN_AUDIT => settingsManager.ConfigurationData.AssistantPluginAudit.MinimumProviderConfidence,
_ => default,
};
@@ -263,11 +268,7 @@ public static class ComponentsExtensions
// Dynamic assistants have no dedicated settings yet, so they derive their defaults from the chat:
Components.DYNAMIC_ASSISTANT or Components.CHAT => settingsManager.ConfigurationData.Chat.PreselectOptions ? settingsManager.GetProviderById(settingsManager.ConfigurationData.Chat.PreselectedProvider) : Settings.Provider.NONE,
Components.AGENT_TEXT_CONTENT_CLEANER => settingsManager.ConfigurationData.TextContentCleaner.PreselectAgentOptions ? settingsManager.GetProviderById(settingsManager.ConfigurationData.TextContentCleaner.PreselectedAgentProvider) : Settings.Provider.NONE,
Components.AGENT_DATA_SOURCE_SELECTION => settingsManager.ConfigurationData.AgentDataSourceSelection.PreselectAgentOptions ? settingsManager.GetProviderById(settingsManager.ConfigurationData.AgentDataSourceSelection.PreselectedAgentProvider) : Settings.Provider.NONE,
Components.AGENT_RETRIEVAL_CONTEXT_VALIDATION => settingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectAgentOptions ? settingsManager.GetProviderById(settingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectedAgentProvider) : Settings.Provider.NONE,
Components.AGENT_ASSISTANT_PLUGIN_AUDIT => settingsManager.GetProviderById(settingsManager.ConfigurationData.AssistantPluginAudit.PreselectedAgentProvider),
// The AI operations choose their provider through AIOperationProviderResolver, see AIOperations/AGENTS.md.
_ => Settings.Provider.NONE,
};
@@ -24,7 +24,7 @@ and whoever runs it: loading, starting, checking an import, and the assistant bu
## Assistant plugins
Every prompt text an assistant plugin brings, its `SystemPrompt` as well as its `CustomChatSystemPrompt`, goes
through `PluginAssistants.BuildSecureSystemPrompt` and into the security audit of `AssistantAuditAgent`. A new
through `PluginAssistants.BuildSecureSystemPrompt` and into the security audit of `PluginAuditOperation`. A new
field which reaches a model as a prompt needs both, and its documentation in `Plugins/assistants/README.md` and in
the template `Plugins/assistants/plugin.lua`: the Assistant Builder reads both files as its source of truth.
@@ -1,21 +1,47 @@
using AIStudio.Agents.AssistantAudit;
using AIStudio.AIOperations;
using AIStudio.AIOperations.PluginAudit;
using AIStudio.Provider;
using AIStudio.Settings;
namespace AIStudio.Tools.PluginSystem.Assistants;
/// <summary>
/// Runs an assistant security audit and maps the agent result to the persisted audit model.
/// Runs the security audit of an assistant plugin and maps its result to the persisted audit model.
/// </summary>
public sealed class AssistantPluginAuditService(AssistantAuditAgent auditAgent)
public sealed class AssistantPluginAuditService(PluginAuditOperation auditOperation, AIOperationProviderResolver providerResolver, SettingsManager settingsManager)
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(AssistantPluginAuditService).Namespace, nameof(AssistantPluginAuditService));
private static string TA(string fallbackEN) => I18N.I.TA(fallbackEN, typeof(AssistantPluginAuditService).Namespace, nameof(AssistantPluginAuditService));
/// <summary>
/// Runs an assistant plugin audit, optionally falling back to the supplied provider when no audit provider is configured.
/// </summary>
public async Task<PluginAssistantAudit> RunAuditAsync(PluginAssistants plugin, Settings.Provider? fallbackProvider = null, CancellationToken token = default)
/// <param name="plugin">The plugin to audit.</param>
/// <param name="providerAtHand">A provider somebody picked for something else, e.g., the assistant they are building; the audit falls back on it last.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The audit, which names the provider it ran with.</returns>
public async Task<PluginAssistantAudit> RunAuditAsync(PluginAssistants plugin, Settings.Provider? providerAtHand = null, CancellationToken token = default)
{
var result = await auditAgent.AuditAsync(plugin, fallbackProvider, token);
var provider = auditAgent.ProviderSettings;
var promptPreview = await plugin.BuildAuditPromptPreviewAsync(token);
var request = new PluginAuditRequest(plugin);
var choice = providerResolver.Resolve(auditOperation, request, PluginAuditOperation.GetProviderSettings(settingsManager), GetProviderOptions(settingsManager, providerAtHand));
PluginAuditResult result;
if (choice.HasProvider)
result = await auditOperation.RunAsync(request, new(choice.Provider), token);
else
{
var issue = GetRelevantIssue(choice);
await MessageBus.INSTANCE.SendError(new (AppIcons.AI_OPERATION, GetMissingProviderMessage(issue)));
result = new PluginAuditResult
{
Level = nameof(PluginAuditLevel.UNKNOWN),
Summary = GetMissingProviderSummary(issue),
};
}
var provider = choice.Provider;
var promptPreview = await plugin.BuildAuditPromptPreviewAsync(token);
return new PluginAssistantAudit
{
PluginId = plugin.Id,
@@ -25,11 +51,123 @@ public sealed class AssistantPluginAuditService(AssistantAuditAgent auditAgent)
AuditProviderName = provider == Settings.Provider.NONE
? string.Empty
: provider.InstanceName,
Level = AssistantAuditLevel.ParseOrUnknown(result.Level),
Level = PluginAuditLevel.ParseOrUnknown(result.Level),
Summary = result.Summary,
Confidence = result.Confidence,
PromptPreview = promptPreview,
Findings = result.Findings,
};
}
/// <summary>
/// Audits every running assistant plugin which needs an audit, as long as automatic audits are switched on.
/// </summary>
/// <remarks>
/// In the background, there is no provider at hand. Should no provider be left for a plugin, its audit would
/// fail without a request, and the user would get two messages for each plugin, again with every visit of the
/// assistants or plugins page. Such a plugin is therefore skipped, and a single message says why.
/// </remarks>
/// <param name="token">The cancellation token.</param>
/// <returns>The audits which succeeded, for the caller to store.</returns>
public async Task<IReadOnlyList<PluginAssistantAudit>> RunAutomaticAuditsAsync(CancellationToken token = default)
{
if (!settingsManager.ConfigurationData.AssistantPluginAudit.AutomaticallyAuditAssistants)
return [];
var audits = new List<PluginAssistantAudit>();
AIOperationProviderIssue? issueOfSkippedPlugins = null;
foreach (var plugin in PluginFactory.RunningPlugins.OfType<PluginAssistants>().ToList())
{
if (!PluginAssistantSecurityResolver.Resolve(settingsManager, plugin).RequiresAudit)
continue;
var choice = this.PreviewProvider(new PluginAuditRequest(plugin));
if (!choice.HasProvider)
{
issueOfSkippedPlugins ??= GetRelevantIssue(choice);
continue;
}
var audit = await this.RunAuditAsync(plugin, token: token);
if (audit.Level is PluginAuditLevel.UNKNOWN)
{
await MessageBus.INSTANCE.SendError(new (AppIcons.AI_OPERATION, string.Format(TA("The automatic security audit for the assistant plugin '{0}' failed. Please run it manually on the plugins page."), plugin.Name)));
continue;
}
audits.Add(audit);
}
if (issueOfSkippedPlugins is { } issue)
await MessageBus.INSTANCE.SendError(new (AppIcons.AI_OPERATION, GetAutomaticAuditMessage(issue)));
return audits;
}
/// <summary>
/// Which provider an audit would run with when nobody has a provider at hand, as in the background.
/// </summary>
/// <param name="request">The audit, for the confidence its content requires; null for the least any audit requires.</param>
/// <returns>The choice, which logs nothing.</returns>
public AIOperationProviderChoice PreviewProvider(PluginAuditRequest? request = null)
{
var requiredConfidence = request is null
? ConfidenceLevel.NONE
: auditOperation.GetRequiredConfidence(request);
return providerResolver.Preview(PluginAuditOperation.GetProviderSettings(settingsManager), requiredConfidence, GetProviderOptions(settingsManager, null));
}
/// <summary>
/// What an audit adds to the choice of its provider.
/// </summary>
/// <remarks>
/// Without a provider of its own, an audit falls back on the app-wide default, and then on the provider at
/// hand. 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 -- may read the source of a plugin only when it
/// clears the bar of the audit. Otherwise a provider an organization ruled out for audits would see the very
/// thing it was ruled out for.
/// </remarks>
/// <param name="settingsManager">The settings, for the app-wide default.</param>
/// <param name="providerAtHand">The provider at hand, or null.</param>
/// <returns>The options for the provider resolver.</returns>
internal static AIOperationProviderOptions GetProviderOptions(SettingsManager settingsManager, Settings.Provider? providerAtHand) => new()
{
FallbackProviderIds = [settingsManager.AppDefaultProviderId, providerAtHand?.Id],
OwnMinimumConfidenceAppliesToFallbacks = true,
};
/// <summary>
/// The issue which explains best why no provider can audit: the one of the provider somebody named.
/// </summary>
/// <remarks>
/// The first named fallback is the app-wide default, or the provider at hand when there is no default.
/// When no fallback was named at all, the preferred provider of the audit is what failed.
/// </remarks>
/// <param name="choice">The choice without a provider.</param>
/// <returns>The issue to explain; NOT_SET when nobody named any provider.</returns>
internal static AIOperationProviderIssue GetRelevantIssue(AIOperationProviderChoice choice) => choice.FallbackIssue is AIOperationProviderIssue.NOT_SET
? choice.PreferredIssue
: choice.FallbackIssue;
private static string GetMissingProviderMessage(AIOperationProviderIssue issue) => issue switch
{
AIOperationProviderIssue.NOT_SET or AIOperationProviderIssue.MISSING => TB("No provider is configured for security checks."),
AIOperationProviderIssue.PROHIBITED => TA("Your organization does not allow the provider for security checks. Pick another one, or choose a dedicated provider for security checks in the app settings."),
_ => TA("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."),
};
private static string GetAutomaticAuditMessage(AIOperationProviderIssue issue) => issue switch
{
AIOperationProviderIssue.NOT_SET or AIOperationProviderIssue.MISSING => TA("AI Studio did not audit new or updated assistant plugins automatically, because no model is set for security checks, and there is no app-wide default either. Choose a model for security checks in the settings."),
AIOperationProviderIssue.PROHIBITED => TA("AI Studio did not audit new or updated assistant plugins automatically, because your organization does not allow the model for security checks. Choose another one in the settings."),
_ => TA("AI Studio did not audit new or updated assistant plugins automatically, because the model for security checks is not trusted enough. Choose another one in the settings."),
};
private static string GetMissingProviderSummary(AIOperationProviderIssue issue) => issue switch
{
AIOperationProviderIssue.NOT_SET or AIOperationProviderIssue.MISSING => TB("No audit provider is configured."),
AIOperationProviderIssue.PROHIBITED => TB("The organization does not allow the provider for security checks."),
_ => TB("The provider is not trusted enough for security checks."),
};
}
@@ -1,4 +1,4 @@
using AIStudio.Agents.AssistantAudit;
using AIStudio.AIOperations.PluginAudit;
namespace AIStudio.Tools.PluginSystem.Assistants;
@@ -9,9 +9,9 @@ public sealed class PluginAssistantAudit
public DateTimeOffset AuditedAtUtc { get; set; }
public string AuditProviderId { get; set; } = string.Empty;
public string AuditProviderName { get; set; } = string.Empty;
public AssistantAuditLevel Level { get; set; } = AssistantAuditLevel.UNKNOWN;
public PluginAuditLevel Level { get; set; } = PluginAuditLevel.UNKNOWN;
public string Summary { get; set; } = string.Empty;
public float Confidence { get; set; }
public string PromptPreview { get; set; } = string.Empty;
public List<AssistantAuditFinding> Findings { get; set; } = [];
public List<PluginAuditFinding> Findings { get; set; } = [];
}
@@ -1,4 +1,4 @@
using AIStudio.Agents.AssistantAudit;
using AIStudio.AIOperations.PluginAudit;
using AIStudio.Settings;
namespace AIStudio.Tools.PluginSystem.Assistants;
@@ -111,8 +111,8 @@ public static class PluginAssistantSecurityResolver
CanActivatePlugin = true,
CanStartAssistant = true,
AuditLabel = TB("Safe"),
AuditColor = AssistantAuditLevel.SAFE.Color,
AuditIcon = AssistantAuditLevel.SAFE.Icon,
AuditColor = PluginAuditLevel.SAFE.Color,
AuditIcon = PluginAuditLevel.SAFE.Icon,
AvailabilityLabel = GetAvailabilityLabel(requiresAudit: false, hasAudit: true, hasHashMismatch: false, isBlocked: false, canOverride: false),
AvailabilityColor = GetAvailabilityColor(requiresAudit: false, hasAudit: true, hasHashMismatch: false, isBlocked: false, canOverride: false),
AvailabilityIcon = GetAvailabilityIcon(requiresAudit: false, hasAudit: true, hasHashMismatch: false, isBlocked: false, canOverride: false),
@@ -130,7 +130,7 @@ public static class PluginAssistantSecurityResolver
}
var audit = settingsManager.ConfigurationData.AssistantPluginAudits.FirstOrDefault(x => x.PluginId == plugin.Id);
var hasAudit = audit is not null && audit.Level is not AssistantAuditLevel.UNKNOWN;
var hasAudit = audit is not null && audit.Level is not PluginAuditLevel.UNKNOWN;
var hashMatches = hasAudit && string.Equals(NormalizeHash(audit!.PluginHash), currentHash, StringComparison.Ordinal);
var hasHashMismatch = hasAudit && !hashMatches;
var isBelowMinimum = hashMatches && audit is not null && audit.Level < auditSettings.MinimumLevel;
@@ -159,8 +159,8 @@ public static class PluginAssistantSecurityResolver
CanActivatePlugin = !isBlocked,
CanStartAssistant = !isBlocked,
AuditLabel = TB("Unknown"),
AuditColor = AssistantAuditLevel.UNKNOWN.Color,
AuditIcon = AssistantAuditLevel.UNKNOWN.Icon,
AuditColor = PluginAuditLevel.UNKNOWN.Color,
AuditIcon = PluginAuditLevel.UNKNOWN.Icon,
AvailabilityLabel = GetAvailabilityLabel(requiresAudit, hasAudit, hasHashMismatch, isBlocked, canOverride: false),
AvailabilityColor = GetAvailabilityColor(requiresAudit, hasAudit, hasHashMismatch, isBlocked, canOverride: false),
AvailabilityIcon = GetAvailabilityIcon(requiresAudit, hasAudit, hasHashMismatch, isBlocked, canOverride: false),
@@ -198,8 +198,8 @@ public static class PluginAssistantSecurityResolver
CanActivatePlugin = !isBlocked,
CanStartAssistant = !isBlocked,
AuditLabel = TB("Unknown"),
AuditColor = AssistantAuditLevel.UNKNOWN.Color,
AuditIcon = AssistantAuditLevel.UNKNOWN.Icon,
AuditColor = PluginAuditLevel.UNKNOWN.Color,
AuditIcon = PluginAuditLevel.UNKNOWN.Icon,
AvailabilityLabel = GetAvailabilityLabel(requiresAudit, hasAudit, hasHashMismatch, isBlocked, canOverride: false),
AvailabilityColor = GetAvailabilityColor(requiresAudit, hasAudit, hasHashMismatch, isBlocked, canOverride: false),
AvailabilityIcon = GetAvailabilityIcon(requiresAudit, hasAudit, hasHashMismatch, isBlocked, canOverride: false),
@@ -408,19 +408,27 @@ public sealed class PluginConfiguration(bool isInternal, LuaState state, PluginT
&& maximumPauseSeconds < minimumPauseSeconds)
LOG.LogWarning("The upper bound of the pause between indexing steps configured by plugin {ConfigPluginId} is below its lower bound. The lower bound of {MinimumPauseSeconds} seconds wins.", this.Id, minimumPauseSeconds);
// Config: data source selection agent settings
// Config: text content cleaner settings
ManagedConfiguration.TryProcessConfiguration(x => x.TextContentCleaner, x => x.PreselectAgentOptions, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.TextContentCleaner, x => x.PreselectedAgentProvider, Guid.Empty, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.TextContentCleaner, x => x.MinimumProviderConfidence, this.Id, settingsTable, dryRun);
// Config: data source selection settings
ManagedConfiguration.TryProcessConfiguration(x => x.AgentDataSourceSelection, x => x.PreselectAgentOptions, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.AgentDataSourceSelection, x => x.PreselectedAgentProvider, Guid.Empty, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.AgentDataSourceSelection, x => x.MinimumProviderConfidence, this.Id, settingsTable, dryRun);
// Config: retrieval context validation agent settings
// Config: retrieval context validation settings
ManagedConfiguration.TryProcessConfiguration(x => x.AgentRetrievalContextValidation, x => x.EnableRetrievalContextValidation, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.AgentRetrievalContextValidation, x => x.PreselectAgentOptions, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.AgentRetrievalContextValidation, x => x.PreselectedAgentProvider, Guid.Empty, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.AgentRetrievalContextValidation, x => x.MinimumProviderConfidence, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.AgentRetrievalContextValidation, x => x.NumParallelValidations, this.Id, settingsTable, dryRun);
// Config: assistant plugin audit settings
ManagedConfiguration.TryProcessConfiguration(x => x.AssistantPluginAudit, x => x.RequireAuditBeforeActivation, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.AssistantPluginAudit, x => x.PreselectedAgentProvider, Guid.Empty, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.AssistantPluginAudit, x => x.MinimumProviderConfidence, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.AssistantPluginAudit, x => x.MinimumLevel, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.AssistantPluginAudit, x => x.BlockActivationBelowMinimum, this.Id, settingsTable, dryRun);
ManagedConfiguration.TryProcessConfiguration(x => x.AssistantPluginAudit, x => x.AutomaticallyAuditAssistants, this.Id, settingsTable, dryRun);
@@ -1,6 +1,7 @@
using System.Text;
using AIStudio.Agents;
using AIStudio.AIOperations;
using AIStudio.AIOperations.RetrievalContextValidation;
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Settings;
@@ -54,14 +55,21 @@ public sealed class AugmentationOne : IAugmentationProcess
// Want the user to validate all retrieval contexts?
if (settings.ConfigurationData.AgentRetrievalContextValidation.EnableRetrievalContextValidation && chatThread.DataSourceOptions.AutomaticValidation)
{
// Let's get the validation agent & set up its provider:
var validationAgent = Program.SERVICE_PROVIDER.GetService<AgentRetrievalContextValidation>()!;
if (validationAgent.SetLLMProvider(provider, chatThread.DataSecurity, chatThread.RequiredProviderConfidence))
//
// Which provider validates? Only one which may see what the chat may see: the model reads
// the passages. One choice serves all passages of this answer.
//
var validation = Program.SERVICE_PROVIDER.GetRequiredService<RetrievalContextValidationOperation>();
var providerResolver = Program.SERVICE_PROVIDER.GetRequiredService<AIOperationProviderResolver>();
var validationRequest = new RetrievalContextValidationRequest(chatThread.SystemPrompt, lastUserPrompt, preparedContexts, chatThread.RequiredProviderConfidence);
var validationProviderOptions = ClassicRagProviderOptions.ForDataAccess(settings, provider.ConfiguredProviderId, chatThread.DataSecurity, chatThread.RequiredProviderConfidence);
var validationChoice = providerResolver.Resolve(validation, validationRequest, RetrievalContextValidationOperation.GetProviderSettings(settings), validationProviderOptions);
if (validationChoice.HasProvider)
{
try
{
// Let's validate all retrieval contexts:
var validationResults = await validationAgent.ValidateRetrievalContextsAsync(lastUserPrompt, chatThread, preparedContexts, token);
var validationResults = await validation.RunAsync(validationRequest, new(validationChoice.Provider), token);
if (validationResults.Count == 0)
LOGGER.LogWarning("Retrieval context validation returned no results. Continuing augmentation with all retrieved contexts.");
else
@@ -98,7 +106,7 @@ public sealed class AugmentationOne : IAugmentationProcess
// an event. It does not change between two answers, so a message would repeat itself
// with every single one until the setting changes.
//
LOGGER.LogWarning("Skipping retrieval context validation because no sufficiently trusted validation agent provider is available. Continuing augmentation with all retrieved contexts.");
LOGGER.LogWarning("Skipping retrieval context validation because no provider which is trusted enough is available for it. Continuing augmentation with all retrieved contexts.");
}
}
@@ -0,0 +1,51 @@
using AIStudio.AIOperations;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
namespace AIStudio.Tools.RAG;
/// <summary>
/// What the classic RAG process adds to the choice of a provider for its AI operations.
/// </summary>
/// <remarks>
/// The data source selection and the validation of retrieval contexts run with the same fallbacks, and
/// DataSourceService asks with them in advance which providers would see the data. All three build their
/// options here, so that the providers a check counts are the ones which run.
/// </remarks>
public static class ClassicRagProviderOptions
{
/// <summary>
/// Builds the options for an AI operation of the classic RAG process.
/// </summary>
/// <remarks>
/// Without a provider of its own, an operation falls back on the provider of the chat, and then on the
/// app-wide default. Its minimum confidence applies to both of them.
/// </remarks>
/// <param name="settingsManager">The settings, for the app-wide default.</param>
/// <param name="chatProviderId">The ID of the provider of the chat.</param>
/// <param name="checkProvider">An optional check of the caller, e.g., whether a provider may see the data sources.</param>
/// <returns>The options for the provider resolver.</returns>
public static AIOperationProviderOptions For(SettingsManager settingsManager, string chatProviderId, Func<AIStudio.Settings.Provider, AIOperationProviderIssue>? checkProvider = null) => new()
{
FallbackProviderIds = [chatProviderId, settingsManager.AppDefaultProviderId],
OwnMinimumConfidenceAppliesToFallbacks = true,
CheckProvider = checkProvider,
};
/// <summary>
/// Builds the options for an AI operation of the classic RAG process which reads the data of data sources.
/// </summary>
/// <remarks>
/// Besides the fallbacks, every candidate has to be allowed to see the data, by the security and the
/// confidence it requires. A candidate which is not reports NOT_ALLOWED_FOR_CONTENT.
/// </remarks>
/// <param name="settingsManager">The settings, for the app-wide default.</param>
/// <param name="chatProviderId">The ID of the provider of the chat.</param>
/// <param name="requiredDataSecurity">The data security the data requires.</param>
/// <param name="requiredConfidenceLevel">The provider confidence the data requires.</param>
/// <returns>The options for the provider resolver.</returns>
public static AIOperationProviderOptions ForDataAccess(SettingsManager settingsManager, string chatProviderId, DataSourceSecurity requiredDataSecurity, ConfidenceLevel requiredConfidenceLevel) => For(settingsManager, chatProviderId, candidate => candidate.AllowsDataSourceAccess(settingsManager, requiredDataSecurity, requiredConfidenceLevel)
? AIOperationProviderIssue.NONE
: AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT);
}
@@ -1,4 +1,5 @@
using AIStudio.Agents;
using AIStudio.AIOperations;
using AIStudio.AIOperations.DataSourceChoice;
using AIStudio.Chat;
using AIStudio.Components;
using AIStudio.Provider;
@@ -31,14 +32,38 @@ public class AgenticSrcSelWithDynHeur : IDataSourceSelectionProcess
IReadOnlyList<IDataSource> selectedDataSources = [];
IReadOnlyList<DataSourceAgentSelected> finalAISelection = [];
// Get the agent for the data source selection:
var selectionAgent = Program.SERVICE_PROVIDER.GetService<AgentDataSourceSelection>()!;
var choiceOperation = Program.SERVICE_PROVIDER.GetRequiredService<DataSourceChoiceOperation>();
var providerResolver = Program.SERVICE_PROVIDER.GetRequiredService<AIOperationProviderResolver>();
var settingsManager = Program.SERVICE_PROVIDER.GetRequiredService<SettingsManager>();
var allowedDataSources = dataSources.AllowedDataSources.ToDictionary(ds => ds.Id, StringComparer.Ordinal);
try
{
// Let the AI agent do its work:
var aiSelectedDataSources = await selectionAgent.PerformSelectionAsync(provider, lastUserPrompt, chatThread, dataSources, token);
//
// Which provider chooses? Only one which may see the data sources: the model reads their
// descriptions, and what it chooses decides what is searched.
//
var request = new DataSourceChoiceRequest(chatThread.SystemPrompt, lastUserPrompt, dataSources.AllowedDataSources);
var choice = providerResolver.Resolve(choiceOperation, request, DataSourceChoiceOperation.GetProviderSettings(settingsManager), GetChoiceProviderOptions(settingsManager, provider.ConfiguredProviderId, dataSources.AllowedDataSources));
if (!choice.HasProvider)
{
LOGGER.LogWarning($"No provider may select the data sources, which require data security '{dataSources.AllowedDataSources.GetRequiredSecurityPolicy()}' and provider confidence '{dataSources.AllowedDataSources.GetRequiredConfidenceLevel().Name}'. The RAG process is skipped.");
proceedWithRAG = false;
return new(proceedWithRAG, selectedDataSources);
}
// Let the AI do its work:
var choiceResult = await choiceOperation.RunAsync(request, new(choice.Provider), token);
if (!choiceResult.IsAnswered)
{
LOGGER.LogWarning("The AI gave no usable answer to the selection of data sources. The RAG process is skipped.");
proceedWithRAG = false;
return new(proceedWithRAG, selectedDataSources);
}
var aiSelectedDataSources = choiceResult.SelectedDataSources.ToList();
// Check if the AI selected any data sources:
if (aiSelectedDataSources.Count is 0)
@@ -112,4 +137,17 @@ public class AgenticSrcSelWithDynHeur : IDataSourceSelectionProcess
}
#endregion
/// <summary>
/// What the process adds to the choice of the provider which selects the data sources.
/// </summary>
/// <remarks>
/// Besides the fallbacks of the classic RAG process, the provider has to be allowed to see the data
/// sources, by their security and by the confidence they require.
/// </remarks>
/// <param name="settingsManager">The settings.</param>
/// <param name="chatProviderId">The ID of the provider of the chat.</param>
/// <param name="dataSources">The data sources to choose from.</param>
/// <returns>The options for the provider resolver.</returns>
internal static AIOperationProviderOptions GetChoiceProviderOptions(SettingsManager settingsManager, string chatProviderId, IReadOnlyList<IDataSource> dataSources) => ClassicRagProviderOptions.ForDataAccess(settingsManager, chatProviderId, dataSources.GetRequiredSecurityPolicy(), dataSources.GetRequiredConfidenceLevel());
}
@@ -23,7 +23,7 @@ public interface IDataSourceSelectionProcess
/// <summary>
/// Starts the data source selection process.
/// </summary>
/// <param name="provider">The LLM provider. Used as default for data selection agents.</param>
/// <param name="provider">The LLM provider. Used as the fallback of the AI operation which selects data sources.</param>
/// <param name="lastUserPrompt">The last prompt that was issued by the user.</param>
/// <param name="chatThread">The chat thread.</param>
/// <param name="dataSources">The allowed data sources yielded by the data source service.</param>
@@ -293,12 +293,12 @@ public sealed class AISrcSelWithRetCtxVal : IRagProcess
/// Semantic Search asks the same place, DataSourceRequirements, so that both ways of searching
/// demand the same of the same data sources. Only the data sources whose passages reached the
/// AI count: one which found nothing leaves the chat as it was, and so does one whose passages
/// the validation agent dropped, or which did not fit into what the model can read, see
/// the validation dropped, or which did not fit into what the model can read, see
/// PassageBudget. Neither the model nor any of its tools ever saw those passages; the
/// validation agent did, but it has no tools. Otherwise, a data source of public papers could
/// validation did, but it has no tools. Otherwise, a data source of public papers could
/// fill the budget while the passages of a confidential one stayed out, and the chat would
/// still lose the web search for good. The data security and the provider confidence were
/// raised before the retrieval already, for every selected data source, because the agents see
/// raised before the retrieval already, for every selected data source, because the AI operations see
/// the passages as well; the data sources with passages are among them, so asking again would
/// change nothing.<br/><br/>
/// The answer which follows does not offer the web search any more: the request reads the
@@ -11,7 +11,7 @@ namespace AIStudio.Tools.Services;
/// Tells a model what a data source holds, so that it can decide where to search.
/// </summary>
/// <remarks>
/// Both the agent which selects data sources and Semantic Search describe the data sources to a
/// Both the AI operation which selects data sources and Semantic Search describe the data sources to a
/// model. The user describes a local data source. An ERI data source is described by its server,
/// which costs two requests and is written by somebody else: that description is filtered for
/// prompt injections like any other external content before it is kept. It is kept for a few
@@ -1201,7 +1201,7 @@ public sealed partial class DataSourceEmbeddingService(SettingsManager settingsM
/// </summary>
/// <remarks>
/// The one place which knows where data sources are kept: in DataSources those which classic
/// RAG and the agents see as well, in Mailboxes those which only the mail tools read. Whatever
/// RAG and its AI operations see as well, in Mailboxes those which only the mail tools read. Whatever
/// works through all of them, or looks one up by its id, goes through here.
/// </remarks>
/// <returns>The data sources, those from DataSources first.</returns>
@@ -1,9 +1,13 @@
using AIStudio.AIOperations;
using AIStudio.AIOperations.DataSourceChoice;
using AIStudio.AIOperations.RetrievalContextValidation;
using AIStudio.Assistants.ERI;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
using AIStudio.Tools.ERIClient;
using AIStudio.Tools.ERIClient.DataModel;
using AIStudio.Tools.RAG;
namespace AIStudio.Tools.Services;
@@ -11,7 +15,7 @@ public sealed class DataSourceService
{
//
// Trust is recorded for every participating provider, while only the chat provider's trust
// decides about external data sources below. The agent which validates retrieval contexts
// decides about external data sources below. The AI operation which validates retrieval contexts
// checks its own provider before it runs, so nothing slips through today. Keeping the value
// named here is what makes that asymmetry visible.
//
@@ -22,11 +26,13 @@ public sealed class DataSourceService
private readonly DataSourceEmbeddingService embeddingService;
private readonly RustService rustService;
private readonly SettingsManager settingsManager;
private readonly AIOperationProviderResolver providerResolver;
private readonly ILogger<DataSourceService> logger;
public DataSourceService(SettingsManager settingsManager, ILogger<DataSourceService> logger, RustService rustService, DataSourceEmbeddingService embeddingService)
public DataSourceService(SettingsManager settingsManager, AIOperationProviderResolver providerResolver, ILogger<DataSourceService> logger, RustService rustService, DataSourceEmbeddingService embeddingService)
{
this.logger = logger;
this.providerResolver = providerResolver;
this.rustService = rustService;
this.settingsManager = settingsManager;
this.embeddingService = embeddingService;
@@ -40,8 +46,8 @@ public sealed class DataSourceService
/// It also returns the data sources selected before when they are still allowed.
/// </summary>
/// <param name="selectedLLMProvider">The selected LLM provider.</param>
/// <param name="dataSourceOptions">The active data source options, which determine which agent providers participate.</param>
/// <param name="retrievalMode">How the data sources are searched in effect, which decides whether any agent participates at all.</param>
/// <param name="dataSourceOptions">The active data source options, which determine which AI operations participate.</param>
/// <param name="retrievalMode">How the data sources are searched in effect, which decides whether any AI operation participates at all.</param>
/// <param name="previousSelectedDataSources">The data sources selected before.</param>
/// <returns>The allowed data sources and the data sources selected before -- when they are still allowed.</returns>
public async Task<AllowedSelectedDataSources> GetDataSources(AIStudio.Settings.Provider selectedLLMProvider, DataSourceOptions dataSourceOptions, DataSourceRetrievalMode retrievalMode, IReadOnlyCollection<IDataSource>? previousSelectedDataSources = null)
@@ -69,8 +75,8 @@ public sealed class DataSourceService
/// this method checks only the supplied data sources.
/// </summary>
/// <param name="selectedLLMProvider">The selected LLM provider.</param>
/// <param name="dataSourceOptions">The active data source options, which determine which agent providers participate.</param>
/// <param name="retrievalMode">How the data sources are searched in effect, which decides whether any agent participates at all.</param>
/// <param name="dataSourceOptions">The active data source options, which determine which AI operations participate.</param>
/// <param name="retrievalMode">How the data sources are searched in effect, which decides whether any AI operation participates at all.</param>
/// <param name="requestedDataSources">The data sources to check.</param>
/// <returns>The requested data sources that are allowed for the provider.</returns>
public async Task<IReadOnlyList<IDataSource>> GetAllowedDataSources(AIStudio.Settings.Provider selectedLLMProvider, DataSourceOptions dataSourceOptions, DataSourceRetrievalMode retrievalMode, IReadOnlyCollection<IDataSource> requestedDataSources)
@@ -101,8 +107,8 @@ public sealed class DataSourceService
/// It also returns the data sources selected before when they are still allowed.
/// </summary>
/// <param name="selectedLLMProvider">The selected LLM provider.</param>
/// <param name="dataSourceOptions">The active data source options, which determine which agent providers participate.</param>
/// <param name="retrievalMode">How the data sources are searched in effect, which decides whether any agent participates at all.</param>
/// <param name="dataSourceOptions">The active data source options, which determine which AI operations participate.</param>
/// <param name="retrievalMode">How the data sources are searched in effect, which decides whether any AI operation participates at all.</param>
/// <param name="previousSelectedDataSources">The data sources selected before.</param>
/// <returns>The allowed data sources and the data sources selected before -- when they are still allowed.</returns>
public async Task<AllowedSelectedDataSources> GetDataSources(IProvider selectedLLMProvider, DataSourceOptions dataSourceOptions, DataSourceRetrievalMode retrievalMode, IReadOnlyCollection<IDataSource>? previousSelectedDataSources = null)
@@ -128,46 +134,62 @@ public sealed class DataSourceService
{
var providers = new List<ParticipatingProvider> { currentProvider };
var retrievalContextValidationEnabled = this.settingsManager.ConfigurationData.AgentRetrievalContextValidation.EnableRetrievalContextValidation;
foreach (var (component, role) in GetParticipatingAgents(dataSourceOptions, retrievalMode, retrievalContextValidationEnabled))
this.AddAgentProvider(providers, component, currentProviderId, role);
foreach (var (component, role) in GetParticipatingOperations(dataSourceOptions, retrievalMode, retrievalContextValidationEnabled))
this.AddOperationProvider(providers, component, currentProviderId, role);
return providers;
}
/// <summary>
/// Which agents get to see the data of the data sources, besides the chat provider.
/// Which AI operations get to see the data of the data sources, besides the chat provider.
/// </summary>
/// <remarks>
/// Only the classic RAG process runs agents. With Semantic Search, the chat model picks the
/// Only the classic RAG process runs AI operations. With Semantic Search, the chat model picks the
/// data sources and judges what it found itself, so the data reaches no other provider.
/// Counting the providers of the agents there would hold back data sources which the chat
/// Counting the providers of the AI operations there would hold back data sources which the chat
/// provider alone may use.
/// </remarks>
/// <param name="dataSourceOptions">The active data source options.</param>
/// <param name="retrievalMode">How the data sources are searched in effect.</param>
/// <param name="retrievalContextValidationEnabled">Whether the validation of retrieval contexts is enabled in the settings.</param>
/// <returns>The component of each participating agent, together with its role for the log.</returns>
internal static IReadOnlyList<(Components Component, string Role)> GetParticipatingAgents(DataSourceOptions dataSourceOptions, DataSourceRetrievalMode retrievalMode, bool retrievalContextValidationEnabled)
/// <returns>The component of each participating AI operation, together with its role for the log.</returns>
internal static IReadOnlyList<(Components Component, string Role)> GetParticipatingOperations(DataSourceOptions dataSourceOptions, DataSourceRetrievalMode retrievalMode, bool retrievalContextValidationEnabled)
{
if (retrievalMode is DataSourceRetrievalMode.SEMANTIC_SEARCH)
return [];
var agents = new List<(Components Component, string Role)>(2);
var operations = new List<(Components Component, string Role)>(2);
if (dataSourceOptions.AutomaticDataSourceSelection)
agents.Add((Components.AGENT_DATA_SOURCE_SELECTION, "data source selection agent"));
operations.Add((Components.AGENT_DATA_SOURCE_SELECTION, "data source selection"));
if (dataSourceOptions.AutomaticValidation && retrievalContextValidationEnabled)
agents.Add((Components.AGENT_RETRIEVAL_CONTEXT_VALIDATION, "retrieval context validation agent"));
operations.Add((Components.AGENT_RETRIEVAL_CONTEXT_VALIDATION, "retrieval context validation"));
return agents;
return operations;
}
private void AddAgentProvider(List<ParticipatingProvider> providers, Components component, string currentProviderId, string role)
/// <summary>
/// Adds the provider which an AI operation would run with, chosen as the operation chooses it when it runs.
/// </summary>
/// <remarks>
/// The data sources are what this check decides, so the choice leaves out the check of the data
/// sources, which the operation adds when it runs. Should that check refuse the provider counted here,
/// the operation falls back on the provider of the chat, which this check counts as well.
/// </remarks>
private void AddOperationProvider(List<ParticipatingProvider> providers, Components component, string currentProviderId, string role)
{
var provider = this.settingsManager.GetPreselectedProvider(component, currentProviderId, true);
var operationSettings = component switch
{
Components.AGENT_DATA_SOURCE_SELECTION => DataSourceChoiceOperation.GetProviderSettings(this.settingsManager),
Components.AGENT_RETRIEVAL_CONTEXT_VALIDATION => RetrievalContextValidationOperation.GetProviderSettings(this.settingsManager),
_ => AIOperationProviderSettings.NONE,
};
var provider = this.providerResolver.Preview(operationSettings, ConfidenceLevel.NONE, ClassicRagProviderOptions.For(this.settingsManager, currentProviderId)).Provider;
if (provider == Settings.Provider.NONE)
{
this.logger.LogWarning($"No provider is available for the {role}. Data sources cannot be made available while this agent is enabled.");
this.logger.LogWarning($"No provider is available for the {role}. Data sources cannot be made available while this AI operation is enabled.");
providers.Add(new(role, false, ConfidenceLevel.NONE));
return;
}
@@ -308,7 +308,7 @@ public sealed class DirectChatService(SettingsManager settingsManager, DataSourc
//
// There is nothing to check when data sources are switched off, and nothing to check either
// when an agent picks them: that choice is made per message in the chat, exactly as it is
// when an AI operation picks them: that choice is made per message in the chat, exactly as it is
// for a chat template the user picks by hand.
//
if (chosenOptions.DisableDataSources || chosenOptions.AutomaticDataSourceSelection || chosenOptions.PreselectedDataSourceIds.Count == 0)
@@ -351,8 +351,8 @@ public sealed class DirectChatService(SettingsManager settingsManager, DataSourc
{
//
// The options the launched chat will run under are what this check runs against: they
// decide which agent providers take part, and an agent with too little confidence makes
// a data source unavailable. Agents take part only when the chat searches with every
// decide which providers of AI operations take part, and an AI operation with too little confidence makes
// a data source unavailable. AI operations take part only when the chat searches with every
// message, which the chat decides the same way:
//
var retrievalMode = await toolRegistry.GetEffectiveRetrievalModeAsync(chosenOptions, provider, Components.CHAT);
@@ -207,9 +207,9 @@ public sealed class SemanticSearchTool(SettingsManager settingsManager, DataSour
/// </summary>
/// <remarks>
/// When the AI selects the data sources, it may search every data source the provider may use:
/// the AI which selects is the chat model itself, no agent. Otherwise, it may search those the
/// the AI which selects is the chat model itself, no AI operation. Otherwise, it may search those the
/// user selected, as far as the provider may use them. Only the chat provider counts, since no
/// agent takes part, see DataSourceService.GetParticipatingAgents.<br/><br/>
/// AI operation takes part, see DataSourceService.GetParticipatingOperations.<br/><br/>
/// Preparing a request knows the provider by its settings, running a call by the provider
/// itself. Both ask the same question, so both come here. The classic RAG process asks here as
/// well while it steps back for this tool, so that it names the unreachable data sources in the
@@ -864,7 +864,7 @@ public sealed class ToolRegistry
/// <remarks>
/// The one place which decides between the two. The RAG process, the data source selection,
/// and the check of what a launched chat may search all ask here, so that none of them counts
/// the agents of the RAG process in or out while another does the opposite. The chat searches
/// the AI operations of the RAG process in or out while another does the opposite. The chat searches
/// itself when the user prefers it and GetOfferBlockReasonAsync has nothing against it. Its
/// answer comes along whatever the user prefers, so that the user interface can leave out a
/// choice which is none and say why the chat searches with every message.<br/><br/>