mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-10-09 13:49:40 +00:00
Describe the data sources Semantic Search may search
This commit is contained in:
3 files changed
+253
-8
No files matched your search
+143
-6
@@ -1,7 +1,13 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
using AIStudio.Chat;
|
||||
using AIStudio.Provider;
|
||||
using AIStudio.Settings;
|
||||
using AIStudio.Settings.DataModel;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
using AIStudio.Tools.RAG;
|
||||
using AIStudio.Tools.Services;
|
||||
|
||||
namespace AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.SemanticSearch;
|
||||
|
||||
@@ -22,7 +28,7 @@ namespace AIStudio.Tools.ToolCallingSystem.ToolCallingImplementations.SemanticSe
|
||||
/// required confidence and data security to what the data sources searched ask for, so their
|
||||
/// passages never reach a less trusted provider later on.
|
||||
/// </remarks>
|
||||
public sealed class SemanticSearchTool : IToolImplementation
|
||||
public sealed class SemanticSearchTool(SettingsManager settingsManager, DataSourceService dataSourceService, DataSourceDescriptionService descriptionService) : IToolImplementation
|
||||
{
|
||||
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(SemanticSearchTool).Namespace, nameof(SemanticSearchTool));
|
||||
|
||||
@@ -35,6 +41,16 @@ public sealed class SemanticSearchTool : IToolImplementation
|
||||
/// </summary>
|
||||
private const string DESCRIPTION = "Search the user's own data sources, such as their documents or the document collections of their organization, for passages matching a query. Each data source searches in its own way, usually by meaning and by keywords. Returns the best matching passages of each data source searched as Markdown, together with where they come from, and tells for each data source whether a further page holds more results.";
|
||||
|
||||
/// <summary>
|
||||
/// How much of the description of a data source the model reads.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The server of an ERI data source writes its description, and nothing keeps it short. The
|
||||
/// tool describes every data source it offers with every request, so a long one would cost its
|
||||
/// length over and over again. A few sentences say what a data source holds.
|
||||
/// </remarks>
|
||||
private const int MAX_DESCRIPTION_CHARACTERS = 500;
|
||||
|
||||
public string ImplementationKey => ToolSelectionRules.SEMANTIC_SEARCH_TOOL_ID;
|
||||
|
||||
public ToolDefinition GetDefinition() => new()
|
||||
@@ -71,14 +87,135 @@ public sealed class SemanticSearchTool : IToolImplementation
|
||||
{
|
||||
Name = ToolSelectionRules.SEMANTIC_SEARCH_TOOL_ID,
|
||||
DescriptionForLLM = DESCRIPTION,
|
||||
Parameters = ToolParameterSchemaBuilder.Create()
|
||||
.RequiredString(QUERY_ARGUMENT, "What to search for: a self-contained question, statement, or a few keywords, naming the subject instead of referring to earlier messages.")
|
||||
.OptionalStringArray(DATA_SOURCE_IDS_ARGUMENT, "Optional IDs of the data sources to search, out of those listed in the description of this tool. Leave it out to search all of them.")
|
||||
.OptionalInteger(PAGE_ARGUMENT, "Optional page of results, starting at 1. A page after the first needs exactly one data source in data_source_ids. Later pages are less relevant, so rephrase the query before you turn pages.")
|
||||
.Build(),
|
||||
Parameters = BuildParameters(),
|
||||
},
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Describes the data sources this provider may search in this chat, and offers exactly those.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Without a data source to offer, the tool stays out of the request: the model should not
|
||||
/// learn about a search which can only come back empty.<br/><br/>
|
||||
/// The descriptions of ERI data sources are asked from their servers and kept for a few
|
||||
/// minutes, so that asking for every request costs no more than the check of the data sources
|
||||
/// the classic RAG process makes with every message, too.
|
||||
/// </remarks>
|
||||
public async ValueTask<ToolFunctionDefinition?> ResolveFunctionAsync(ToolDefinition definition, ToolResolutionContext context, CancellationToken token = default)
|
||||
{
|
||||
var dataSources = await this.GetOfferedDataSourcesAsync(context.Provider, context.ChatThread);
|
||||
if (dataSources.Count == 0)
|
||||
return null;
|
||||
|
||||
var descriptions = await Task.WhenAll(dataSources.Select(dataSource => descriptionService.GetDescriptionAsync(dataSource, token)));
|
||||
return DescribeDataSources(definition.Function, dataSources.Zip(descriptions).ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The data sources of the chat which the provider may search, in the order they are offered.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// When the AI selects the data sources, it may search every data source the provider may use:
|
||||
/// the AI which selects is the chat model itself, no agent. Otherwise, it may search those the
|
||||
/// user selected, as far as the provider may use them. Only the chat provider counts, since no
|
||||
/// agent takes part, see DataSourceService.GetParticipatingAgents.
|
||||
/// </remarks>
|
||||
private async Task<IReadOnlyList<IDataSource>> GetOfferedDataSourcesAsync(AIStudio.Settings.Provider provider, ChatThread thread)
|
||||
{
|
||||
//
|
||||
// Data sources are a preview feature, and a chat keeps its data source options while the
|
||||
// feature is switched off, cf. AISrcSelWithRetCtxVal:
|
||||
//
|
||||
var options = thread.DataSourceOptions;
|
||||
if (!PreviewFeatures.PRE_RAG_2024.IsEnabled(settingsManager) || !options.IsEnabled())
|
||||
return [];
|
||||
|
||||
var preselectedDataSources = options.PreselectedDataSourceIds
|
||||
.Select(id => settingsManager.ConfigurationData.DataSources.FirstOrDefault(dataSource => dataSource.Id == id))
|
||||
.OfType<IDataSource>()
|
||||
.ToList();
|
||||
|
||||
var dataSources = await dataSourceService.GetDataSources(provider, options, DataSourceRetrievalMode.SEMANTIC_SEARCH, preselectedDataSources);
|
||||
var offeredDataSources = options.AutomaticDataSourceSelection ? dataSources.AllowedDataSources : dataSources.SelectedDataSources;
|
||||
|
||||
// A data source configured to return no matches would only ever come back empty:
|
||||
return InOfferOrder(offeredDataSources.Where(dataSource => dataSource.MaxMatches > 0));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sorts data sources the way the tool offers them: by their number, then by their ID.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The same data sources always come in the same order, however the settings list them or the
|
||||
/// checks return them. The providers cache a request from its beginning, and the tools are part
|
||||
/// of that beginning, see IToolImplementation.ResolveFunctionAsync.
|
||||
/// </remarks>
|
||||
internal static IReadOnlyList<IDataSource> InOfferOrder(IEnumerable<IDataSource> dataSources) => dataSources
|
||||
.OrderBy(dataSource => dataSource.Num)
|
||||
.ThenBy(dataSource => dataSource.Id, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
|
||||
/// <summary>
|
||||
/// Tailors the function to the data sources offered: lists them in its description, and allows
|
||||
/// exactly their IDs.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The model learns the name, the kind, and the description of each data source, and how far it
|
||||
/// can page through it. Where a data source lies stays out: the model has no use for a path.
|
||||
/// What the user describes and what the server of an ERI data source describes both arrive in a
|
||||
/// single line, and the latter already filtered for prompt injections, see
|
||||
/// DataSourceDescriptionService.
|
||||
/// </remarks>
|
||||
/// <param name="function">The function as registered.</param>
|
||||
/// <param name="dataSources">The data sources to offer, in the order to list them, each with its description.</param>
|
||||
/// <returns>The function to offer in this request.</returns>
|
||||
internal static ToolFunctionDefinition DescribeDataSources(ToolFunctionDefinition function, IReadOnlyList<(IDataSource DataSource, string Description)> dataSources)
|
||||
{
|
||||
var description = new StringBuilder(DESCRIPTION);
|
||||
description.AppendLine();
|
||||
description.AppendLine();
|
||||
description.AppendLine($"The data sources you may search, by the ID to pass in {DATA_SOURCE_IDS_ARGUMENT}:");
|
||||
foreach (var (dataSource, dataSourceDescription) in dataSources)
|
||||
{
|
||||
description.Append($"- id={dataSource.Id}, name='{dataSource.Name}', type={GetKind(dataSource)}, results per page={dataSource.MaxMatches}, last page={RetrievalPaging.GetLastPage(dataSource.MaxMatches)}");
|
||||
if (!string.IsNullOrWhiteSpace(dataSourceDescription))
|
||||
description.Append($", description='{Shorten(dataSourceDescription.Trim())}'");
|
||||
|
||||
description.AppendLine();
|
||||
}
|
||||
|
||||
return function with
|
||||
{
|
||||
DescriptionForLLM = description.ToString().TrimEnd(),
|
||||
Parameters = BuildParameters(dataSources.Select(offered => offered.DataSource.Id).ToArray()),
|
||||
};
|
||||
}
|
||||
|
||||
/// <param name="dataSourceIds">The IDs the model may pass, or none while no data sources are known.</param>
|
||||
private static JsonElement BuildParameters(params string[] dataSourceIds) => ToolParameterSchemaBuilder.Create()
|
||||
.RequiredString(QUERY_ARGUMENT, "What to search for: a self-contained question, statement, or a few keywords, naming the subject instead of referring to earlier messages.")
|
||||
.OptionalStringArray(DATA_SOURCE_IDS_ARGUMENT, "Optional IDs of the data sources to search, out of those listed in the description of this tool. Leave it out to search all of them.", dataSourceIds)
|
||||
.OptionalInteger(PAGE_ARGUMENT, "Optional page of results, starting at 1. A page after the first needs exactly one data source in data_source_ids. Later pages are less relevant, so rephrase the query before you turn pages.")
|
||||
.Build();
|
||||
|
||||
private static string GetKind(IDataSource dataSource) => dataSource switch
|
||||
{
|
||||
DataSourceLocalDirectory => "local folder",
|
||||
DataSourceLocalFile => "local file",
|
||||
IERIDataSource => "external data source",
|
||||
_ => "data source",
|
||||
};
|
||||
|
||||
private static string Shorten(string description)
|
||||
{
|
||||
if (description.Length <= MAX_DESCRIPTION_CHARACTERS)
|
||||
return description;
|
||||
|
||||
// Never between the two halves of a surrogate pair, which no JSON writer takes:
|
||||
var end = char.IsHighSurrogate(description[MAX_DESCRIPTION_CHARACTERS - 1]) ? MAX_DESCRIPTION_CHARACTERS - 1 : MAX_DESCRIPTION_CHARACTERS;
|
||||
return $"{description[..end].TrimEnd()}...";
|
||||
}
|
||||
|
||||
public string Icon => Icons.Material.Filled.ManageSearch;
|
||||
|
||||
// An ERI data source is a server somebody else runs, and even a local document may hold text
|
||||
|
||||
Reference in new issue
Block a user