|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Frozen; |
| 6 | +using System.Collections.Generic; |
| 7 | +using System.Runtime.CompilerServices; |
| 8 | +using System.Text; |
| 9 | +using System.Threading; |
| 10 | +using System.Threading.Tasks; |
| 11 | +using Microsoft.Extensions.AI; |
| 12 | +using Microsoft.Shared.Diagnostics; |
| 13 | + |
| 14 | +namespace Microsoft.Extensions.DataIngestion; |
| 15 | + |
| 16 | +/// <summary> |
| 17 | +/// Enriches chunks with keyword extraction using an AI chat model. |
| 18 | +/// </summary> |
| 19 | +/// <remarks> |
| 20 | +/// It adds "keywords" metadata to each chunk. It's an array of strings representing the extracted keywords. |
| 21 | +/// </remarks> |
| 22 | +public sealed class KeywordEnricher : IngestionChunkProcessor<string> |
| 23 | +{ |
| 24 | + private const int DefaultMaxKeywords = 5; |
| 25 | +#if NET |
| 26 | + private static readonly System.Buffers.SearchValues<char> _illegalCharacters = System.Buffers.SearchValues.Create([';', ',']); |
| 27 | +#else |
| 28 | + private static readonly char[] _illegalCharacters = [';', ',']; |
| 29 | +#endif |
| 30 | + private readonly IChatClient _chatClient; |
| 31 | + private readonly ChatOptions? _chatOptions; |
| 32 | + private readonly FrozenSet<string>? _predefinedKeywords; |
| 33 | + private readonly ChatMessage _systemPrompt; |
| 34 | + |
| 35 | + /// <summary> |
| 36 | + /// Initializes a new instance of the <see cref="KeywordEnricher"/> class. |
| 37 | + /// </summary> |
| 38 | + /// <param name="chatClient">The chat client used for keyword extraction.</param> |
| 39 | + /// <param name="predefinedKeywords">The set of predefined keywords for extraction.</param> |
| 40 | + /// <param name="chatOptions">Options for the chat client.</param> |
| 41 | + /// <param name="maxKeywords">The maximum number of keywords to extract. When not provided, it defaults to 5.</param> |
| 42 | + /// <param name="confidenceThreshold">The confidence threshold for keyword inclusion. When not provided, it defaults to 0.7.</param> |
| 43 | + /// <remarks> |
| 44 | + /// If no predefined keywords are provided, the model will extract keywords based on the content alone. |
| 45 | + /// Such results may vary more significantly between different AI models. |
| 46 | + /// </remarks> |
| 47 | + public KeywordEnricher(IChatClient chatClient, ReadOnlySpan<string> predefinedKeywords, |
| 48 | + ChatOptions? chatOptions = null, int? maxKeywords = null, double? confidenceThreshold = null) |
| 49 | + { |
| 50 | + _chatClient = Throw.IfNull(chatClient); |
| 51 | + _chatOptions = chatOptions; |
| 52 | + _predefinedKeywords = CreatePredfinedKeywords(predefinedKeywords); |
| 53 | + |
| 54 | + double threshold = confidenceThreshold.HasValue |
| 55 | + ? Throw.IfOutOfRange(confidenceThreshold.Value, 0.0, 1.0, nameof(confidenceThreshold)) |
| 56 | + : 0.7; |
| 57 | + int keywordsCount = maxKeywords.HasValue |
| 58 | + ? Throw.IfLessThanOrEqual(maxKeywords.Value, 0, nameof(maxKeywords)) |
| 59 | + : DefaultMaxKeywords; |
| 60 | + _systemPrompt = CreateSystemPrompt(keywordsCount, predefinedKeywords, threshold); |
| 61 | + } |
| 62 | + |
| 63 | + /// <summary> |
| 64 | + /// Gets the metadata key used to store the keywords. |
| 65 | + /// </summary> |
| 66 | + public static string MetadataKey => "keywords"; |
| 67 | + |
| 68 | + /// <inheritdoc/> |
| 69 | + public override async IAsyncEnumerable<IngestionChunk<string>> ProcessAsync(IAsyncEnumerable<IngestionChunk<string>> chunks, |
| 70 | + [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| 71 | + { |
| 72 | + _ = Throw.IfNull(chunks); |
| 73 | + |
| 74 | + await foreach (IngestionChunk<string> chunk in chunks.WithCancellation(cancellationToken)) |
| 75 | + { |
| 76 | + // Structured response is not used here because it's not part of Microsoft.Extensions.AI.Abstractions. |
| 77 | + var response = await _chatClient.GetResponseAsync( |
| 78 | + [ |
| 79 | + _systemPrompt, |
| 80 | + new(ChatRole.User, chunk.Content) |
| 81 | + ], _chatOptions, cancellationToken: cancellationToken).ConfigureAwait(false); |
| 82 | + |
| 83 | +#pragma warning disable EA0009 // Use 'System.MemoryExtensions.Split' for improved performance |
| 84 | + string[] keywords = response.Text.Split(';'); |
| 85 | + if (_predefinedKeywords is not null) |
| 86 | + { |
| 87 | + foreach (var keyword in keywords) |
| 88 | + { |
| 89 | + if (!_predefinedKeywords.Contains(keyword)) |
| 90 | + { |
| 91 | + throw new InvalidOperationException($"The extracted keyword '{keyword}' is not in the predefined keywords list."); |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + chunk.Metadata[MetadataKey] = keywords; |
| 97 | + |
| 98 | + yield return chunk; |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + private static FrozenSet<string>? CreatePredfinedKeywords(ReadOnlySpan<string> predefinedKeywords) |
| 103 | + { |
| 104 | + if (predefinedKeywords.Length == 0) |
| 105 | + { |
| 106 | + return null; |
| 107 | + } |
| 108 | + |
| 109 | + HashSet<string> result = new(StringComparer.Ordinal); |
| 110 | + foreach (string keyword in predefinedKeywords) |
| 111 | + { |
| 112 | +#if NET |
| 113 | + if (keyword.AsSpan().ContainsAny(_illegalCharacters)) |
| 114 | +#else |
| 115 | + if (keyword.IndexOfAny(_illegalCharacters) >= 0) |
| 116 | +#endif |
| 117 | + { |
| 118 | + Throw.ArgumentException(nameof(predefinedKeywords), $"Predefined keyword '{keyword}' contains an invalid character (';' or ',')."); |
| 119 | + } |
| 120 | + |
| 121 | + if (!result.Add(keyword)) |
| 122 | + { |
| 123 | + Throw.ArgumentException(nameof(predefinedKeywords), $"Duplicate keyword found: '{keyword}'"); |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + return result.ToFrozenSet(StringComparer.Ordinal); |
| 128 | + } |
| 129 | + |
| 130 | + private static ChatMessage CreateSystemPrompt(int maxKeywords, ReadOnlySpan<string> predefinedKeywords, double confidenceThreshold) |
| 131 | + { |
| 132 | + StringBuilder sb = new($"You are a keyword extraction expert. Analyze the given text and extract up to {maxKeywords} most relevant keywords. "); |
| 133 | + |
| 134 | + if (predefinedKeywords.Length > 0) |
| 135 | + { |
| 136 | +#pragma warning disable IDE0058 // Expression value is never used |
| 137 | + sb.Append("Focus on extracting keywords from the following predefined list: "); |
| 138 | +#if NET9_0_OR_GREATER |
| 139 | + sb.AppendJoin(", ", predefinedKeywords!); |
| 140 | +#else |
| 141 | + for (int i = 0; i < predefinedKeywords.Length; i++) |
| 142 | + { |
| 143 | + sb.Append(predefinedKeywords[i]); |
| 144 | + if (i < predefinedKeywords.Length - 1) |
| 145 | + { |
| 146 | + sb.Append(", "); |
| 147 | + } |
| 148 | + } |
| 149 | +#endif |
| 150 | + |
| 151 | + sb.Append(". "); |
| 152 | + } |
| 153 | + |
| 154 | + sb.Append("Exclude keywords with confidence score below ").Append(confidenceThreshold).Append('.'); |
| 155 | + sb.Append(" Return just the keywords separated with ';'."); |
| 156 | +#pragma warning restore IDE0058 // Expression value is never used |
| 157 | + |
| 158 | + return new(ChatRole.System, sb.ToString()); |
| 159 | + } |
| 160 | +} |
0 commit comments