|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Diagnostics.CodeAnalysis; |
| 6 | +using System.Linq; |
| 7 | +using System.Text; |
| 8 | +using System.Text.Json; |
| 9 | +using System.Text.Json.Serialization; |
| 10 | +using System.Threading; |
| 11 | +using System.Threading.Tasks; |
| 12 | +using Microsoft.Extensions.AI; |
| 13 | +using Microsoft.SemanticKernel.Data; |
| 14 | + |
| 15 | +namespace Microsoft.SemanticKernel.Memory; |
| 16 | + |
| 17 | +/// <summary> |
| 18 | +/// A component that does a search based on any messages that the AI model is invoked with and injects the results into the AI model invocation context. |
| 19 | +/// </summary> |
| 20 | +[Experimental("SKEXP0130")] |
| 21 | +public sealed class TextRagComponent : ConversationStatePart |
| 22 | +{ |
| 23 | + private const string DefaultPluginSearchFunctionName = "Search"; |
| 24 | + private const string DefaultPluginSearchFunctionDescription = "Allows searching for additional information to help answer the user question."; |
| 25 | + private const string DefaultContextPrompt = "Consider the following information when responding to the user:"; |
| 26 | + private const string DefaultIncludeCitationsPrompt = "Include citations to the relevant information where it is referenced in the response."; |
| 27 | + |
| 28 | + private readonly ITextSearch _textSearch; |
| 29 | + |
| 30 | + private readonly AIFunction[] _aIFunctions; |
| 31 | + |
| 32 | + /// <summary> |
| 33 | + /// Initializes a new instance of the <see cref="TextRagComponent"/> class. |
| 34 | + /// </summary> |
| 35 | + /// <param name="textSearch">The text search component to retrieve results from.</param> |
| 36 | + /// <param name="options">Options that configure the behavior of the component.</param> |
| 37 | + /// <exception cref="ArgumentNullException"></exception> |
| 38 | + public TextRagComponent(ITextSearch textSearch, TextRagComponentOptions? options = default) |
| 39 | + { |
| 40 | + Verify.NotNull(textSearch); |
| 41 | + |
| 42 | + this._textSearch = textSearch; |
| 43 | + this.Options = options ?? new(); |
| 44 | + |
| 45 | + this._aIFunctions = |
| 46 | + [ |
| 47 | + AIFunctionFactory.Create( |
| 48 | + this.SearchAsync, |
| 49 | + name: this.Options.PluginFunctionName ?? DefaultPluginSearchFunctionName, |
| 50 | + description: this.Options.PluginFunctionDescription ?? DefaultPluginSearchFunctionDescription) |
| 51 | + ]; |
| 52 | + } |
| 53 | + |
| 54 | + /// <summary> |
| 55 | + /// Gets the options that have been configured for this component. |
| 56 | + /// </summary> |
| 57 | + public TextRagComponentOptions Options { get; } |
| 58 | + |
| 59 | + /// <inheritdoc/> |
| 60 | + public override IReadOnlyCollection<AIFunction> AIFunctions |
| 61 | + { |
| 62 | + get |
| 63 | + { |
| 64 | + if (this.Options.SearchTime != TextRagComponentOptions.RagBehavior.ViaPlugin) |
| 65 | + { |
| 66 | + return Array.Empty<AIFunction>(); |
| 67 | + } |
| 68 | + |
| 69 | + return this._aIFunctions; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + /// <inheritdoc/> |
| 74 | + public override async Task<string> OnModelInvokeAsync(ICollection<ChatMessage> newMessages, CancellationToken cancellationToken = default) |
| 75 | + { |
| 76 | + if (this.Options.SearchTime != TextRagComponentOptions.RagBehavior.BeforeAIInvoke) |
| 77 | + { |
| 78 | + return string.Empty; |
| 79 | + } |
| 80 | + |
| 81 | + Verify.NotNull(newMessages); |
| 82 | + |
| 83 | + string input = string.Join("\n", newMessages.Where(m => m is not null).Select(m => m.Text)); |
| 84 | + |
| 85 | + var searchResults = await this._textSearch.GetTextSearchResultsAsync( |
| 86 | + input, |
| 87 | + new() { Top = this.Options.Top }, |
| 88 | + cancellationToken: cancellationToken).ConfigureAwait(false); |
| 89 | + |
| 90 | + var results = await searchResults.Results.ToListAsync(cancellationToken).ConfigureAwait(false); |
| 91 | + |
| 92 | + return this.FormatResults(results); |
| 93 | + } |
| 94 | + |
| 95 | + /// <summary> |
| 96 | + /// Plugin method to search the database on demand. |
| 97 | + /// </summary> |
| 98 | + [KernelFunction] |
| 99 | + internal async Task<string> SearchAsync(string userQuestion, CancellationToken cancellationToken = default) |
| 100 | + { |
| 101 | + var searchResults = await this._textSearch.GetTextSearchResultsAsync( |
| 102 | + userQuestion, |
| 103 | + new() { Top = this.Options.Top }, |
| 104 | + cancellationToken: cancellationToken).ConfigureAwait(false); |
| 105 | + |
| 106 | + var results = await searchResults.Results.ToListAsync(cancellationToken).ConfigureAwait(false); |
| 107 | + |
| 108 | + return this.FormatResults(results); |
| 109 | + } |
| 110 | + |
| 111 | + /// <summary> |
| 112 | + /// Format the results showing the content with source link and name for each result. |
| 113 | + /// </summary> |
| 114 | + /// <param name="results">The results to format.</param> |
| 115 | + /// <returns>The formatted results.</returns> |
| 116 | + private string FormatResults(List<TextSearchResult> results) |
| 117 | + { |
| 118 | + if (this.Options.ContextFormatter is not null) |
| 119 | + { |
| 120 | + return this.Options.ContextFormatter(results); |
| 121 | + } |
| 122 | + |
| 123 | + if (results.Count == 0) |
| 124 | + { |
| 125 | + return string.Empty; |
| 126 | + } |
| 127 | + |
| 128 | + var sb = new StringBuilder(); |
| 129 | + sb.AppendLine(this.Options.ContextPrompt ?? DefaultContextPrompt); |
| 130 | + for (int i = 0; i < results.Count; i++) |
| 131 | + { |
| 132 | + var result = results[i]; |
| 133 | + sb.AppendLine($"Item {i + 1}:"); |
| 134 | + sb.AppendLine($"Name: {result.Name}"); |
| 135 | + sb.AppendLine($"Link: {result.Link}"); |
| 136 | + sb.AppendLine($"Contents: {result.Value}"); |
| 137 | + } |
| 138 | + sb.AppendLine(this.Options.IncludeCitationsPrompt ?? DefaultIncludeCitationsPrompt); |
| 139 | + sb.AppendLine(); |
| 140 | + return sb.ToString(); |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +[JsonSourceGenerationOptions(JsonSerializerDefaults.General, |
| 145 | + UseStringEnumConverter = false, |
| 146 | + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, |
| 147 | + WriteIndented = false)] |
| 148 | +[JsonSerializable(typeof(List<TextSearchResult>))] |
| 149 | +internal partial class TextRagSourceGenerationContext : JsonSerializerContext |
| 150 | +{ |
| 151 | +} |
0 commit comments