Fixed the retrieval context validation keeping unhelpful passages (#1217)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-21 20:50:25 +01:00
1 parent 808b95b15d
commit 78f5066bfd
10 files changed
+453 -35

No files matched your search

@@ -11,6 +11,6 @@ namespace AIStudio.AIOperations;
/// </summary> /// </summary>
[JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata)] [JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata)]
[JsonSerializable(typeof(List<SelectedDataSource>))] [JsonSerializable(typeof(List<SelectedDataSource>))]
[JsonSerializable(typeof(RetrievalContextValidationResult))] [JsonSerializable(typeof(RetrievalContextValidationAnswer))]
[JsonSerializable(typeof(PluginAuditResult))] [JsonSerializable(typeof(PluginAuditResult))]
internal sealed partial class AIOperationsJsonContext : JsonSerializerContext; internal sealed partial class AIOperationsJsonContext : JsonSerializerContext;
@@ -0,0 +1,14 @@
namespace AIStudio.AIOperations.RetrievalContextValidation;
/// <summary>
/// What a model writes when it judges whether a retrieval context helps with a prompt.
/// </summary>
/// <remarks>
/// Every value may be missing from the answer, and a missing value stays null instead of turning into the
/// default of its type. An answer without a decision or a confidence is no usable answer, see
/// RetrievalContextValidationOperation.ReadAnswer.
/// </remarks>
/// <param name="Decision">Whether the retrieval context helps with the prompt.</param>
/// <param name="Reason">Why the model decided so.</param>
/// <param name="Confidence">The probability that the decision is right, between 0 and 1.</param>
public readonly record struct RetrievalContextValidationAnswer(bool? Decision, string? Reason, float? Confidence);
@@ -21,17 +21,21 @@ public sealed class RetrievalContextValidationOperation(ILogger<RetrievalContext
private const string JOB_DESCRIPTION = private const string JOB_DESCRIPTION =
""" """
You receive a system and user prompt as well as a retrieval context as input. Your task is to decide whether this You receive a system and user prompt as well as a retrieval context as input. Your task is to decide whether this
retrieval context is helpful in processing the prompts or not. You respond with the decision (true or false), retrieval context is helpful in processing the prompts or not. You respond with the decision, your reasoning,
your reasoning, and your confidence in this decision. and your confidence in this decision.
Your decision is true when the retrieval context helps in processing the prompts, and false when it does not.
Your response is only one JSON object in the following format: Your response is only one JSON object in the following format:
``` ```
{"decision": true, "reason": "Why did you choose this source?", "confidence": 0.87} {"decision": true, "reason": "Why does this retrieval context help or not?", "confidence": 0.87}
``` ```
You express your confidence as a floating-point number between 0.0 (maximum uncertainty) and Your confidence is the probability that your decision is right, as a floating-point number between 0.0 and
1.0 (you are absolutely certain that this retrieval context is needed). 1.0: 0.5 means that your decision is no better than a guess, and 1.0 means that you are absolutely certain
of it. This holds for both decisions: when you are certain that the retrieval context does not help, your
decision is false and your confidence is 1.0.
The JSON schema is: The JSON schema is:
@@ -47,7 +51,9 @@ public sealed class RetrievalContextValidationOperation(ILogger<RetrievalContext
"type": "string" "type": "string"
}, },
"confidence": { "confidence": {
"type": "number" "type": "number",
"minimum": 0,
"maximum": 1
} }
}, },
"required": [ "required": [
@@ -112,7 +118,7 @@ public sealed class RetrievalContextValidationOperation(ILogger<RetrievalContext
if (string.IsNullOrWhiteSpace(lastPromptContent)) if (string.IsNullOrWhiteSpace(lastPromptContent))
{ {
this.Logger.LogWarning("The last prompt is empty. The AI cannot validate the retrieval contexts."); this.Logger.LogWarning("The last prompt is empty. The AI cannot validate the retrieval contexts.");
return request.RetrievalContexts.Select(retrievalContext => new RetrievalContextValidationResult(false, "The last prompt was empty.", 1.0f, retrievalContext)).ToList(); return request.RetrievalContexts.Select(retrievalContext => RetrievalContextValidationResult.NotAnswered(retrievalContext, "The last prompt was empty.")).ToList();
} }
var settings = this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation; var settings = this.SettingsManager.ConfigurationData.AgentRetrievalContextValidation;
@@ -172,7 +178,7 @@ public sealed class RetrievalContextValidationOperation(ILogger<RetrievalContext
// too long: // too long:
// //
if (token.IsCancellationRequested) if (token.IsCancellationRequested)
return new(false, "The validation was canceled.", 1.0f, retrievalContext); return RetrievalContextValidationResult.NotAnswered(retrievalContext, "The validation was canceled.");
// //
// The model reads the passage exactly as the chat model would, filtered once for both, // The model reads the passage exactly as the chat model would, filtered once for both,
@@ -200,27 +206,53 @@ public sealed class RetrievalContextValidationOperation(ILogger<RetrievalContext
var answer = await this.AskAsync(request, context, systemPrompt, userPrompt, token); var answer = await this.AskAsync(request, context, systemPrompt, userPrompt, token);
if (answer is null) if (answer is null)
return new(false, "The AI did not return a response.", 1.0f, retrievalContext); {
this.Logger.LogWarning("The AI did not return a response to the validation of a retrieval context.");
return RetrievalContextValidationResult.NotAnswered(retrievalContext, "The AI did not return a response.");
}
// var result = ReadAnswer(answer, retrievalContext);
// We know how bad models may be at writing JSON without surrounding text, so we expect if (!result.IsAnswered)
// the worst and extract the JSON object from the text: this.Logger.LogWarning($"The AI gave no usable answer to the validation of a retrieval context: {result.Reason}");
//
var json = ModelAnswerJson.ExtractObject(answer); return result;
try
{
var result = JsonSerializer.Deserialize<RetrievalContextValidationResult>(json, AIOperationsJson.OPTIONS);
return result with { RetrievalContext = retrievalContext };
}
catch
{
this.Logger.LogWarning("The AI answered with an invalid or unexpected JSON format.");
return new(false, "The AI answered with an invalid or unexpected JSON format.", 1.0f, retrievalContext);
}
} }
finally finally
{ {
semaphore.Release(); semaphore.Release();
} }
} }
/// <summary>
/// Reads what a model answered about one retrieval context.
/// </summary>
/// <remarks>
/// We know how bad models may be at writing JSON without surrounding text, so we expect the worst and
/// extract the JSON object from the text. The answer counts only when it holds a decision and a confidence
/// between 0 and 1. Anything else is no usable answer, rather than being read as something the model did
/// not say: a missing decision would otherwise become false and drop a passage nobody judged.
/// </remarks>
/// <param name="answer">The whole answer of the model.</param>
/// <param name="retrievalContext">The retrieval context the model judged.</param>
/// <returns>The result, with IsAnswered being false when the answer is not usable.</returns>
internal static RetrievalContextValidationResult ReadAnswer(string answer, PreparedRetrievalContext retrievalContext)
{
RetrievalContextValidationAnswer judgment;
try
{
judgment = JsonSerializer.Deserialize<RetrievalContextValidationAnswer>(ModelAnswerJson.ExtractObject(answer), AIOperationsJson.OPTIONS);
}
catch (JsonException)
{
return RetrievalContextValidationResult.NotAnswered(retrievalContext, "The AI answered with an invalid or unexpected JSON format.");
}
if (judgment.Decision is not { } decision)
return RetrievalContextValidationResult.NotAnswered(retrievalContext, "The AI answered without a decision.");
if (judgment.Confidence is not { } confidence || confidence is not (>= 0f and <= 1f))
return RetrievalContextValidationResult.NotAnswered(retrievalContext, "The AI answered without a confidence between 0 and 1.");
return new(retrievalContext, true, decision, judgment.Reason ?? string.Empty, confidence);
}
} }
@@ -5,8 +5,22 @@ namespace AIStudio.AIOperations.RetrievalContextValidation;
/// <summary> /// <summary>
/// Represents the result of a retrieval context validation. /// Represents the result of a retrieval context validation.
/// </summary> /// </summary>
/// <param name="Decision">Whether the retrieval context is useful or not.</param> /// <remarks>
/// <param name="Reason">The reason for the decision.</param> /// Decision and Confidence mean nothing unless IsAnswered is true: a validation which failed says nothing about
/// <param name="Confidence">The confidence of the decision.</param> /// its retrieval context, neither that it helps nor that it does not.
/// </remarks>
/// <param name="RetrievalContext">The retrieval context that was validated, as it is prepared for the AI.</param> /// <param name="RetrievalContext">The retrieval context that was validated, as it is prepared for the AI.</param>
public readonly record struct RetrievalContextValidationResult(bool Decision, string Reason, float Confidence, PreparedRetrievalContext? RetrievalContext) : IConfidence; /// <param name="IsAnswered">Whether the model gave a usable answer.</param>
/// <param name="Decision">Whether the retrieval context is useful or not.</param>
/// <param name="Reason">The reason for the decision, or why the model gave no usable answer.</param>
/// <param name="Confidence">The probability that the decision is right, between 0 and 1.</param>
public readonly record struct RetrievalContextValidationResult(PreparedRetrievalContext RetrievalContext, bool IsAnswered, bool Decision, string Reason, float Confidence) : IConfidence
{
/// <summary>
/// A validation without a usable answer, e.g., because the model gave none or its JSON was invalid.
/// </summary>
/// <param name="retrievalContext">The retrieval context that was to be validated.</param>
/// <param name="reason">Why there is no usable answer.</param>
/// <returns>The result, with IsAnswered being false.</returns>
public static RetrievalContextValidationResult NotAnswered(PreparedRetrievalContext retrievalContext, string reason) => new(retrievalContext, false, false, reason, 0f);
}
@@ -77,11 +77,19 @@ public sealed class AugmentationOne : IAugmentationProcess
// //
// Now, filter the retrieval contexts to the most relevant ones: // Now, filter the retrieval contexts to the most relevant ones:
// //
var targetWindow = validationResults.DetermineTargetWindow(TargetWindowStrategy.TOP10_BETTER_THAN_GUESSING); var validated = KeepFittingPassages(validationResults);
var threshold = validationResults.GetConfidenceThreshold(targetWindow); usedContexts = validated.Contexts;
LOGGER.LogInformation($"The check of which passages fit kept {validated.Contexts.Count:###,###,###,##0} of {validationResults.Count:###,###,###,##0} retrieved contexts: {validated.NumUnchecked:###,###,###,##0} without a usable judgment, {validated.NumRejected:###,###,###,##0} judged not to fit, {validated.NumBelowThreshold:###,###,###,##0} below the confidence threshold of {validated.Threshold:0.00}.");
// Filter the retrieval contexts: //
usedContexts = validationResults.Where(x => x.RetrievalContext is not null && x.Confidence >= threshold).Select(x => x.RetrievalContext!).ToList(); // The user switched this check on. When it failed for every passage, the answer
// rests on unfiltered passages, just as when the check throws:
//
if (validated.IsUnchecked)
{
LOGGER.LogWarning("Retrieval context validation got no usable answer for any context. Continuing augmentation with all retrieved contexts.");
await WarnThatTheCheckFailedAsync();
}
} }
} }
catch (OperationCanceledException) when (token.IsCancellationRequested) catch (OperationCanceledException) when (token.IsCancellationRequested)
@@ -96,7 +104,7 @@ public sealed class AugmentationOne : IAugmentationProcess
// The user switched this check on. Continuing without it silently would hide // The user switched this check on. Continuing without it silently would hide
// that the answer rests on unfiltered passages: // that the answer rests on unfiltered passages:
// //
await MessageBus.INSTANCE.SendWarning(new(AppIcons.PASSAGE_RELEVANCE_CHECK, TA("The check of which passages fit your question failed. This answer uses all passages that were found."))); await WarnThatTheCheckFailedAsync();
} }
} }
else else
@@ -134,6 +142,35 @@ public sealed class AugmentationOne : IAugmentationProcess
#endregion #endregion
/// <summary>
/// Keeps the passages which the check of which passages fit the user prompt let through.
/// </summary>
/// <remarks>
/// A passage judged not to fit is left out, however confident the judgment. Of the passages judged to fit,
/// those stay whose confidence reaches the threshold, which only they decide. A passage whose check failed
/// stays: the failure says nothing about the passage, neither that it fits nor that it does not. It does not
/// count for the threshold either, so that a failed check moves the line for none of the others.
/// </remarks>
/// <param name="validationResults">The results of the check, one for each passage.</param>
/// <returns>The passages left, in the order of the results, and why the others were left out.</returns>
internal static ValidatedPassages KeepFittingPassages(IReadOnlyList<RetrievalContextValidationResult> validationResults)
{
var numJudged = validationResults.Count(result => result.IsAnswered);
var fitting = validationResults.Where(result => result.IsAnswered && result.Decision).ToList();
//
// Without a passage which fits, there is no threshold to find; asking for one would only log a warning:
//
var threshold = fitting.Count is 0 ? 0f : fitting.GetConfidenceThreshold(fitting.DetermineTargetWindow(TargetWindowStrategy.TOP10_BETTER_THAN_GUESSING));
var contexts = validationResults.Where(result => !result.IsAnswered || (result.Decision && result.Confidence >= threshold)).Select(result => result.RetrievalContext).ToList();
return new(contexts, numJudged, validationResults.Count - numJudged, numJudged - fitting.Count, fitting.Count(result => result.Confidence < threshold), threshold);
}
/// <summary>
/// Tells the user that the check of which passages fit failed, so that the answer uses all passages found.
/// </summary>
private static Task WarnThatTheCheckFailedAsync() => MessageBus.INSTANCE.SendWarning(new(AppIcons.PASSAGE_RELEVANCE_CHECK, TA("The check of which passages fit your question failed. This answer uses all passages that were found.")));
/// <summary> /// <summary>
/// Writes what the model reads along with the user prompt: the passages which fit, and how many did not. /// Writes what the model reads along with the user prompt: the passages which fit, and how many did not.
/// </summary> /// </summary>
@@ -0,0 +1,18 @@
namespace AIStudio.Tools.RAG;
/// <summary>
/// The passages which the check of which passages fit the user prompt left, and why it left out the others.
/// </summary>
/// <param name="Contexts">The passages left, in the order of the results of the check.</param>
/// <param name="NumJudged">How many passages the check judged, i.e., got a usable answer for.</param>
/// <param name="NumUnchecked">How many passages stayed without a judgment, because their check failed.</param>
/// <param name="NumRejected">How many passages were left out, because the check judged them not to fit.</param>
/// <param name="NumBelowThreshold">How many passages judged to fit were left out, because their confidence fell below the threshold.</param>
/// <param name="Threshold">The confidence a passage judged to fit needed to stay.</param>
public sealed record ValidatedPassages(IReadOnlyList<PreparedRetrievalContext> Contexts, int NumJudged, int NumUnchecked, int NumRejected, int NumBelowThreshold, float Threshold)
{
/// <summary>
/// Whether the check failed for every passage, so that it judged none of them.
/// </summary>
public bool IsUnchecked => this.NumUnchecked > 0 && this.NumJudged is 0;
}
@@ -34,3 +34,4 @@
- Fixed the fonts of AI Studio, which were missing from all released versions. Your computer used fonts of its own instead; now, texts and code appear in the fonts we chose for AI Studio. - Fixed the fonts of AI Studio, which were missing from all released versions. Your computer used fonts of its own instead; now, texts and code appear in the fonts we chose for AI Studio.
- Fixed the settings of the security audit for assistant plugins, which you could change even when your organization had locked them through a configuration plugin. They now show the lock, like all other settings your organization manages. - Fixed the settings of the security audit for assistant plugins, which you could change even when your organization had locked them through a configuration plugin. They now show the lock, like all other settings your organization manages.
- Fixed the automatic security audit of assistant plugins when no model was set for it: you got two error messages for each plugin, again whenever you opened the assistants or plugins page. Now AI Studio tells you once, and the settings of the security audit show a warning. - Fixed the automatic security audit of assistant plugins when no model was set for it: you got two error messages for each plugin, again whenever you opened the assistants or plugins page. Now AI Studio tells you once, and the settings of the security audit show a warning.
- Fixed the AI-based data validation of classic RAG, which kept passages that the AI had judged as not fitting your question. Now the AI only gets the passages that fit. When the check fails for a passage, AI Studio keeps it, and when it fails for all of them, AI Studio tells you.
@@ -0,0 +1,115 @@
using AIStudio.AIOperations;
using AIStudio.AIOperations.RetrievalContextValidation;
using AIStudio.Chat;
using AIStudio.Provider;
using AIStudio.Settings;
using AIStudio.Tools.RAG;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.AIOperations;
/// <summary>
/// Checks how the validation of retrieval contexts reads what a model answered about a passage.
/// </summary>
/// <remarks>
/// A failed validation once stood for a decision with a confidence of 1.0, so the passage always stayed and
/// moved the threshold of all others. An answer without a usable judgment now says so with IsAnswered,
/// and nothing the model left out is read as a value it never wrote.
/// </remarks>
[TestFixture]
public sealed class RetrievalContextValidationAnswerTests
{
private static readonly PreparedRetrievalContext PASSAGE = new(new RetrievalTextContext
{
DataSourceName = "Handbook",
Category = RetrievalContentCategory.TEXT,
Type = RetrievalContentType.TEXT_DOCUMENT,
Path = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "handbook.pdf")),
MatchedText = "The handbook explains the travel expenses.",
}, "body", [], null);
[TestCase("""{"decision": true, "reason": "It answers the question.", "confidence": 0.87}""", true, 0.87f)]
[TestCase("""{"decision": false, "reason": "It is about something else.", "confidence": 0.9}""", false, 0.9f)]
[TestCase("""{"decision": true, "reason": "Certain.", "confidence": 1}""", true, 1f)]
[TestCase("""{"decision": false, "reason": "A pure guess.", "confidence": 0}""", false, 0f)]
public void AJudgmentIsReadAsTheModelWroteIt(string answer, bool decision, float confidence)
{
var result = RetrievalContextValidationOperation.ReadAnswer(answer, PASSAGE);
Assert.Multiple(() =>
{
Assert.That(result.IsAnswered, Is.True);
Assert.That(result.Decision, Is.EqualTo(decision));
Assert.That(result.Confidence, Is.EqualTo(confidence));
Assert.That(result.RetrievalContext, Is.SameAs(PASSAGE), "The classic RAG process finds the passages it keeps by reference.");
});
}
[Test]
public void TheJudgmentIsFoundAmidProseAndACodeFence()
{
const string ANSWER = """
Here is my judgment:
```json
{"decision": true, "reason": "It names the limit for hotels.", "confidence": 0.75}
```
""";
var result = RetrievalContextValidationOperation.ReadAnswer(ANSWER, PASSAGE);
Assert.Multiple(() =>
{
Assert.That(result.IsAnswered, Is.True);
Assert.That(result.Reason, Is.EqualTo("It names the limit for hotels."));
});
}
[Test]
public void AJudgmentWithoutAReasonStillCounts()
{
var result = RetrievalContextValidationOperation.ReadAnswer("""{"decision": true, "confidence": 0.8}""", PASSAGE);
Assert.Multiple(() =>
{
Assert.That(result.IsAnswered, Is.True, "The reason only explains the judgment; the judgment stands without it.");
Assert.That(result.Reason, Is.Empty);
});
}
[TestCase("""{"reason": "It answers the question.", "confidence": 0.87}""", TestName = "Without a decision")]
[TestCase("""{"decision": true, "reason": "It answers the question."}""", TestName = "Without a confidence")]
[TestCase("""{"decision": true, "reason": "In percent.", "confidence": 87}""", TestName = "With a confidence above 1")]
[TestCase("""{"decision": true, "reason": "Negative.", "confidence": -0.1}""", TestName = "With a confidence below 0")]
[TestCase("""{"decision": "yes", "reason": "A word instead of a value.", "confidence": 0.8}""", TestName = "With a decision which is no boolean")]
[TestCase("""{"decision": true, "reason": "Broken off""", TestName = "With JSON which breaks off")]
[TestCase("I think this passage helps a lot.", TestName = "Without any JSON")]
[TestCase("", TestName = "With an empty answer")]
public void AnAnswerWithoutAUsableJudgmentIsNotAnswered(string answer)
{
var result = RetrievalContextValidationOperation.ReadAnswer(answer, PASSAGE);
Assert.Multiple(() =>
{
Assert.That(result.IsAnswered, Is.False, "Reading a value the model never wrote, e.g., false for a missing decision, would drop a passage nobody judged.");
Assert.That(result.RetrievalContext, Is.SameAs(PASSAGE));
Assert.That(result.Reason, Is.Not.Empty, "The log says why the answer was of no use.");
});
}
[Test]
public async Task AnEmptyPromptLeavesEveryPassageUnjudged()
{
var operation = new RetrievalContextValidationOperation(NullLogger<RetrievalContextValidationOperation>.Instance, new SettingsManager(NullLogger<SettingsManager>.Instance, null!));
var request = new RetrievalContextValidationRequest("You are a helpful assistant.", new ContentText { Text = " " }, [PASSAGE, PASSAGE], ConfidenceLevel.NONE);
var results = await operation.RunAsync(request, new AIOperationContext(AIStudio.Settings.Provider.NONE));
Assert.Multiple(() =>
{
Assert.That(results, Has.Count.EqualTo(2));
Assert.That(results.Select(result => result.IsAnswered), Is.All.False, "Nobody asked the model, so nothing was judged.");
});
}
}
@@ -25,7 +25,7 @@ public static partial class JsonTestRoots
// The AI operations, which select data sources, check retrieved passages, and audit assistant plugins: // 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(List<SelectedDataSource>), AIOperationsJson.OPTIONS));
yield return Case(new(typeof(RetrievalContextValidationResult), AIOperationsJson.OPTIONS)); yield return Case(new(typeof(RetrievalContextValidationAnswer), AIOperationsJson.OPTIONS));
yield return Case(new(typeof(PluginAuditResult), AIOperationsJson.OPTIONS)); yield return Case(new(typeof(PluginAuditResult), AIOperationsJson.OPTIONS));
// The Assistant Builder, for assistant plugins and for direct chat launchers: // The Assistant Builder, for assistant plugins and for direct chat launchers:
@@ -0,0 +1,187 @@
using AIStudio.AIOperations.RetrievalContextValidation;
using AIStudio.Tools.RAG;
using AIStudio.Tools.RAG.AugmentationProcesses;
namespace AIStudio.Tests.Tools;
/// <summary>
/// Checks which passages the classic RAG process keeps after a model checked which of them fit the user prompt.
/// </summary>
/// <remarks>
/// A passage whose check failed once counted as judged with a confidence of 1.0: it always stayed and moved
/// the threshold of all the passages which were judged. The check of a passage may fail for many reasons,
/// e.g., an answer with broken JSON, and none of them says anything about the passage.<br/><br/>
/// The decision of the model was once ignored as well: only the confidence counted, so a passage judged not to
/// fit with a confidence of 0.9 stayed, and took the room of a passage which fits.
/// </remarks>
[TestFixture]
public sealed class ClassicRagValidationTests
{
[Test]
public void NothingToKeepIsNoFailedCheck()
{
var validated = AugmentationOne.KeepFittingPassages([]);
Assert.Multiple(() =>
{
Assert.That(validated.Contexts, Is.Empty);
Assert.That(validated.IsUnchecked, Is.False, "Without a passage, no check failed, and the user needs no warning.");
});
}
[Test]
public void WhenEveryCheckFailsEveryPassageStays()
{
var passages = Passages(4);
var validated = AugmentationOne.KeepFittingPassages(passages.Select(Failed).ToList());
Assert.Multiple(() =>
{
Assert.That(validated.Contexts, Is.EqualTo(passages), "A failed check says nothing about its passage, so the passage stays.");
Assert.That(validated.NumUnchecked, Is.EqualTo(4));
Assert.That(validated.IsUnchecked, Is.True, "The user switched the check on and hears that it failed for every passage.");
});
}
[Test]
public void FailedChecksDoNotMoveTheThresholdOfTheJudgedPassages()
{
//
// Eight passages fit with little confidence, and two checks failed. When the failed checks counted as
// judged with 1.0, only those two passages were better than guessing and set the threshold to 0.5: all
// eight judged passages fell out, and only the two which nobody judged were left.
//
var judged = Passages(8);
var failed = Passages(2);
var results = judged.Select(passage => Fits(passage, 0.3f)).Concat(failed.Select(Failed)).ToList();
var validated = AugmentationOne.KeepFittingPassages(results);
Assert.Multiple(() =>
{
Assert.That(validated.Contexts, Is.EqualTo(judged.Concat(failed)), "The judged passages are all alike, so none of them is worse than another.");
Assert.That(validated.NumJudged, Is.EqualTo(8));
Assert.That(validated.NumUnchecked, Is.EqualTo(2));
Assert.That(validated.IsUnchecked, Is.False);
});
}
[Test]
public void WeakPassagesFallBelowTheThresholdWhileUncheckedOnesStay()
{
var passages = Passages(6);
List<RetrievalContextValidationResult> results =
[
Fits(passages[0], 0.2f),
Fits(passages[1], 0.3f),
Fits(passages[2], 0.9f),
Failed(passages[3]),
Fits(passages[4], 0.95f),
Fits(passages[5], 1.0f),
];
var validated = AugmentationOne.KeepFittingPassages(results);
Assert.Multiple(() =>
{
Assert.That(validated.Contexts, Is.EqualTo(new[] { passages[2], passages[3], passages[4], passages[5] }), "The three strong passages stay, and so does the unchecked one, in the order of the results.");
Assert.That(validated.NumBelowThreshold, Is.EqualTo(2));
Assert.That(validated.Threshold, Is.EqualTo(0.5f).Within(0.001f));
});
}
[Test]
public void APassageJudgedNotToFitIsLeftOutHoweverConfident()
{
var passages = Passages(3);
var validated = AugmentationOne.KeepFittingPassages([NotFitting(passages[0], 0.95f), Fits(passages[1], 0.6f), Fits(passages[2], 0.7f)]);
Assert.Multiple(() =>
{
Assert.That(validated.Contexts, Is.EqualTo(new[] { passages[1], passages[2] }), "The confidence says how sure the model is of its decision, not how well the passage fits.");
Assert.That(validated.NumRejected, Is.EqualTo(1));
});
}
[Test]
public void WhenEveryPassageIsJudgedNotToFitNoneStays()
{
var passages = Passages(10);
var validated = AugmentationOne.KeepFittingPassages(passages.Select(passage => NotFitting(passage, 0.9f)).ToList());
Assert.Multiple(() =>
{
Assert.That(validated.Contexts, Is.Empty, "The model answers as when the search found nothing.");
Assert.That(validated.NumRejected, Is.EqualTo(10));
Assert.That(validated.IsUnchecked, Is.False, "Every check worked, so the user needs no warning.");
});
}
[Test]
public void PassagesJudgedNotToFitDoNotMoveTheThresholdOfTheFittingOnes()
{
//
// Eight passages fit with little confidence, and two do not fit with much. When only the confidence
// counted, the two were the only ones better than guessing and set the threshold to 0.5: the eight which
// fit fell out, and only the two which do not fit were left.
//
var fitting = Passages(8);
var notFitting = Passages(2);
var results = fitting.Select(passage => Fits(passage, 0.3f)).Concat(notFitting.Select(passage => NotFitting(passage, 0.9f))).ToList();
var validated = AugmentationOne.KeepFittingPassages(results);
Assert.Multiple(() =>
{
Assert.That(validated.Contexts, Is.EqualTo(fitting));
Assert.That(validated.NumRejected, Is.EqualTo(2));
Assert.That(validated.NumBelowThreshold, Is.Zero);
});
}
[Test]
public void AMixOfJudgmentsAndFailedChecksKeepsTheStrongFittingAndTheUncheckedPassages()
{
var passages = Passages(7);
List<RetrievalContextValidationResult> results =
[
Fits(passages[0], 0.2f),
NotFitting(passages[1], 0.9f),
Fits(passages[2], 0.9f),
Failed(passages[3]),
Fits(passages[4], 0.95f),
NotFitting(passages[5], 0.6f),
Fits(passages[6], 1.0f),
];
var validated = AugmentationOne.KeepFittingPassages(results);
Assert.Multiple(() =>
{
Assert.That(validated.Contexts, Is.EqualTo(new[] { passages[2], passages[3], passages[4], passages[6] }));
Assert.That(validated.NumJudged, Is.EqualTo(6));
Assert.That(validated.NumUnchecked, Is.EqualTo(1));
Assert.That(validated.NumRejected, Is.EqualTo(2));
Assert.That(validated.NumBelowThreshold, Is.EqualTo(1));
Assert.That(validated.IsUnchecked, Is.False);
});
}
/// <summary>
/// Passages which differ from each other, so that a test can tell which of them were left.
/// </summary>
private static List<PreparedRetrievalContext> Passages(int count) => Enumerable.Range(1, count).Select(number => new PreparedRetrievalContext(new RetrievalTextContext
{
DataSourceName = "Handbook",
Category = RetrievalContentCategory.TEXT,
Type = RetrievalContentType.TEXT_DOCUMENT,
Path = Path.GetFullPath(Path.Combine(Path.GetTempPath(), $"handbook-{number}.pdf")),
MatchedText = $"Passage {number} of the handbook.",
}, $"body {number}", [], null)).ToList();
private static RetrievalContextValidationResult Fits(PreparedRetrievalContext passage, float confidence) => new(passage, true, true, "It fits.", confidence);
private static RetrievalContextValidationResult NotFitting(PreparedRetrievalContext passage, float confidence) => new(passage, true, false, "It is about something else.", confidence);
private static RetrievalContextValidationResult Failed(PreparedRetrievalContext passage) => RetrievalContextValidationResult.NotAnswered(passage, "The AI did not return a response.");
}