mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-11-23 04:53:48 +00:00
Fixed the retrieval context validation keeping unhelpful passages (#1217)
This commit is contained in:
1 parent
808b95b15d
commit
78f5066bfd
10 files changed
+454
-36
No files matched your search
@@ -11,6 +11,6 @@ namespace AIStudio.AIOperations;
|
||||
/// </summary>
|
||||
[JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata)]
|
||||
[JsonSerializable(typeof(List<SelectedDataSource>))]
|
||||
[JsonSerializable(typeof(RetrievalContextValidationResult))]
|
||||
[JsonSerializable(typeof(RetrievalContextValidationAnswer))]
|
||||
[JsonSerializable(typeof(PluginAuditResult))]
|
||||
internal sealed partial class AIOperationsJsonContext : JsonSerializerContext;
|
||||
+14
@@ -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);
|
||||
+56
-24
@@ -21,17 +21,21 @@ public sealed class RetrievalContextValidationOperation(ILogger<RetrievalContext
|
||||
private const string JOB_DESCRIPTION =
|
||||
"""
|
||||
You receive a system and user prompt as well as a retrieval context as input. Your task is to decide whether this
|
||||
retrieval context is helpful in processing the prompts or not. You respond with the decision (true or false),
|
||||
your reasoning, and your confidence in this decision.
|
||||
retrieval context is helpful in processing the prompts or not. You respond with the decision, your reasoning,
|
||||
and your confidence in this decision.
|
||||
|
||||
Your decision is true when the retrieval context helps in processing the prompts, and false when it does not.
|
||||
|
||||
Your response is only one JSON object in the following format:
|
||||
|
||||
```
|
||||
{"decision": true, "reason": "Why 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
|
||||
1.0 (you are absolutely certain that this retrieval context is needed).
|
||||
Your confidence is the probability that your decision is right, as a floating-point number between 0.0 and
|
||||
1.0: 0.5 means that your decision is no better than a guess, and 1.0 means that you are absolutely certain
|
||||
of it. This holds for both decisions: when you are certain that the retrieval context does not help, your
|
||||
decision is false and your confidence is 1.0.
|
||||
|
||||
The JSON schema is:
|
||||
|
||||
@@ -47,7 +51,9 @@ public sealed class RetrievalContextValidationOperation(ILogger<RetrievalContext
|
||||
"type": "string"
|
||||
},
|
||||
"confidence": {
|
||||
"type": "number"
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -112,7 +118,7 @@ public sealed class RetrievalContextValidationOperation(ILogger<RetrievalContext
|
||||
if (string.IsNullOrWhiteSpace(lastPromptContent))
|
||||
{
|
||||
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;
|
||||
@@ -172,7 +178,7 @@ public sealed class RetrievalContextValidationOperation(ILogger<RetrievalContext
|
||||
// too long:
|
||||
//
|
||||
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,
|
||||
@@ -200,27 +206,53 @@ public sealed class RetrievalContextValidationOperation(ILogger<RetrievalContext
|
||||
|
||||
var answer = await this.AskAsync(request, context, systemPrompt, userPrompt, token);
|
||||
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.");
|
||||
}
|
||||
|
||||
//
|
||||
// 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:
|
||||
//
|
||||
var json = ModelAnswerJson.ExtractObject(answer);
|
||||
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);
|
||||
}
|
||||
var result = ReadAnswer(answer, retrievalContext);
|
||||
if (!result.IsAnswered)
|
||||
this.Logger.LogWarning($"The AI gave no usable answer to the validation of a retrieval context: {result.Reason}");
|
||||
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads what a model answered about one retrieval context.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// We know how bad models may be at writing JSON without surrounding text, so we expect the worst and
|
||||
/// extract the JSON object from the text. The answer counts only when it holds a decision and a confidence
|
||||
/// between 0 and 1. Anything else is no usable answer, rather than being read as something the model did
|
||||
/// not say: a missing decision would otherwise become false and drop a passage nobody judged.
|
||||
/// </remarks>
|
||||
/// <param name="answer">The whole answer of the model.</param>
|
||||
/// <param name="retrievalContext">The retrieval context the model judged.</param>
|
||||
/// <returns>The result, with IsAnswered being false when the answer is not usable.</returns>
|
||||
internal static RetrievalContextValidationResult ReadAnswer(string answer, PreparedRetrievalContext retrievalContext)
|
||||
{
|
||||
RetrievalContextValidationAnswer judgment;
|
||||
try
|
||||
{
|
||||
judgment = JsonSerializer.Deserialize<RetrievalContextValidationAnswer>(ModelAnswerJson.ExtractObject(answer), AIOperationsJson.OPTIONS);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return RetrievalContextValidationResult.NotAnswered(retrievalContext, "The AI answered with an invalid or unexpected JSON format.");
|
||||
}
|
||||
|
||||
if (judgment.Decision is not { } decision)
|
||||
return RetrievalContextValidationResult.NotAnswered(retrievalContext, "The AI answered without a decision.");
|
||||
|
||||
if (judgment.Confidence is not { } confidence || confidence is not (>= 0f and <= 1f))
|
||||
return RetrievalContextValidationResult.NotAnswered(retrievalContext, "The AI answered without a confidence between 0 and 1.");
|
||||
|
||||
return new(retrievalContext, true, decision, judgment.Reason ?? string.Empty, confidence);
|
||||
}
|
||||
}
|
||||
+18
-4
@@ -5,8 +5,22 @@ namespace AIStudio.AIOperations.RetrievalContextValidation;
|
||||
/// <summary>
|
||||
/// Represents the result of a retrieval context validation.
|
||||
/// </summary>
|
||||
/// <param name="Decision">Whether the retrieval context is useful or not.</param>
|
||||
/// <param name="Reason">The reason for the decision.</param>
|
||||
/// <param name="Confidence">The confidence of the decision.</param>
|
||||
/// <remarks>
|
||||
/// Decision and Confidence mean nothing unless IsAnswered is true: a validation which failed says nothing about
|
||||
/// its retrieval context, neither that it helps nor that it does not.
|
||||
/// </remarks>
|
||||
/// <param name="RetrievalContext">The retrieval context that was validated, as it is prepared for the AI.</param>
|
||||
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:
|
||||
//
|
||||
var targetWindow = validationResults.DetermineTargetWindow(TargetWindowStrategy.TOP10_BETTER_THAN_GUESSING);
|
||||
var threshold = validationResults.GetConfidenceThreshold(targetWindow);
|
||||
var validated = KeepFittingPassages(validationResults);
|
||||
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)
|
||||
@@ -96,7 +104,7 @@ public sealed class AugmentationOne : IAugmentationProcess
|
||||
// The user switched this check on. Continuing without it silently would hide
|
||||
// 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
|
||||
@@ -134,6 +142,35 @@ public sealed class AugmentationOne : IAugmentationProcess
|
||||
|
||||
#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>
|
||||
/// Writes what the model reads along with the user prompt: the passages which fit, and how many did not.
|
||||
/// </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;
|
||||
}
|
||||
@@ -33,4 +33,5 @@
|
||||
- Fixed AI Studio claiming that the provider had returned an invalid tool calling response when you stopped an answer while the AI was still thinking and could use tools. The same false message no longer follows a timeout or a lost connection either, which AI Studio reports on its own.
|
||||
- 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 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.
|
||||
Reference in new issue
Block a user