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

@@ -0,0 +1,191 @@
using AIStudio.AIOperations;
using AIStudio.Provider;
namespace AIStudio.Tests.AIOperations;
/// <summary>
/// Checks how the provider of an AI operation is chosen from the facts about its candidates.
/// </summary>
/// <remarks>
/// Each row names the candidates, the rules, and what has to come out: the chosen provider, why the preferred
/// one was not chosen, and why the first named fallback failed. The rows cover every issue and their order,
/// the order of the fallbacks, the minimum of the operation for fallbacks switched on and off, and the rules
/// which apply to every candidate. Names are written out in full where a short one would find a namespace
/// of this assembly first, see AIOperationProviderResolverTests.
/// </remarks>
[TestFixture]
public sealed class AIOperationProviderChoiceTests
{
private const string PREFERRED = "preferred";
private const string FIRST = "first";
private const string SECOND = "second";
[TestCaseSource(nameof(Cases))]
public void ChoosesTheExpectedProvider(Func<AIOperationProviderCandidate> preferred, Func<AIOperationProviderCandidate>[] fallbacks, AIOperationProviderRules rules, string? expectedProviderId, AIOperationProviderIssue expectedPreferredIssue, AIOperationProviderIssue expectedFallbackIssue)
{
var choice = AIOperationProviderChoice.Choose(preferred(), fallbacks.Select(fallback => fallback()).ToList(), rules);
Assert.Multiple(() =>
{
if (expectedProviderId is null)
Assert.That(choice.HasProvider, Is.False, "No candidate passes, so no provider may be chosen.");
else
Assert.That(choice.Provider.Id, Is.EqualTo(expectedProviderId));
Assert.That(choice.PreferredIssue, Is.EqualTo(expectedPreferredIssue));
Assert.That(choice.FallbackIssue, Is.EqualTo(expectedFallbackIssue));
});
}
[Test]
public void ReportsWhetherAFallbackWasChosen()
{
var rules = Rules();
var preferredChoice = AIOperationProviderChoice.Choose(Candidate(PREFERRED)(), [Candidate(FIRST)()], rules);
var fallbackChoice = AIOperationProviderChoice.Choose(AIOperationProviderCandidate.NOT_NAMED, [Candidate(FIRST)()], rules);
var noChoice = AIOperationProviderChoice.Choose(AIOperationProviderCandidate.NOT_NAMED, [], rules);
Assert.Multiple(() =>
{
Assert.That(preferredChoice.UsesFallback, Is.False);
Assert.That(fallbackChoice.UsesFallback, Is.True);
Assert.That(noChoice.UsesFallback, Is.False, "Without a provider, nothing was chosen, not even a fallback.");
});
}
private static IEnumerable<TestCaseData> Cases()
{
//
// The preferred provider and each issue in turn:
//
yield return Row("PreferredWinsWhenItPasses",
Candidate(PREFERRED), [Candidate(FIRST)], Rules(),
PREFERRED, AIOperationProviderIssue.NONE, AIOperationProviderIssue.NONE);
yield return Row("PreferredNotSetFallsBackWithoutAHint",
NotNamed, [Candidate(FIRST)], Rules(),
FIRST, AIOperationProviderIssue.NOT_SET, AIOperationProviderIssue.NONE);
yield return Row("PreferredMissingFallsBack",
Missing, [Candidate(FIRST)], Rules(),
FIRST, AIOperationProviderIssue.MISSING, AIOperationProviderIssue.NONE);
yield return Row("PreferredProhibitedFallsBack",
Candidate(PREFERRED, isProhibited: true), [Candidate(FIRST)], Rules(),
FIRST, AIOperationProviderIssue.PROHIBITED, AIOperationProviderIssue.NONE);
yield return Row("PreferredBelowTheGlobalMinimumFallsBack",
Candidate(PREFERRED, ConfidenceLevel.LOW), [Candidate(FIRST)], Rules(global: ConfidenceLevel.MEDIUM),
FIRST, AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE, AIOperationProviderIssue.NONE);
yield return Row("PreferredBelowTheOwnMinimumFallsBack",
Candidate(PREFERRED, ConfidenceLevel.LOW), [Candidate(FIRST)], Rules(own: ConfidenceLevel.MEDIUM),
FIRST, AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE, AIOperationProviderIssue.NONE);
yield return Row("PreferredBelowWhatTheContentRequiresFallsBack",
Candidate(PREFERRED, ConfidenceLevel.LOW), [Candidate(FIRST)], Rules(required: ConfidenceLevel.MEDIUM),
FIRST, AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT, AIOperationProviderIssue.NONE);
yield return Row("PreferredRefusedForItsContentByTheCallerFallsBack",
Candidate(PREFERRED, callerIssue: AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT), [Candidate(FIRST)], Rules(),
FIRST, AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT, AIOperationProviderIssue.NONE);
yield return Row("PreferredWithTooSmallAWindowFallsBack",
Candidate(PREFERRED, callerIssue: AIOperationProviderIssue.CONTEXT_WINDOW_TOO_SMALL), [Candidate(FIRST)], Rules(),
FIRST, AIOperationProviderIssue.CONTEXT_WINDOW_TOO_SMALL, AIOperationProviderIssue.NONE);
yield return Row("ReachingTheMinimumExactlyIsEnough",
Candidate(PREFERRED, ConfidenceLevel.MEDIUM), [], Rules(ConfidenceLevel.MEDIUM, ConfidenceLevel.MEDIUM, ConfidenceLevel.MEDIUM),
PREFERRED, AIOperationProviderIssue.NONE, AIOperationProviderIssue.NONE);
//
// The order of the issues: a candidate reports the first rule it breaks.
//
yield return Row("AProhibitionComesBeforeTheConfidence",
Candidate(PREFERRED, ConfidenceLevel.LOW, isProhibited: true), [], Rules(global: ConfidenceLevel.HIGH),
null, AIOperationProviderIssue.PROHIBITED, AIOperationProviderIssue.NOT_SET);
yield return Row("TheMinimumComesBeforeWhatTheContentRequires",
Candidate(PREFERRED, ConfidenceLevel.LOW), [], Rules(own: ConfidenceLevel.MEDIUM, required: ConfidenceLevel.HIGH),
null, AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE, AIOperationProviderIssue.NOT_SET);
yield return Row("WhatTheContentRequiresComesBeforeTheCheckOfTheCaller",
Candidate(PREFERRED, ConfidenceLevel.LOW, callerIssue: AIOperationProviderIssue.CONTEXT_WINDOW_TOO_SMALL), [], Rules(required: ConfidenceLevel.MEDIUM),
null, AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT, AIOperationProviderIssue.NOT_SET);
//
// The order of the fallbacks:
//
yield return Row("TheFirstPassingFallbackWins",
NotNamed, [Candidate(FIRST, isProhibited: true), Candidate(SECOND), Candidate("third")], Rules(),
SECOND, AIOperationProviderIssue.NOT_SET, AIOperationProviderIssue.NONE);
yield return Row("AFallbackNobodyNamedIsSkipped",
NotNamed, [NotNamed, Candidate(SECOND)], Rules(),
SECOND, AIOperationProviderIssue.NOT_SET, AIOperationProviderIssue.NONE);
//
// The minimum of the operation for fallbacks:
//
yield return Row("TheOwnMinimumAppliesToFallbacksWhenSwitchedOn",
NotNamed, [Candidate(FIRST, ConfidenceLevel.LOW)], Rules(own: ConfidenceLevel.MEDIUM),
null, AIOperationProviderIssue.NOT_SET, AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE);
yield return Row("TheOwnMinimumSparesFallbacksWhenSwitchedOff",
NotNamed, [Candidate(FIRST, ConfidenceLevel.LOW)], Rules(own: ConfidenceLevel.MEDIUM, ownForFallbacks: false),
FIRST, AIOperationProviderIssue.NOT_SET, AIOperationProviderIssue.NONE);
yield return Row("TheOwnMinimumStillAppliesToThePreferredWhenSwitchedOffForFallbacks",
Candidate(PREFERRED, ConfidenceLevel.LOW), [Candidate(FIRST, ConfidenceLevel.LOW)], Rules(own: ConfidenceLevel.MEDIUM, ownForFallbacks: false),
FIRST, AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE, AIOperationProviderIssue.NONE);
//
// What applies to every candidate, even with the minimum of the operation switched off for fallbacks:
//
yield return Row("TheGlobalMinimumAppliesToFallbacks",
NotNamed, [Candidate(FIRST, ConfidenceLevel.LOW)], Rules(global: ConfidenceLevel.MEDIUM, ownForFallbacks: false),
null, AIOperationProviderIssue.NOT_SET, AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE);
yield return Row("AProhibitionAppliesToFallbacks",
NotNamed, [Candidate(FIRST, isProhibited: true)], Rules(ownForFallbacks: false),
null, AIOperationProviderIssue.NOT_SET, AIOperationProviderIssue.PROHIBITED);
yield return Row("WhatTheContentRequiresAppliesToFallbacks",
NotNamed, [Candidate(FIRST, ConfidenceLevel.LOW)], Rules(required: ConfidenceLevel.MEDIUM, ownForFallbacks: false),
null, AIOperationProviderIssue.NOT_SET, AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT);
yield return Row("TheCheckOfTheCallerAppliesToFallbacks",
NotNamed, [Candidate(FIRST, callerIssue: AIOperationProviderIssue.CONTEXT_WINDOW_TOO_SMALL)], Rules(ownForFallbacks: false),
null, AIOperationProviderIssue.NOT_SET, AIOperationProviderIssue.CONTEXT_WINDOW_TOO_SMALL);
//
// What is reported when nothing passes:
//
yield return Row("NothingNamedNeedsNoHint",
NotNamed, [], Rules(),
null, AIOperationProviderIssue.NOT_SET, AIOperationProviderIssue.NOT_SET);
yield return Row("TheFallbackIssueIsTheOneOfTheFirstNamedFallback",
Candidate(PREFERRED, isProhibited: true), [NotNamed, Missing, Candidate(SECOND, isProhibited: true)], Rules(),
null, AIOperationProviderIssue.PROHIBITED, AIOperationProviderIssue.MISSING);
yield return Row("FallbacksNobodyNamedLeaveTheFallbackIssueNotSet",
Candidate(PREFERRED, isProhibited: true), [NotNamed, NotNamed], Rules(),
null, AIOperationProviderIssue.PROHIBITED, AIOperationProviderIssue.NOT_SET);
}
private static TestCaseData Row(string name, Func<AIOperationProviderCandidate> preferred, Func<AIOperationProviderCandidate>[] fallbacks, AIOperationProviderRules rules, string? expectedProviderId, AIOperationProviderIssue expectedPreferredIssue, AIOperationProviderIssue expectedFallbackIssue) => new TestCaseData(preferred, fallbacks, rules, expectedProviderId, expectedPreferredIssue, expectedFallbackIssue).SetName(name);
private static AIOperationProviderRules Rules(ConfidenceLevel global = ConfidenceLevel.NONE, ConfidenceLevel own = ConfidenceLevel.NONE, ConfidenceLevel required = ConfidenceLevel.NONE, bool ownForFallbacks = true) => new(global, own, required, ownForFallbacks);
//
// The rows hand over factories instead of candidates: NUnit gathers the rows before TestHost sets up the
// logger factory, and a provider built that early breaks the type initializer of Settings.Provider for
// every test of the run.
//
private static Func<AIOperationProviderCandidate> NotNamed => () => AIOperationProviderCandidate.NOT_NAMED;
private static Func<AIOperationProviderCandidate> Missing => () => AIOperationProviderCandidate.MISSING;
private static Func<AIOperationProviderCandidate> Candidate(string id, ConfidenceLevel confidence = ConfidenceLevel.HIGH, bool isProhibited = false, AIOperationProviderIssue callerIssue = AIOperationProviderIssue.NONE) => () => new(new AIStudio.Settings.Provider(1, id, id, LLMProviders.SELF_HOSTED, new("test-model", null)), true, true, isProhibited, confidence, callerIssue);
}
@@ -0,0 +1,173 @@
using AIStudio.AIOperations;
using AIStudio.Provider;
using AIStudio.Settings;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.AIOperations;
/// <summary>
/// Checks that the resolver gathers the facts about the candidates from the settings.
/// </summary>
/// <remarks>
/// AIOperationProviderChoiceTests covers the decision itself. Here, it is about what the resolver reads:
/// a deleted provider, a prohibition of the organization, the global minimum, the check of the caller, and
/// the app-wide default with its shortcut for a single provider.<br/><br/>
/// Names are written out in full where a short one would find a namespace of this assembly first. This
/// assembly has an AIStudio.Tests.Tools and an AIStudio.Tests.Provider of its own, and the app has an
/// AIStudio.Components -- all three are what a short name finds from here, and a using alias does not help,
/// because names from the enclosing namespaces win over it.
/// </remarks>
[TestFixture]
public sealed class AIOperationProviderResolverTests
{
private const string OWN_PROVIDER_ID = "11111111-1111-1111-1111-111111111111";
private const string FALLBACK_PROVIDER_ID = "22222222-2222-2222-2222-222222222222";
private const string APP_DEFAULT_PROVIDER_ID = "33333333-3333-3333-3333-333333333333";
private const string DELETED_PROVIDER_ID = "44444444-4444-4444-4444-444444444444";
[Test]
public void APickedProviderWhichWasDeletedIsMissing()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, FALLBACK_PROVIDER_ID, LLMProviders.SELF_HOSTED);
AddProvider(settingsManager, APP_DEFAULT_PROVIDER_ID, LLMProviders.SELF_HOSTED);
var choice = CreateResolver(settingsManager).Preview(new(DELETED_PROVIDER_ID, ConfidenceLevel.NONE), ConfidenceLevel.NONE, new() { FallbackProviderIds = [FALLBACK_PROVIDER_ID] });
Assert.Multiple(() =>
{
Assert.That(choice.Provider.Id, Is.EqualTo(FALLBACK_PROVIDER_ID));
Assert.That(choice.PreferredIssue, Is.EqualTo(AIOperationProviderIssue.MISSING), "A provider which was picked and deleted since is worth a hint, unlike one nobody picked.");
});
}
[Test]
public void AProviderOfNoneCountsAsNotPicked()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, FALLBACK_PROVIDER_ID, LLMProviders.SELF_HOSTED);
AddProvider(settingsManager, APP_DEFAULT_PROVIDER_ID, LLMProviders.SELF_HOSTED);
var choice = CreateResolver(settingsManager).Preview(new(AIStudio.Settings.Provider.NONE.Id, ConfidenceLevel.NONE), ConfidenceLevel.NONE, new() { FallbackProviderIds = [FALLBACK_PROVIDER_ID] });
Assert.That(choice.PreferredIssue, Is.EqualTo(AIOperationProviderIssue.NOT_SET), "Some settings store the ID of Provider.NONE for an empty choice.");
}
[Test]
public void AProhibitionOfTheOrganizationIsRead()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, OWN_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, FALLBACK_PROVIDER_ID, LLMProviders.SELF_HOSTED);
settingsManager.ConfigurationData.App.ProhibitedProviders.Add(LLMProviders.OPEN_AI);
var choice = CreateResolver(settingsManager).Preview(new(OWN_PROVIDER_ID, ConfidenceLevel.NONE), ConfidenceLevel.NONE, new() { FallbackProviderIds = [FALLBACK_PROVIDER_ID] });
Assert.Multiple(() =>
{
Assert.That(choice.Provider.Id, Is.EqualTo(FALLBACK_PROVIDER_ID));
Assert.That(choice.PreferredIssue, Is.EqualTo(AIOperationProviderIssue.PROHIBITED));
});
}
[Test]
public void TheGlobalMinimumIsRead()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, OWN_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, FALLBACK_PROVIDER_ID, LLMProviders.OPEN_AI);
settingsManager.ConfigurationData.Confidence.EnforceGlobalMinimumConfidence = true;
settingsManager.ConfigurationData.Confidence.GlobalMinimumConfidence = ConfidenceLevel.HIGH;
var choice = CreateResolver(settingsManager).Preview(new(OWN_PROVIDER_ID, ConfidenceLevel.NONE), ConfidenceLevel.NONE, new() { FallbackProviderIds = [FALLBACK_PROVIDER_ID], OwnMinimumConfidenceAppliesToFallbacks = false });
Assert.Multiple(() =>
{
Assert.That(choice.HasProvider, Is.False, "What the organization enforces leaves no fallback out, even one exempt from the minimum of the operation.");
Assert.That(choice.PreferredIssue, Is.EqualTo(AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE));
Assert.That(choice.FallbackIssue, Is.EqualTo(AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE));
});
}
[Test]
public void TheCheckOfTheCallerSeesEveryConfiguredCandidate()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, OWN_PROVIDER_ID, LLMProviders.SELF_HOSTED);
AddProvider(settingsManager, FALLBACK_PROVIDER_ID, LLMProviders.SELF_HOSTED);
var checkedIds = new List<string>();
var choice = CreateResolver(settingsManager).Preview(new(OWN_PROVIDER_ID, ConfidenceLevel.NONE), ConfidenceLevel.NONE, new()
{
FallbackProviderIds = [DELETED_PROVIDER_ID, FALLBACK_PROVIDER_ID],
CheckProvider = provider =>
{
checkedIds.Add(provider.Id);
return provider.Id == OWN_PROVIDER_ID ? AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT : AIOperationProviderIssue.NONE;
},
});
Assert.Multiple(() =>
{
Assert.That(choice.Provider.Id, Is.EqualTo(FALLBACK_PROVIDER_ID));
Assert.That(choice.PreferredIssue, Is.EqualTo(AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT));
Assert.That(checkedIds, Is.EqualTo(new[] { OWN_PROVIDER_ID, FALLBACK_PROVIDER_ID }), "The check gets the configured providers only, never a missing one.");
});
}
[Test]
public void TheAppDefaultIsTheOneTheSettingsName()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, FALLBACK_PROVIDER_ID, LLMProviders.SELF_HOSTED);
AddProvider(settingsManager, APP_DEFAULT_PROVIDER_ID, LLMProviders.SELF_HOSTED);
settingsManager.ConfigurationData.App.PreselectedProvider = APP_DEFAULT_PROVIDER_ID;
var choice = CreateResolver(settingsManager).Preview(AIOperationProviderSettings.NONE, ConfidenceLevel.NONE, new() { FallbackProviderIds = [null, settingsManager.AppDefaultProviderId] });
Assert.That(choice.Provider.Id, Is.EqualTo(APP_DEFAULT_PROVIDER_ID));
}
[Test]
public void TheOnlyProviderIsTheAppDefault()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, FALLBACK_PROVIDER_ID, LLMProviders.SELF_HOSTED);
settingsManager.ConfigurationData.App.PreselectedProvider = DELETED_PROVIDER_ID;
Assert.That(settingsManager.AppDefaultProviderId, Is.EqualTo(FALLBACK_PROVIDER_ID), "With a single provider, there is nothing else to choose, as in GetPreselectedProvider.");
}
[Test]
public void WithoutADefaultThereIsNoAppDefault()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, FALLBACK_PROVIDER_ID, LLMProviders.SELF_HOSTED);
AddProvider(settingsManager, APP_DEFAULT_PROVIDER_ID, LLMProviders.SELF_HOSTED);
var choice = CreateResolver(settingsManager).Preview(AIOperationProviderSettings.NONE, ConfidenceLevel.NONE, new() { FallbackProviderIds = [settingsManager.AppDefaultProviderId] });
Assert.Multiple(() =>
{
Assert.That(choice.HasProvider, Is.False, "Two configured providers are not a choice.");
Assert.That(choice.FallbackIssue, Is.EqualTo(AIOperationProviderIssue.NOT_SET));
});
}
/// <summary>
/// Builds a settings manager the way these tests need it.
/// </summary>
/// <remarks>
/// The rust service is handed in as null on purpose: choosing a provider never asks it.
/// </remarks>
private static SettingsManager CreateSettingsManager() => new(NullLogger<SettingsManager>.Instance, null!);
private static AIOperationProviderResolver CreateResolver(SettingsManager settingsManager) => new(settingsManager, NullLogger<AIOperationProviderResolver>.Instance);
private static void AddProvider(SettingsManager settingsManager, string id, LLMProviders llmProvider)
{
var providers = settingsManager.ConfigurationData.Providers;
providers.Add(new((uint)providers.Count + 1, id, $"Instance {providers.Count + 1}", llmProvider, new("test-model", null)));
}
}
@@ -0,0 +1,128 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using AIStudio.AIOperations;
namespace AIStudio.Tests.AIOperations;
/// <summary>
/// Checks that every AI operation can serve several callers at once.
/// </summary>
/// <remarks>
/// The operations are singletons, so two chats with RAG run the same instance at the same time. Anything an
/// operation stored between calls, such as its provider or its answers, would leak from one call into the
/// other. Only the parameters of a primary constructor may be kept, which hold the services it depends on.
/// </remarks>
[TestFixture]
public sealed class AIOperationsAreStatelessTests
{
[Test]
public void TheOperationsAreFound()
{
Assert.That(FindOperationTypes().Select(type => type.Name), Is.SupersetOf(new[] { "TextContentCleaningOperation", "DataSourceChoiceOperation", "RetrievalContextValidationOperation", "PluginAuditOperation" }), "Without the operations, every other test here would pass while checking nothing.");
}
[Test]
public void NoOperationHasWritableState()
{
foreach (var operationType in FindOperationTypes())
Assert.That(FindWritableState(operationType), Is.Empty, $"The AI operation '{operationType.Name}' keeps state between calls; keep everything of a call in local variables.");
}
[Test]
public void EveryOperationIsASingleton()
{
var programSource = ReadProgramSource();
foreach (var operationType in FindOperationTypes())
Assert.That(programSource, Does.Contain($"builder.Services.AddSingleton<{operationType.Name}>();"), $"The AI operation '{operationType.Name}' has to be registered as a singleton in Program.cs.");
}
[Test]
public void EveryOperationReadsItsProviderSettings()
{
foreach (var operationType in FindOperationTypes())
{
var method = operationType.GetMethod("GetProviderSettings", BindingFlags.Public | BindingFlags.Static, [typeof(AIStudio.Settings.SettingsManager)]);
Assert.That(method?.ReturnType, Is.EqualTo(typeof(AIOperationProviderSettings)), $"The AI operation '{operationType.Name}' needs a public static GetProviderSettings(SettingsManager), see IAIOperation.");
}
}
/// <summary>
/// Checks the check itself, since the operations alone would let it pass while it finds nothing.
/// </summary>
[Test]
public void TheCheckFindsWritableState()
{
Assert.Multiple(() =>
{
Assert.That(FindWritableState(typeof(StatefulExample)), Is.EquivalentTo(new[] { "StatefulExample.counter", "StatefulExample.Instances", "StatefulExample.Answer", "StatefulExample.Model" }));
Assert.That(FindWritableState(typeof(StatelessExample)), Is.Empty, "Constants, read-only fields, getters, and the parameters of a primary constructor are no state.");
});
}
private static IEnumerable<Type> FindOperationTypes() => typeof(IAIOperation<,>).Assembly.GetTypes().Where(type => type is { IsClass: true, IsAbstract: false } && type.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IAIOperation<,>)));
/// <summary>
/// Lists the fields and properties of a type and its base types which could keep state between calls.
/// </summary>
private static List<string> FindWritableState(Type type)
{
const BindingFlags ALL_DECLARED = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
var writable = new List<string>();
for (var current = type; current is not null && current != typeof(object); current = current.BaseType)
{
foreach (var field in current.GetFields(ALL_DECLARED))
{
if (field.IsLiteral || field.IsInitOnly)
continue;
// The backing field of a property, which the properties below cover:
if (field.IsDefined(typeof(CompilerGeneratedAttribute)) && field.Name.EndsWith("k__BackingField", StringComparison.Ordinal))
continue;
// A parameter of a primary constructor, which the compiler keeps as a field named <name>P:
if (field.Name.StartsWith('<') && field.Name.EndsWith(">P", StringComparison.Ordinal))
continue;
writable.Add($"{current.Name}.{field.Name}");
}
foreach (var property in current.GetProperties(ALL_DECLARED))
if (property.SetMethod is not null)
writable.Add($"{current.Name}.{property.Name}");
}
return writable;
}
private static string ReadProgramSource([CallerFilePath] string sourceFilePath = "") => File.ReadAllText(Path.Combine(Path.GetDirectoryName(sourceFilePath)!, "..", "..", "MindWork AI Studio", "Program.cs"));
// ReSharper disable UnusedMember.Local
private sealed class StatefulExample
{
private int counter;
public StatefulExample() => Instances++;
private static int Instances { get; set; }
public string Answer { get; set; } = string.Empty;
public string Model { get; init; } = string.Empty;
public int Count() => ++this.counter + Instances;
}
private sealed class StatelessExample(string name)
{
private const int LIMIT = 3;
private static readonly string PREFIX = "prefix";
private readonly int limit = LIMIT;
public string Name => $"{PREFIX}{name}{this.limit}";
public int Limit { get; } = LIMIT;
}
// ReSharper restore UnusedMember.Local
}
@@ -0,0 +1,167 @@
using AIStudio.AIOperations;
using AIStudio.AIOperations.DataSourceChoice;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
using AIStudio.Tools.RAG.DataSourceSelectionProcesses;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.AIOperations;
/// <summary>
/// Checks which provider selects the data sources in the classic RAG process.
/// </summary>
/// <remarks>
/// The provider reads the descriptions of the data sources, and what it chooses decides what is searched.
/// It therefore has to be allowed to see them, by their security and by the confidence they require, and a
/// provider which is not falls back on the provider of the chat, which the chat already checked. Names are
/// written out in full where a short one would find a namespace of this assembly first.
/// </remarks>
[TestFixture]
public sealed class DataSourceChoiceProviderTests
{
private const string CHAT_PROVIDER_ID = "11111111-1111-1111-1111-111111111111";
private const string OWN_PROVIDER_ID = "22222222-2222-2222-2222-222222222222";
[Test]
public void FallsBackToTheChatProvider()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, CHAT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, OWN_PROVIDER_ID, LLMProviders.MISTRAL);
var choice = Choose(settingsManager, [OpenServer()]);
Assert.That(choice.Provider.Id, Is.EqualTo(CHAT_PROVIDER_ID));
}
[Test]
public void PrefersItsOwnProvider()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, CHAT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, OWN_PROVIDER_ID, LLMProviders.MISTRAL);
PickOwnProvider(settingsManager);
var choice = Choose(settingsManager, [OpenServer()]);
Assert.That(choice.Provider.Id, Is.EqualTo(OWN_PROVIDER_ID));
}
/// <summary>
/// Checks that a provider which must not see a data source falls back instead of ending the selection.
/// </summary>
/// <remarks>
/// A server for self-hosted providers refuses a cloud provider. The provider of the chat, a self-hosted
/// one, may see it, and the chat already uses it for the very same data.
/// </remarks>
[Test]
public void AnOwnProviderRefusedByTheSecurityOfADataSourceFallsBack()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, CHAT_PROVIDER_ID, LLMProviders.SELF_HOSTED, isSelfHosted: true);
AddProvider(settingsManager, OWN_PROVIDER_ID, LLMProviders.MISTRAL);
PickOwnProvider(settingsManager);
var choice = Choose(settingsManager, [SelfHostedServer()]);
Assert.Multiple(() =>
{
Assert.That(choice.Provider.Id, Is.EqualTo(CHAT_PROVIDER_ID));
Assert.That(choice.PreferredIssue, Is.EqualTo(AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT));
});
}
[Test]
public void AnOwnProviderBelowWhatADataSourceRequiresFallsBack()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, CHAT_PROVIDER_ID, LLMProviders.SELF_HOSTED, isSelfHosted: true);
AddProvider(settingsManager, OWN_PROVIDER_ID, LLMProviders.MISTRAL);
PickOwnProvider(settingsManager);
var choice = Choose(settingsManager, [LocalDirectory(ConfidenceLevel.HIGH)]);
Assert.Multiple(() =>
{
Assert.That(choice.Provider.Id, Is.EqualTo(CHAT_PROVIDER_ID));
Assert.That(choice.PreferredIssue, Is.EqualTo(AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT));
});
}
[Test]
public void NoProviderWhenNoneMaySeeTheDataSources()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, CHAT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, OWN_PROVIDER_ID, LLMProviders.MISTRAL);
PickOwnProvider(settingsManager);
var choice = Choose(settingsManager, [SelfHostedServer()]);
Assert.Multiple(() =>
{
Assert.That(choice.HasProvider, Is.False, "No provider may read the descriptions of a server it must not see.");
Assert.That(choice.FallbackIssue, Is.EqualTo(AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT));
});
}
[Test]
public void ItsOwnMinimumAppliesToTheChatProvider()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, CHAT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, OWN_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.AgentDataSourceSelection.PreselectAgentOptions = true;
settingsManager.ConfigurationData.AgentDataSourceSelection.MinimumProviderConfidence = ConfidenceLevel.HIGH;
var choice = Choose(settingsManager, [OpenServer()]);
Assert.That(choice.HasProvider, Is.False);
}
private static AIOperationProviderChoice Choose(SettingsManager settingsManager, IReadOnlyList<IDataSource> dataSources)
{
var resolver = new AIOperationProviderResolver(settingsManager, NullLogger<AIOperationProviderResolver>.Instance);
return resolver.Preview(DataSourceChoiceOperation.GetProviderSettings(settingsManager), dataSources.GetRequiredConfidenceLevel(), AgenticSrcSelWithDynHeur.GetChoiceProviderOptions(settingsManager, CHAT_PROVIDER_ID, dataSources));
}
private static void PickOwnProvider(SettingsManager settingsManager)
{
settingsManager.ConfigurationData.AgentDataSourceSelection.PreselectAgentOptions = true;
settingsManager.ConfigurationData.AgentDataSourceSelection.PreselectedAgentProvider = OWN_PROVIDER_ID;
}
private static IDataSource OpenServer() => new DataSourceERI_V1
{
Id = "2a8d5f1c-7e3b-4c9a-b6d2-5f8e1a3c7b49",
Name = "Server for any provider",
SecurityPolicy = DataSourceSecurity.ALLOW_ANY,
};
private static IDataSource SelfHostedServer() => new DataSourceERI_V1
{
Id = "9e4a2c7f-5b1d-4f6e-a8c3-1d7b4e9f2a65",
Name = "Server for self-hosted providers",
SecurityPolicy = DataSourceSecurity.SELF_HOSTED,
};
private static IDataSource LocalDirectory(ConfidenceLevel confidenceLevel) => new DataSourceLocalDirectory
{
Id = "5c1e9a7d-3f2b-4e8a-9d6c-7b4a2e1f8c35",
Name = "Handbook",
ConfidenceLevel = confidenceLevel,
};
/// <summary>
/// Builds a settings manager without the rust service, which choosing a provider never asks.
/// </summary>
private static SettingsManager CreateSettingsManager() => new(NullLogger<SettingsManager>.Instance, null!);
private static void AddProvider(SettingsManager settingsManager, string id, LLMProviders llmProvider, bool isSelfHosted = false)
{
var providers = settingsManager.ConfigurationData.Providers;
providers.Add(new((uint)providers.Count + 1, id, $"Instance {providers.Count + 1}", llmProvider, new("test-model", null), IsSelfHosted: isSelfHosted));
}
}
@@ -0,0 +1,170 @@
using AIStudio.AIOperations;
using AIStudio.AIOperations.PluginAudit;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Tools.PluginSystem.Assistants;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.AIOperations;
/// <summary>
/// Checks which provider audits a plugin.
/// </summary>
/// <remarks>
/// The audit may be given a model of its own, which an organization rolls out. Without one, it falls back on
/// the app-wide default, and then on the provider at hand: the one picked in the audit dialog, or for the
/// assistant being built. Names are written out in full where a short one would find a namespace of this
/// assembly first, see AIOperationProviderResolverTests.
/// </remarks>
[TestFixture]
public sealed class PluginAuditProviderTests
{
private const string AT_HAND_PROVIDER_ID = "11111111-1111-1111-1111-111111111111";
private const string AUDIT_PROVIDER_ID = "22222222-2222-2222-2222-222222222222";
private const string APP_DEFAULT_PROVIDER_ID = "33333333-3333-3333-3333-333333333333";
/// <summary>
/// Checks that the audit's provider needs no switch to be used.
/// </summary>
/// <remarks>
/// Unlike the content cleaner, the audit has no "preselect options" flag: an organization rolls its
/// provider out and that is what audits run with. A test which assumed the two behaved alike would
/// pass here for the wrong reason.
/// </remarks>
[Test]
public void UsesItsOwnProviderWithoutAPreselectionSwitch()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, AUDIT_PROVIDER_ID, LLMProviders.MISTRAL);
AddProvider(settingsManager, APP_DEFAULT_PROVIDER_ID, LLMProviders.OPEN_AI);
settingsManager.ConfigurationData.App.PreselectedProvider = APP_DEFAULT_PROVIDER_ID;
settingsManager.ConfigurationData.AssistantPluginAudit.PreselectedAgentProvider = AUDIT_PROVIDER_ID;
var choice = Choose(settingsManager, null);
Assert.That(choice.Provider.Id, Is.EqualTo(AUDIT_PROVIDER_ID), "A provider rolled out for audits outranks the app-wide default.");
}
[Test]
public void FallsBackToTheAppDefault()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, AT_HAND_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, APP_DEFAULT_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.App.PreselectedProvider = APP_DEFAULT_PROVIDER_ID;
var choice = Choose(settingsManager, null);
Assert.That(choice.Provider.Id, Is.EqualTo(APP_DEFAULT_PROVIDER_ID), "Without a dedicated audit provider, the app-wide default is what audits run with.");
}
/// <summary>
/// Checks the state the audit dialog was useless in before it offered a provider itself.
/// </summary>
[Test]
public void EndsUpWithNothingWhenNeitherIsConfigured()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, AT_HAND_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, AUDIT_PROVIDER_ID, LLMProviders.MISTRAL);
var choice = Choose(settingsManager, null);
Assert.Multiple(() =>
{
Assert.That(choice.HasProvider, Is.False, "Two configured providers are not a choice: without one being named for audits, the audit has none.");
Assert.That(AssistantPluginAuditService.GetRelevantIssue(choice), Is.EqualTo(AIOperationProviderIssue.NOT_SET), "The dialog then says that nothing is set, not that something is wrong.");
});
}
[Test]
public void RejectsAnAppDefaultBelowTheGlobalMinimum()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, AT_HAND_PROVIDER_ID, LLMProviders.SELF_HOSTED);
AddProvider(settingsManager, APP_DEFAULT_PROVIDER_ID, LLMProviders.OPEN_AI);
settingsManager.ConfigurationData.App.PreselectedProvider = APP_DEFAULT_PROVIDER_ID;
settingsManager.ConfigurationData.Confidence.EnforceGlobalMinimumConfidence = true;
settingsManager.ConfigurationData.Confidence.GlobalMinimumConfidence = ConfidenceLevel.HIGH;
var choice = Choose(settingsManager, null);
Assert.Multiple(() =>
{
Assert.That(choice.HasProvider, Is.False, "The app-wide default is not exempt from what the organization enforces.");
Assert.That(AssistantPluginAuditService.GetRelevantIssue(choice), Is.EqualTo(AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE));
});
}
[Test]
public void FallsBackToTheProviderAtHandLast()
{
var settingsManager = CreateSettingsManager();
var providerAtHand = AddProvider(settingsManager, AT_HAND_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, AUDIT_PROVIDER_ID, LLMProviders.MISTRAL);
var choice = Choose(settingsManager, providerAtHand);
Assert.That(choice.Provider.Id, Is.EqualTo(AT_HAND_PROVIDER_ID));
}
[Test]
public void TheAppDefaultComesBeforeTheProviderAtHand()
{
var settingsManager = CreateSettingsManager();
var providerAtHand = AddProvider(settingsManager, AT_HAND_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, APP_DEFAULT_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.App.PreselectedProvider = APP_DEFAULT_PROVIDER_ID;
var choice = Choose(settingsManager, providerAtHand);
Assert.That(choice.Provider.Id, Is.EqualTo(APP_DEFAULT_PROVIDER_ID));
}
/// <summary>
/// Checks that a provider picked for something else clears the bar of the audit before it reads a plugin.
/// </summary>
[Test]
public void ItsOwnMinimumAppliesToTheProviderAtHand()
{
var settingsManager = CreateSettingsManager();
var providerAtHand = AddProvider(settingsManager, AT_HAND_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, AUDIT_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.AssistantPluginAudit.MinimumProviderConfidence = ConfidenceLevel.HIGH;
var choice = Choose(settingsManager, providerAtHand);
Assert.Multiple(() =>
{
Assert.That(choice.HasProvider, Is.False, "A provider an organization ruled out for audits must not read a plugin because it was at hand.");
Assert.That(AssistantPluginAuditService.GetRelevantIssue(choice), Is.EqualTo(AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE));
});
}
private static AIOperationProviderChoice Choose(SettingsManager settingsManager, AIStudio.Settings.Provider? providerAtHand)
{
var resolver = new AIOperationProviderResolver(settingsManager, NullLogger<AIOperationProviderResolver>.Instance);
return resolver.Preview(PluginAuditOperation.GetProviderSettings(settingsManager), ConfidenceLevel.NONE, AssistantPluginAuditService.GetProviderOptions(settingsManager, providerAtHand));
}
/// <summary>
/// Builds a settings manager without the rust service, which choosing a provider never asks.
/// </summary>
private static SettingsManager CreateSettingsManager() => new(NullLogger<SettingsManager>.Instance, null!);
/// <summary>
/// Adds a provider to the settings.
/// </summary>
/// <remarks>
/// Every test here configures at least two of them: with exactly one configured provider, it is the
/// app-wide default whatever the settings name, and a test would pass no matter what the fallback does.
/// </remarks>
private static AIStudio.Settings.Provider AddProvider(SettingsManager settingsManager, string id, LLMProviders llmProvider)
{
var providers = settingsManager.ConfigurationData.Providers;
var provider = new AIStudio.Settings.Provider((uint)providers.Count + 1, id, $"Instance {providers.Count + 1}", llmProvider, new("test-model", null));
providers.Add(provider);
return provider;
}
}
@@ -0,0 +1,95 @@
using AIStudio.AIOperations;
using AIStudio.AIOperations.RetrievalContextValidation;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Settings.DataModel;
using AIStudio.Tools.RAG;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.AIOperations;
/// <summary>
/// Checks which provider validates the passages which the classic RAG process found.
/// </summary>
/// <remarks>
/// The provider reads the passages, so it has to meet what the chat requires of every provider which reads
/// its data: the data security and the confidence. A provider which does not falls back on the provider of
/// the chat. Names are written out in full where a short one would find a namespace of this assembly first.
/// </remarks>
[TestFixture]
public sealed class RetrievalContextValidationProviderTests
{
private const string CHAT_PROVIDER_ID = "11111111-1111-1111-1111-111111111111";
private const string OWN_PROVIDER_ID = "22222222-2222-2222-2222-222222222222";
[Test]
public void PrefersItsOwnProvider()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, CHAT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, OWN_PROVIDER_ID, LLMProviders.MISTRAL);
PickOwnProvider(settingsManager);
var choice = Choose(settingsManager, DataSourceSecurity.ALLOW_ANY, ConfidenceLevel.NONE);
Assert.That(choice.Provider.Id, Is.EqualTo(OWN_PROVIDER_ID));
}
[Test]
public void AnOwnProviderRefusedByTheDataSecurityOfTheChatFallsBack()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, CHAT_PROVIDER_ID, LLMProviders.SELF_HOSTED, isSelfHosted: true);
AddProvider(settingsManager, OWN_PROVIDER_ID, LLMProviders.MISTRAL);
PickOwnProvider(settingsManager);
var choice = Choose(settingsManager, DataSourceSecurity.SELF_HOSTED, ConfidenceLevel.NONE);
Assert.Multiple(() =>
{
Assert.That(choice.Provider.Id, Is.EqualTo(CHAT_PROVIDER_ID), "Passages from a server for self-hosted providers must not reach a cloud provider through the validation.");
Assert.That(choice.PreferredIssue, Is.EqualTo(AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT));
});
}
[Test]
public void AnOwnProviderBelowTheConfidenceOfTheChatFallsBack()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, CHAT_PROVIDER_ID, LLMProviders.SELF_HOSTED, isSelfHosted: true);
AddProvider(settingsManager, OWN_PROVIDER_ID, LLMProviders.MISTRAL);
PickOwnProvider(settingsManager);
var choice = Choose(settingsManager, DataSourceSecurity.ALLOW_ANY, ConfidenceLevel.HIGH);
Assert.Multiple(() =>
{
Assert.That(choice.Provider.Id, Is.EqualTo(CHAT_PROVIDER_ID));
Assert.That(choice.PreferredIssue, Is.EqualTo(AIOperationProviderIssue.NOT_ALLOWED_FOR_CONTENT));
});
}
private static AIOperationProviderChoice Choose(SettingsManager settingsManager, DataSourceSecurity dataSecurity, ConfidenceLevel requiredConfidence)
{
var resolver = new AIOperationProviderResolver(settingsManager, NullLogger<AIOperationProviderResolver>.Instance);
return resolver.Preview(RetrievalContextValidationOperation.GetProviderSettings(settingsManager), requiredConfidence, ClassicRagProviderOptions.ForDataAccess(settingsManager, CHAT_PROVIDER_ID, dataSecurity, requiredConfidence));
}
private static void PickOwnProvider(SettingsManager settingsManager)
{
settingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectAgentOptions = true;
settingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectedAgentProvider = OWN_PROVIDER_ID;
}
/// <summary>
/// Builds a settings manager without the rust service, which choosing a provider never asks.
/// </summary>
private static SettingsManager CreateSettingsManager() => new(NullLogger<SettingsManager>.Instance, null!);
private static void AddProvider(SettingsManager settingsManager, string id, LLMProviders llmProvider, bool isSelfHosted = false)
{
var providers = settingsManager.ConfigurationData.Providers;
providers.Add(new((uint)providers.Count + 1, id, $"Instance {providers.Count + 1}", llmProvider, new("test-model", null), IsSelfHosted: isSelfHosted));
}
}
@@ -0,0 +1,176 @@
using AIStudio.AIOperations;
using AIStudio.AIOperations.TextContentCleaning;
using AIStudio.Provider;
using AIStudio.Settings;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.AIOperations;
/// <summary>
/// Checks which provider the text content cleaner is handed when a web page is read in an assistant.
/// </summary>
/// <remarks>
/// The cleaner may be given a model of its own, because a small and cheap one is enough for what it does.
/// Almost nobody does that, so what matters in practice is what happens when it has none: the model of the
/// assistant it sits in, the app-wide default, or nothing at all. Two bugs shipped in that fallback, which is
/// why it is pinned down here, with the options the reader passes. The component lifecycle itself is not
/// covered; there is no bUnit in this solution. Names are written out in full where a short one would find a
/// namespace of this assembly first, see AIOperationProviderResolverTests.
/// </remarks>
[TestFixture]
public sealed class TextContentCleaningProviderTests
{
private const string ASSISTANT_PROVIDER_ID = "11111111-1111-1111-1111-111111111111";
private const string CLEANER_PROVIDER_ID = "22222222-2222-2222-2222-222222222222";
private const string APP_DEFAULT_PROVIDER_ID = "33333333-3333-3333-3333-333333333333";
[Test]
public void FallsBackToTheAssistantProvider()
{
var settingsManager = CreateSettingsManager();
var assistantProvider = AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, CLEANER_PROVIDER_ID, LLMProviders.MISTRAL);
var choice = Choose(settingsManager, assistantProvider);
Assert.That(choice.Provider.Id, Is.EqualTo(ASSISTANT_PROVIDER_ID), "With nothing configured for the cleaner, it has to use the model of the assistant around it.");
}
[Test]
public void FallsBackToTheAppDefault()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, APP_DEFAULT_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.App.PreselectedProvider = APP_DEFAULT_PROVIDER_ID;
var choice = Choose(settingsManager, AIStudio.Settings.Provider.NONE);
Assert.That(choice.Provider.Id, Is.EqualTo(APP_DEFAULT_PROVIDER_ID), "Without an assistant model, the app-wide default is what is left before giving up.");
}
[Test]
public void PrefersItsOwnProviderOverTheAssistantOne()
{
var settingsManager = CreateSettingsManager();
var assistantProvider = AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, CLEANER_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.TextContentCleaner.PreselectAgentOptions = true;
settingsManager.ConfigurationData.TextContentCleaner.PreselectedAgentProvider = CLEANER_PROVIDER_ID;
var choice = Choose(settingsManager, assistantProvider);
Assert.That(choice.Provider.Id, Is.EqualTo(CLEANER_PROVIDER_ID), "A model picked for the cleaner is the whole point of picking one, so it outranks the assistant's.");
}
/// <summary>
/// Checks that the switch above the cleaner's provider field really turns that provider off.
/// </summary>
/// <remarks>
/// The provider id stays in the settings when the switch goes off, so the only thing saying it
/// must not be used is this one flag. Settings which hand out the stored id instead of asking the
/// flag would keep using a provider the user switched away from.
/// </remarks>
[Test]
public void IgnoresItsOwnProviderWhenPreselectionIsOff()
{
var settingsManager = CreateSettingsManager();
var assistantProvider = AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, CLEANER_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.TextContentCleaner.PreselectAgentOptions = false;
settingsManager.ConfigurationData.TextContentCleaner.PreselectedAgentProvider = CLEANER_PROVIDER_ID;
var choice = Choose(settingsManager, assistantProvider);
Assert.That(choice.Provider.Id, Is.EqualTo(ASSISTANT_PROVIDER_ID), "With its preselection switched off, the cleaner has to fall back to the assistant's model.");
}
/// <summary>
/// Checks that a model too untrusted for the cleaner is not used just because it is there.
/// </summary>
/// <remarks>
/// This is the case the user meets as a hint next to the cleaner switch: a model is selected in
/// the assistant, and the cleaner still has none. Under TRUST_ALL every provider reaches MEDIUM
/// and a self-hosted one reaches HIGH, so a minimum of HIGH separates the two.
/// </remarks>
[Test]
public void RejectsAnAssistantProviderBelowTheGlobalMinimum()
{
var settingsManager = CreateSettingsManager();
var assistantProvider = AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, CLEANER_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.Confidence.EnforceGlobalMinimumConfidence = true;
settingsManager.ConfigurationData.Confidence.GlobalMinimumConfidence = ConfidenceLevel.HIGH;
var choice = Choose(settingsManager, assistantProvider);
Assert.Multiple(() =>
{
Assert.That(choice.HasProvider, Is.False, "A provider the organization ruled out must not reach the cleaner through the assistant.");
Assert.That(choice.FallbackIssue, Is.EqualTo(AIOperationProviderIssue.BELOW_MINIMUM_CONFIDENCE), "The hint next to the switch tells this reason from a missing model.");
});
}
[Test]
public void AcceptsAnAssistantProviderMeetingTheGlobalMinimum()
{
var settingsManager = CreateSettingsManager();
var assistantProvider = AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.SELF_HOSTED);
AddProvider(settingsManager, CLEANER_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.Confidence.EnforceGlobalMinimumConfidence = true;
settingsManager.ConfigurationData.Confidence.GlobalMinimumConfidence = ConfidenceLevel.HIGH;
var choice = Choose(settingsManager, assistantProvider);
Assert.That(choice.Provider.Id, Is.EqualTo(ASSISTANT_PROVIDER_ID), "A provider which clears the bar has to be handed over, or the hint would never go away.");
}
/// <summary>
/// Checks that the minimum of the cleaner itself applies to the model of the assistant as well.
/// </summary>
/// <remarks>
/// Whether a model may read the page is decided by what the cleaner requires, not by what the model was
/// picked for. Otherwise a model ruled out for the cleaner would clean the page anyway.
/// </remarks>
[Test]
public void ItsOwnMinimumAppliesToTheAssistantProvider()
{
var settingsManager = CreateSettingsManager();
var assistantProvider = AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, CLEANER_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.TextContentCleaner.PreselectAgentOptions = true;
settingsManager.ConfigurationData.TextContentCleaner.MinimumProviderConfidence = ConfidenceLevel.HIGH;
var choice = Choose(settingsManager, assistantProvider);
Assert.That(choice.HasProvider, Is.False);
}
private static AIOperationProviderChoice Choose(SettingsManager settingsManager, AIStudio.Settings.Provider assistantProvider)
{
var resolver = new AIOperationProviderResolver(settingsManager, NullLogger<AIOperationProviderResolver>.Instance);
return resolver.Preview(TextContentCleaningOperation.GetProviderSettings(settingsManager), ConfidenceLevel.NONE, AIStudio.Components.ReadWebContent.GetCleanerProviderOptions(settingsManager, assistantProvider));
}
/// <summary>
/// Builds a settings manager without the rust service, which choosing a provider never asks.
/// </summary>
private static SettingsManager CreateSettingsManager() => new(NullLogger<SettingsManager>.Instance, null!);
/// <summary>
/// Adds a provider to the settings.
/// </summary>
/// <remarks>
/// Every test here configures at least two of them, and not for variety: with exactly one configured
/// provider, it is the app-wide default whatever the settings name. A single-provider test would pass no
/// matter what the fallback does.
/// </remarks>
private static AIStudio.Settings.Provider AddProvider(SettingsManager settingsManager, string id, LLMProviders llmProvider)
{
var providers = settingsManager.ConfigurationData.Providers;
var provider = new AIStudio.Settings.Provider((uint)providers.Count + 1, id, $"Instance {providers.Count + 1}", llmProvider, new("test-model", null));
providers.Add(provider);
return provider;
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
using AIStudio.Agents;
using AIStudio.AIOperations.DataSourceChoice;
using AIStudio.Chat;
using AIStudio.Components;
using AIStudio.Provider;
@@ -120,7 +120,7 @@ public sealed class ChatThreadRollbackTests
using (Assert.EnterMultipleScope())
{
Assert.That(thread.AugmentedData, Is.Empty, "Nobody knows whether the retrieved data belongs to a kept or to a removed message, so it must not reach the next system prompt.");
Assert.That(thread.AISelectedDataSources, Is.Empty, "The data sources an agent picked belong to the same retrieval as the data.");
Assert.That(thread.AISelectedDataSources, Is.Empty, "The data sources an AI operation picked belong to the same retrieval as the data.");
Assert.That(thread.DataSourceOptions, Is.SameAs(options), "The data source options are the user's choice, not the result of a message.");
Assert.That(options.DisableDataSources, Is.False);
Assert.That(options.AutomaticDataSourceSelection, Is.True);
@@ -1,5 +1,7 @@
using AIStudio.Agents;
using AIStudio.Agents.AssistantAudit;
using AIStudio.AIOperations;
using AIStudio.AIOperations.DataSourceChoice;
using AIStudio.AIOperations.PluginAudit;
using AIStudio.AIOperations.RetrievalContextValidation;
using AIStudio.Assistants.BeyondFactsLab;
using AIStudio.Assistants.Builder;
using AIStudio.Assistants.ERI;
@@ -14,17 +16,17 @@ namespace AIStudio.Tests.Serialization;
public static partial class JsonTestRoots
{
/// <summary>
/// The JSON which models write for the agents and assistants of AI Studio, apart from the Visual Briefing
/// The JSON which models write for the AI operations and assistants of AI Studio, apart from the Visual Briefing
/// assistant.
/// </summary>
public static IEnumerable<TestCaseData> ModelAnswers()
{
TestHost.PrepareStaticState();
// The agents, which select data sources, check retrieved passages, and audit assistant plugins:
yield return Case(new(typeof(List<SelectedDataSource>), AgentBase.JSON_SERIALIZER_OPTIONS));
yield return Case(new(typeof(RetrievalContextValidationResult), AgentBase.JSON_SERIALIZER_OPTIONS));
yield return Case(new(typeof(AssistantAuditResult), AgentBase.JSON_SERIALIZER_OPTIONS));
// The AI operations, which select data sources, check retrieved passages, and audit assistant plugins:
yield return Case(new(typeof(List<SelectedDataSource>), AIOperationsJson.OPTIONS));
yield return Case(new(typeof(RetrievalContextValidationResult), AIOperationsJson.OPTIONS));
yield return Case(new(typeof(PluginAuditResult), AIOperationsJson.OPTIONS));
// The Assistant Builder, for assistant plugins and for direct chat launchers:
yield return Case(new(typeof(LuaResponse), LuaResponse.JSON_OPTIONS));
@@ -0,0 +1,75 @@
using AIStudio.Provider;
using AIStudio.Settings;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.Settings;
/// <summary>
/// Checks when the minimum confidence of a background task applies.
/// </summary>
/// <remarks>
/// The text content cleaner, the data source selection, and the retrieval context validation apply their
/// provider and their minimum only while their preselection is switched on, like the assistants. The audit
/// of plugins has no such switch, so its minimum always applies. Names are written out in full where a short
/// one would find a namespace of this assembly first, see AIOperationProviderResolverTests.
/// </remarks>
[TestFixture]
public sealed class BackgroundTaskMinimumConfidenceTests
{
[Test]
public void TheTextContentCleanerAppliesItsMinimumOnlyWithItsPreselection()
{
var settingsManager = CreateSettingsManager();
settingsManager.ConfigurationData.TextContentCleaner.MinimumProviderConfidence = ConfidenceLevel.HIGH;
AssertMinimumFollowsPreselection(settingsManager, AIStudio.Tools.Components.AGENT_TEXT_CONTENT_CLEANER, on => settingsManager.ConfigurationData.TextContentCleaner.PreselectAgentOptions = on);
}
[Test]
public void TheDataSourceSelectionAppliesItsMinimumOnlyWithItsPreselection()
{
var settingsManager = CreateSettingsManager();
settingsManager.ConfigurationData.AgentDataSourceSelection.MinimumProviderConfidence = ConfidenceLevel.HIGH;
AssertMinimumFollowsPreselection(settingsManager, AIStudio.Tools.Components.AGENT_DATA_SOURCE_SELECTION, on => settingsManager.ConfigurationData.AgentDataSourceSelection.PreselectAgentOptions = on);
}
[Test]
public void TheRetrievalContextValidationAppliesItsMinimumOnlyWithItsPreselection()
{
var settingsManager = CreateSettingsManager();
settingsManager.ConfigurationData.AgentRetrievalContextValidation.MinimumProviderConfidence = ConfidenceLevel.HIGH;
AssertMinimumFollowsPreselection(settingsManager, AIStudio.Tools.Components.AGENT_RETRIEVAL_CONTEXT_VALIDATION, on => settingsManager.ConfigurationData.AgentRetrievalContextValidation.PreselectAgentOptions = on);
}
[Test]
public void ThePluginAuditAlwaysAppliesItsMinimum()
{
var settingsManager = CreateSettingsManager();
settingsManager.ConfigurationData.AssistantPluginAudit.MinimumProviderConfidence = ConfidenceLevel.HIGH;
Assert.That(AIStudio.Tools.ComponentsExtensions.MinimumConfidence(AIStudio.Tools.Components.AGENT_ASSISTANT_PLUGIN_AUDIT, settingsManager), Is.EqualTo(ConfidenceLevel.HIGH), "The audit has no preselection switch, so nothing may turn its minimum off.");
}
private static void AssertMinimumFollowsPreselection(SettingsManager settingsManager, AIStudio.Tools.Components component, Action<bool> setPreselection)
{
setPreselection(false);
var minimumWithoutPreselection = AIStudio.Tools.ComponentsExtensions.MinimumConfidence(component, settingsManager);
setPreselection(true);
var minimumWithPreselection = AIStudio.Tools.ComponentsExtensions.MinimumConfidence(component, settingsManager);
Assert.Multiple(() =>
{
Assert.That(minimumWithoutPreselection, Is.EqualTo(ConfidenceLevel.NONE), "With the preselection switched off, the stored minimum must not apply.");
Assert.That(minimumWithPreselection, Is.EqualTo(ConfidenceLevel.HIGH));
});
}
/// <summary>
/// Builds a settings manager without the rust service, which reading a minimum never asks.
/// </summary>
private static SettingsManager CreateSettingsManager() => new(NullLogger<SettingsManager>.Instance, null!);
}
@@ -73,7 +73,7 @@ public sealed class ChatTemplateConfigurationTests
using (Assert.EnterMultipleScope())
{
Assert.That(read.DataSourceOptions, Is.Not.Null);
Assert.That(read.DataSourceOptions!.AutomaticDataSourceSelection, Is.True, "Letting an agent pick the sources is the one thing only a chat template can state, so it must not be lost on the way through Lua.");
Assert.That(read.DataSourceOptions!.AutomaticDataSourceSelection, Is.True, "Letting an AI operation pick the sources is the one thing only a chat template can state, so it must not be lost on the way through Lua.");
Assert.That(read.DataSourceOptions.PreselectedDataSourceIds, Is.Empty);
Assert.That(read.ToolIds, Is.Null);
}
@@ -383,7 +383,7 @@ public sealed class ChatTemplateConfigurationTests
using (Assert.EnterMultipleScope())
{
Assert.That(ChatTemplate.GetPreselectedLocalDataSourceNames(eriOnly, ConfiguredDataSources()), Is.Empty);
Assert.That(ChatTemplate.GetPreselectedLocalDataSourceNames(agentic, ConfiguredDataSources()), Is.Empty, "An agent picks the sources per message, so this template names none to begin with.");
Assert.That(ChatTemplate.GetPreselectedLocalDataSourceNames(agentic, ConfiguredDataSources()), Is.Empty, "An AI operation picks the sources per message, so this template names none to begin with.");
Assert.That(ChatTemplate.GetPreselectedLocalDataSourceNames(NewTemplate(), ConfiguredDataSources()), Is.Empty);
}
}
@@ -11,7 +11,7 @@ namespace AIStudio.Tests.Settings;
/// Either side can be filled in without knowing about the other, so all four combinations happen.
/// The rule is deliberately the same for tools and for data sources: the chat template wins as a
/// whole, because it is the only one of the two which can also leave the choice of sources to an
/// agent, and a field-by-field mix of both would be something neither of them asked for.
/// AI operation, and a field-by-field mix of both would be something neither of them asked for.
/// </remarks>
[TestFixture]
public sealed class ChatTemplatePrecedenceTests
@@ -115,7 +115,7 @@ public sealed class ChatTemplatePrecedenceTests
using (Assert.EnterMultipleScope())
{
Assert.That(optionsChoice.Options!.AutomaticDataSourceSelection, Is.True, "Letting an agent pick the sources is the one thing a launcher cannot express, so it is exactly what must not be overwritten by one.");
Assert.That(optionsChoice.Options!.AutomaticDataSourceSelection, Is.True, "Letting an AI operation pick the sources is the one thing a launcher cannot express, so it is exactly what must not be overwritten by one.");
Assert.That(optionsChoice.Options.PreselectedDataSourceIds, Is.Empty);
Assert.That(optionsChoice.LauncherChoiceDropped, Is.True);
}
@@ -1,217 +0,0 @@
using AIStudio.Provider;
using AIStudio.Settings;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.Settings;
/// <summary>
/// Checks which provider an agent is handed when nobody picked one for it.
/// </summary>
/// <remarks>
/// Agents such as the content cleaner or the security audit may be given a model of their own,
/// because a small and cheap one is enough for what they do. Almost nobody does that, so what
/// matters in practice is what happens when they have none: the model of the assistant they sit
/// in, the app-wide default, or nothing at all. Two bugs shipped in that fallback, and both of
/// them lived here rather than in the components -- which is why this is where they are pinned
/// down. The component lifecycle itself is not covered; there is no bUnit in this solution.
///
/// Names are written out in full throughout. This assembly has an AIStudio.Tests.Tools and an
/// AIStudio.Tests.Provider of its own, and the app has an AIStudio.Components -- all three are
/// what a short name finds from here, and a using alias does not help, because names from the
/// enclosing namespaces win over it.
/// </remarks>
[TestFixture]
public sealed class PreselectedProviderTests
{
private const string ASSISTANT_PROVIDER_ID = "11111111-1111-1111-1111-111111111111";
private const string AGENT_PROVIDER_ID = "22222222-2222-2222-2222-222222222222";
private const string APP_DEFAULT_PROVIDER_ID = "33333333-3333-3333-3333-333333333333";
[Test]
public void ContentCleanerFallsBackToTheAssistantProvider()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, AGENT_PROVIDER_ID, LLMProviders.MISTRAL);
var provider = settingsManager.GetPreselectedProvider(AIStudio.Tools.Components.AGENT_TEXT_CONTENT_CLEANER, ASSISTANT_PROVIDER_ID, true);
Assert.That(provider.Id, Is.EqualTo(ASSISTANT_PROVIDER_ID), "With nothing configured for the cleaner, it has to use the model of the assistant around it.");
}
[Test]
public void ContentCleanerFallsBackToTheAppDefault()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, APP_DEFAULT_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.App.PreselectedProvider = APP_DEFAULT_PROVIDER_ID;
var provider = settingsManager.GetPreselectedProvider(AIStudio.Tools.Components.AGENT_TEXT_CONTENT_CLEANER, null, true);
Assert.That(provider.Id, Is.EqualTo(APP_DEFAULT_PROVIDER_ID), "Without an assistant model, the app-wide default is what is left before giving up.");
}
[Test]
public void ContentCleanerPrefersItsOwnProviderOverTheAssistantOne()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, AGENT_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.TextContentCleaner.PreselectAgentOptions = true;
settingsManager.ConfigurationData.TextContentCleaner.PreselectedAgentProvider = AGENT_PROVIDER_ID;
var provider = settingsManager.GetPreselectedProvider(AIStudio.Tools.Components.AGENT_TEXT_CONTENT_CLEANER, ASSISTANT_PROVIDER_ID, true);
Assert.That(provider.Id, Is.EqualTo(AGENT_PROVIDER_ID), "A model picked for the cleaner is the whole point of picking one, so it outranks the assistant's.");
}
/// <summary>
/// Checks that the switch above the cleaner's provider field really turns that provider off.
/// </summary>
/// <remarks>
/// The provider id stays in the settings when the switch goes off, so the only thing saying it
/// must not be used is this one flag. A component which reads the stored id instead of asking
/// here would keep using a provider the user switched away from.
/// </remarks>
[Test]
public void ContentCleanerIgnoresItsOwnProviderWhenPreselectionIsOff()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, AGENT_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.TextContentCleaner.PreselectAgentOptions = false;
settingsManager.ConfigurationData.TextContentCleaner.PreselectedAgentProvider = AGENT_PROVIDER_ID;
var provider = settingsManager.GetPreselectedProvider(AIStudio.Tools.Components.AGENT_TEXT_CONTENT_CLEANER, ASSISTANT_PROVIDER_ID, true);
Assert.That(provider.Id, Is.EqualTo(ASSISTANT_PROVIDER_ID), "With its preselection switched off, the cleaner has to fall back to the assistant's model.");
}
/// <summary>
/// Checks that a model too untrusted for the cleaner is not used just because it is there.
/// </summary>
/// <remarks>
/// This is the case the user meets as a hint next to the cleaner switch: a model is selected in
/// the assistant, and the cleaner still has none. Under TRUST_ALL every provider reaches MEDIUM
/// and a self-hosted one reaches HIGH, so a global minimum of HIGH separates the two.
/// </remarks>
[Test]
public void ContentCleanerRejectsAnAssistantProviderBelowTheGlobalMinimum()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, AGENT_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.Confidence.EnforceGlobalMinimumConfidence = true;
settingsManager.ConfigurationData.Confidence.GlobalMinimumConfidence = ConfidenceLevel.HIGH;
var provider = settingsManager.GetPreselectedProvider(AIStudio.Tools.Components.AGENT_TEXT_CONTENT_CLEANER, ASSISTANT_PROVIDER_ID, true);
Assert.That(provider, Is.EqualTo(AIStudio.Settings.Provider.NONE), "A provider the organization ruled out must not reach the cleaner through the assistant.");
}
[Test]
public void ContentCleanerAcceptsAnAssistantProviderMeetingTheGlobalMinimum()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.SELF_HOSTED);
AddProvider(settingsManager, AGENT_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.Confidence.EnforceGlobalMinimumConfidence = true;
settingsManager.ConfigurationData.Confidence.GlobalMinimumConfidence = ConfidenceLevel.HIGH;
var provider = settingsManager.GetPreselectedProvider(AIStudio.Tools.Components.AGENT_TEXT_CONTENT_CLEANER, ASSISTANT_PROVIDER_ID, true);
Assert.That(provider.Id, Is.EqualTo(ASSISTANT_PROVIDER_ID), "A provider which clears the bar has to be handed over, or the hint would never go away.");
}
/// <summary>
/// Checks that the audit agent's provider needs no switch to be used.
/// </summary>
/// <remarks>
/// Unlike the content cleaner, the audit agent has no "preselect options" flag: an organization
/// rolls its provider out and that is what audits run with. A test which assumed the two agents
/// behaved alike would pass here for the wrong reason.
/// </remarks>
[Test]
public void AuditAgentUsesItsOwnProviderWithoutAPreselectionSwitch()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, AGENT_PROVIDER_ID, LLMProviders.MISTRAL);
AddProvider(settingsManager, APP_DEFAULT_PROVIDER_ID, LLMProviders.OPEN_AI);
settingsManager.ConfigurationData.App.PreselectedProvider = APP_DEFAULT_PROVIDER_ID;
settingsManager.ConfigurationData.AssistantPluginAudit.PreselectedAgentProvider = AGENT_PROVIDER_ID;
var provider = settingsManager.GetPreselectedProvider(AIStudio.Tools.Components.AGENT_ASSISTANT_PLUGIN_AUDIT, null, true);
Assert.That(provider.Id, Is.EqualTo(AGENT_PROVIDER_ID), "A provider rolled out for audits outranks the app-wide default.");
}
[Test]
public void AuditAgentFallsBackToTheAppDefault()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, APP_DEFAULT_PROVIDER_ID, LLMProviders.MISTRAL);
settingsManager.ConfigurationData.App.PreselectedProvider = APP_DEFAULT_PROVIDER_ID;
var provider = settingsManager.GetPreselectedProvider(AIStudio.Tools.Components.AGENT_ASSISTANT_PLUGIN_AUDIT, null, true);
Assert.That(provider.Id, Is.EqualTo(APP_DEFAULT_PROVIDER_ID), "Without a dedicated audit provider, the app-wide default is what audits run with.");
}
/// <summary>
/// Checks the state the audit dialog was useless in before it offered a provider itself.
/// </summary>
[Test]
public void AuditAgentEndsUpWithNothingWhenNeitherIsConfigured()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.OPEN_AI);
AddProvider(settingsManager, AGENT_PROVIDER_ID, LLMProviders.MISTRAL);
var provider = settingsManager.GetPreselectedProvider(AIStudio.Tools.Components.AGENT_ASSISTANT_PLUGIN_AUDIT, null, true);
Assert.That(provider, Is.EqualTo(AIStudio.Settings.Provider.NONE), "Two configured providers are not a choice: without one being named for audits, the agent has none.");
}
[Test]
public void AuditAgentRejectsAnAppDefaultBelowTheGlobalMinimum()
{
var settingsManager = CreateSettingsManager();
AddProvider(settingsManager, ASSISTANT_PROVIDER_ID, LLMProviders.SELF_HOSTED);
AddProvider(settingsManager, APP_DEFAULT_PROVIDER_ID, LLMProviders.OPEN_AI);
settingsManager.ConfigurationData.App.PreselectedProvider = APP_DEFAULT_PROVIDER_ID;
settingsManager.ConfigurationData.Confidence.EnforceGlobalMinimumConfidence = true;
settingsManager.ConfigurationData.Confidence.GlobalMinimumConfidence = ConfidenceLevel.HIGH;
var provider = settingsManager.GetPreselectedProvider(AIStudio.Tools.Components.AGENT_ASSISTANT_PLUGIN_AUDIT, null, true);
Assert.That(provider, Is.EqualTo(AIStudio.Settings.Provider.NONE), "The app-wide default is not exempt from what the organization enforces.");
}
/// <summary>
/// Builds a settings manager the way these tests need it.
/// </summary>
/// <remarks>
/// The rust service is handed in as null on purpose: resolving a provider never asks it
/// anything. It reads the configured providers, the confidence scheme and the preselections,
/// all of which are plain settings. Should that change, the test says so by failing loudly
/// rather than by quietly measuring something else.
/// </remarks>
private static SettingsManager CreateSettingsManager() => new(NullLogger<SettingsManager>.Instance, null!);
/// <summary>
/// Adds a provider to the settings.
/// </summary>
/// <remarks>
/// Every test here configures at least two of them, and not for variety: with exactly one
/// configured provider, resolving takes a shortcut and returns it without looking at any
/// preselection. A single-provider test would pass no matter what the fallback does.
/// </remarks>
private static void AddProvider(SettingsManager settingsManager, string id, LLMProviders llmProvider)
{
var providers = settingsManager.ConfigurationData.Providers;
providers.Add(new((uint)providers.Count + 1, id, $"Instance {providers.Count + 1}", llmProvider, new("test-model", null)));
}
}
@@ -19,7 +19,7 @@ namespace AIStudio.Tests.Settings;
/// <remarks>
/// The settings are reached through Program.SERVICE_PROVIDER, as in the app, because a managed
/// setting writes its value and its lock there. Names are written out in full where a short one
/// would find a namespace of this assembly first, see PreselectedProviderTests.
/// would find a namespace of this assembly first, see AIOperationProviderResolverTests.
/// </remarks>
[TestFixture]
public sealed class ProhibitedProvidersTests
@@ -67,7 +67,7 @@ public sealed class ClassicRagOutboundDataRestrictionTests : ToolRegistryTestBas
public void BothWaysOfSearchingRestrictTheChatAlike(IDataSource[] dataSources, int[] passageCounts, OutboundDataRestriction organizationMinimum)
{
//
// Semantic Search offers the data sources in a fixed order, while the selection agent of the
// Semantic Search offers the data sources in a fixed order, while the data source selection of the
// classic process may return them in any order. Both have to name the same data source.
//
// AsEnumerable() keeps Reverse() a reversed copy: from C# 14 on, Reverse() on an array
@@ -61,7 +61,7 @@ public sealed class ClassicRagUnreachableTests
{
var unreachable = Checked([INTRANET, WIKI]).GetUnreachableOfTheChat(new DataSourceOptions { AutomaticDataSourceSelection = true });
Assert.That(unreachable, Is.EqualTo(new[] { INTRANET, WIKI }), "The selection agent might have picked any of them.");
Assert.That(unreachable, Is.EqualTo(new[] { INTRANET, WIKI }), "The data source selection might have picked any of them.");
}
[Test]
@@ -1,51 +0,0 @@
using AIStudio.Settings.DataModel;
using AIStudio.Tools.Services;
namespace AIStudio.Tests.Tools;
/// <summary>
/// Checks which agents count as seeing the data of the data sources.
/// </summary>
/// <remarks>
/// Every provider which sees the data must be trusted enough for every data source it sees. That
/// cuts both ways: leaving out an agent which does run would send data to a provider trusted too
/// little, while counting an agent which does not run holds back data sources for no reason. The
/// classic RAG process runs its agents; Semantic Search runs none, since the chat model picks the
/// data sources and judges the passages itself.
/// </remarks>
[TestFixture]
public sealed class DataSourceParticipatingAgentsTests
{
[Test]
public void SemanticSearchRunsNoAgent()
{
var agents = DataSourceService.GetParticipatingAgents(Options(automaticSelection: true, automaticValidation: true), DataSourceRetrievalMode.SEMANTIC_SEARCH, retrievalContextValidationEnabled: true);
Assert.That(agents, Is.Empty, "The chat provider alone sees the data, so its trust alone decides which data sources it may search.");
}
[Test]
public void TheClassicRAGProcessCountsTheAgentsItRuns()
{
var agents = DataSourceService.GetParticipatingAgents(Options(automaticSelection: true, automaticValidation: true), DataSourceRetrievalMode.EVERY_MESSAGE, retrievalContextValidationEnabled: true);
Assert.That(agents.Select(agent => agent.Component), Is.EqualTo(new[] { AIStudio.Tools.Components.AGENT_DATA_SOURCE_SELECTION, AIStudio.Tools.Components.AGENT_RETRIEVAL_CONTEXT_VALIDATION }));
}
[Test]
public void TheClassicRAGProcessCountsNoAgentItDoesNotRun()
{
using (Assert.EnterMultipleScope())
{
Assert.That(DataSourceService.GetParticipatingAgents(Options(automaticSelection: false, automaticValidation: false), DataSourceRetrievalMode.EVERY_MESSAGE, retrievalContextValidationEnabled: true), Is.Empty);
Assert.That(DataSourceService.GetParticipatingAgents(Options(automaticSelection: false, automaticValidation: true), DataSourceRetrievalMode.EVERY_MESSAGE, retrievalContextValidationEnabled: false), Is.Empty, "The validation of this chat is on, but the settings switch it off everywhere.");
}
}
private static DataSourceOptions Options(bool automaticSelection, bool automaticValidation) => new()
{
DisableDataSources = false,
AutomaticDataSourceSelection = automaticSelection,
AutomaticValidation = automaticValidation,
};
}
@@ -0,0 +1,51 @@
using AIStudio.Settings.DataModel;
using AIStudio.Tools.Services;
namespace AIStudio.Tests.Tools;
/// <summary>
/// Checks which AI operations count as seeing the data of the data sources.
/// </summary>
/// <remarks>
/// Every provider which sees the data must be trusted enough for every data source it sees. That
/// cuts both ways: leaving out an operation which does run would send data to a provider trusted too
/// little, while counting an operation which does not run holds back data sources for no reason. The
/// classic RAG process runs its AI operations; Semantic Search runs none, since the chat model picks the
/// data sources and judges the passages itself.
/// </remarks>
[TestFixture]
public sealed class DataSourceParticipatingOperationsTests
{
[Test]
public void SemanticSearchRunsNoOperation()
{
var operations = DataSourceService.GetParticipatingOperations(Options(automaticSelection: true, automaticValidation: true), DataSourceRetrievalMode.SEMANTIC_SEARCH, retrievalContextValidationEnabled: true);
Assert.That(operations, Is.Empty, "The chat provider alone sees the data, so its trust alone decides which data sources it may search.");
}
[Test]
public void TheClassicRAGProcessCountsTheOperationsItRuns()
{
var operations = DataSourceService.GetParticipatingOperations(Options(automaticSelection: true, automaticValidation: true), DataSourceRetrievalMode.EVERY_MESSAGE, retrievalContextValidationEnabled: true);
Assert.That(operations.Select(operation => operation.Component), Is.EqualTo(new[] { AIStudio.Tools.Components.AGENT_DATA_SOURCE_SELECTION, AIStudio.Tools.Components.AGENT_RETRIEVAL_CONTEXT_VALIDATION }));
}
[Test]
public void TheClassicRAGProcessCountsNoOperationItDoesNotRun()
{
using (Assert.EnterMultipleScope())
{
Assert.That(DataSourceService.GetParticipatingOperations(Options(automaticSelection: false, automaticValidation: false), DataSourceRetrievalMode.EVERY_MESSAGE, retrievalContextValidationEnabled: true), Is.Empty);
Assert.That(DataSourceService.GetParticipatingOperations(Options(automaticSelection: false, automaticValidation: true), DataSourceRetrievalMode.EVERY_MESSAGE, retrievalContextValidationEnabled: false), Is.Empty, "The validation of this chat is on, but the settings switch it off everywhere.");
}
}
private static DataSourceOptions Options(bool automaticSelection, bool automaticValidation) => new()
{
DisableDataSources = false,
AutomaticDataSourceSelection = automaticSelection,
AutomaticValidation = automaticValidation,
};
}
@@ -55,7 +55,7 @@ public sealed class DataSourceRequirementsTests
using (Assert.EnterMultipleScope())
{
Assert.That(DataSourceRequirements.Of([HANDBOOK, ARCHIVE], [1, 1], OutboundDataRestriction.UNRESTRICTED).OutboundData, Is.EqualTo(expected));
Assert.That(DataSourceRequirements.Of([ARCHIVE, HANDBOOK], [1, 1], OutboundDataRestriction.UNRESTRICTED).OutboundData, Is.EqualTo(expected), "An agent may select the data sources in another order.");
Assert.That(DataSourceRequirements.Of([ARCHIVE, HANDBOOK], [1, 1], OutboundDataRestriction.UNRESTRICTED).OutboundData, Is.EqualTo(expected), "An AI operation may select the data sources in another order.");
}
}
@@ -191,7 +191,7 @@ public sealed class EmbeddingChangeImpactTests
using (Assert.EnterMultipleScope())
{
Assert.That(EditKeepingTheProvider(embeddingProvider, stored, stored with { Name = "Another name" }), Is.False, "The name is how the data source is offered, not how it was read.");
Assert.That(EditKeepingTheProvider(embeddingProvider, stored, stored with { Description = "Another description" }), Is.False, "The description is there for the agent which picks data sources.");
Assert.That(EditKeepingTheProvider(embeddingProvider, stored, stored with { Description = "Another description" }), Is.False, "The description is there for the AI operation which picks data sources.");
Assert.That(EditKeepingTheProvider(embeddingProvider, stored, stored with { MaxMatches = 42 }), Is.False, "How many matches an answer may use is decided per query.");
Assert.That(EditKeepingTheProvider(embeddingProvider, stored, stored with { ConfidenceLevel = ConfidenceLevel.HIGH }), Is.False, "The confidence level is enforced live on every request and changes no vector.");
}
+1 -1
View File
@@ -22,7 +22,7 @@ public sealed class ModelAnswerJsonTests
""";
/// <summary>
/// A data source selection as the agent is asked to write it.
/// A data source selection as the AI operation is asked to write it.
/// </summary>
private const string SELECTION = """
[
@@ -321,7 +321,7 @@ public sealed class SearchMailsToolTests : ToolRegistryTestBase
[Test]
public void SemanticSearchNeverSeesAMailbox()
{
Assert.That(typeof(IDataSource).IsAssignableFrom(typeof(DataSourceMailbox)), Is.False, "Semantic Search, classic RAG, and the agents take their data sources from DataSources, which holds only IDataSource. A mailbox has its own rules and tools.");
Assert.That(typeof(IDataSource).IsAssignableFrom(typeof(DataSourceMailbox)), Is.False, "Semantic Search, classic RAG, and the AI operations take their data sources from DataSources, which holds only IDataSource. A mailbox has its own rules and tools.");
}
// Stating its definition and reading its arguments needs none of the services the tool searches with: