-
Notifications
You must be signed in to change notification settings - Fork 19
/
SemanticKernelRAGService.cs
444 lines (373 loc) · 17.6 KB
/
SemanticKernelRAGService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
using Azure.AI.OpenAI;
using BuildYourOwnCopilot.Common.Interfaces;
using BuildYourOwnCopilot.Common.Models.BusinessDomain;
using BuildYourOwnCopilot.Common.Models.Chat;
using BuildYourOwnCopilot.Infrastructure.Constants;
using BuildYourOwnCopilot.Infrastructure.Interfaces;
using BuildYourOwnCopilot.Infrastructure.Models;
using BuildYourOwnCopilot.Infrastructure.Models.ConfigurationOptions;
using BuildYourOwnCopilot.SemanticKernel.Memory;
using BuildYourOwnCopilot.SemanticKernel.Plugins.Core;
using BuildYourOwnCopilot.SemanticKernel.Plugins.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Microsoft.SemanticKernel.Memory;
using System.Text.Json;
using System.Text.RegularExpressions;
#pragma warning disable SKEXP0001, SKEXP0010, SKEXP0020, SKEXP0050, SKEXP0060
namespace BuildYourOwnCopilot.Infrastructure.Services;
public class SemanticKernelRAGService : IRAGService
{
readonly IItemTransformerFactory _itemTransformerFactory;
readonly ISystemPromptService _systemPromptService;
readonly IEnumerable<IMemorySource> _memorySources;
readonly ICosmosDBClientFactory _cosmosDBClientFactory;
readonly ITokenizerService _tokenizerService;
readonly SemanticKernelRAGServiceSettings _settings;
readonly ILoggerFactory _loggerFactory;
readonly ILogger<SemanticKernelRAGService> _logger;
readonly Kernel _semanticKernel;
readonly Dictionary<string, VectorMemoryStore> _longTermMemoryStores = [];
VectorMemoryStore _shortTermMemoryStore;
readonly List<PluginBase> _contextPlugins = [];
KnowledgeManagementContextPlugin _kmContextPlugin;
ContextPluginsListPlugin _listPlugin;
readonly ISemanticCacheService _semanticCache;
bool _serviceInitialized = false;
string _prompt = string.Empty;
string _contextSelectorPrompt = string.Empty;
public bool IsInitialized => _serviceInitialized;
public SemanticKernelRAGService(
IItemTransformerFactory itemTransformerFactory,
ISystemPromptService systemPromptService,
IEnumerable<IMemorySource> memorySources,
ICosmosDBClientFactory cosmosDBClientFactory,
ITokenizerService tokenizerService,
IOptions<SemanticKernelRAGServiceSettings> options,
ILoggerFactory loggerFactory)
{
_itemTransformerFactory = itemTransformerFactory;
_systemPromptService = systemPromptService;
_memorySources = memorySources;
_cosmosDBClientFactory = cosmosDBClientFactory;
_tokenizerService = tokenizerService;
_settings = options.Value;
_loggerFactory = loggerFactory;
_logger = _loggerFactory.CreateLogger<SemanticKernelRAGService>();
_logger.LogInformation("Initializing the Semantic Kernel RAG service...");
var builder = Kernel.CreateBuilder();
builder.Services.AddSingleton<ILoggerFactory>(loggerFactory);
builder.AddAzureOpenAIChatCompletion(
_settings.OpenAI.CompletionsDeployment,
_settings.OpenAI.Endpoint,
_settings.OpenAI.Key);
_semanticKernel = builder.Build();
CreateMemoryStoresAndPlugins();
// Semantic cache uses a dedicated text embedding generation service.
// This allows us to experiment with different embedding sizes.
_semanticCache = new SemanticCacheService(
_settings.SemanticCache,
_settings.OpenAI,
_settings.SemanticCacheIndexing,
cosmosDBClientFactory,
_tokenizerService,
_settings.TextSplitter.TokenizerEncoder!,
loggerFactory);
Task.Run(Initialize);
}
private async Task Initialize()
{
try
{
foreach (var longTermMemoryStore in _longTermMemoryStores.Values)
await longTermMemoryStore.Initialize();
await EnsureShortTermMemory();
await _semanticCache.Initialize();
_prompt = await _systemPromptService.GetPrompt(_settings.OpenAI.ChatCompletionPromptName);
_kmContextPlugin = new KnowledgeManagementContextPlugin(
_prompt,
_settings.OpenAI,
_loggerFactory.CreateLogger<KnowledgeManagementContextPlugin>());
_semanticKernel.ImportPluginFromObject(_kmContextPlugin);
_contextSelectorPrompt = await _systemPromptService.GetPrompt(_settings.OpenAI.ContextSelectorPromptName);
_listPlugin = new ContextPluginsListPlugin(
_contextPlugins);
_semanticKernel.ImportPluginFromObject(_listPlugin);
_serviceInitialized = true;
_logger.LogInformation("Semantic Kernel RAG service initialized.");
}
catch (Exception ex)
{
_logger.LogError(ex, "Semantic Kernel RAG service was not initialized. The following error occurred: {ErrorMessage}.", ex.Message);
}
}
private void CreateMemoryStoresAndPlugins()
{
// The long-term memory stores use an Azure Cosmos DB NoSQL memory store.
foreach (var item in _settings.ModelRegistryKnowledgeIndexing.Values)
{
var memoryStore = new VectorMemoryStore(
item.IndexName,
new AzureCosmosDBNoSQLMemoryStore(
_cosmosDBClientFactory.Client,
_cosmosDBClientFactory.DatabaseName,
item.VectorEmbeddingPolicy,
item.IndexingPolicy),
new AzureOpenAITextEmbeddingGenerationService(
_settings.OpenAI.EmbeddingsDeployment,
_settings.OpenAI.Endpoint,
_settings.OpenAI.Key,
dimensions: (int)item.Dimensions),
_loggerFactory.CreateLogger<VectorMemoryStore>()
);
_longTermMemoryStores.Add(memoryStore.CollectionName, memoryStore);
_contextPlugins.Add(new MemoryStoreContextPlugin(
memoryStore,
item,
_loggerFactory.CreateLogger<MemoryStoreContextPlugin>()));
}
// The short-term memory store uses a volatile memory store.
_shortTermMemoryStore = new VectorMemoryStore(
_settings.StaticKnowledgeIndexing.IndexName,
new VolatileMemoryStore(),
new AzureOpenAITextEmbeddingGenerationService(
_settings.OpenAI.EmbeddingsDeployment,
_settings.OpenAI.Endpoint,
_settings.OpenAI.Key,
dimensions: (int)_settings.StaticKnowledgeIndexing.Dimensions),
_loggerFactory.CreateLogger<VectorMemoryStore>()
);
_contextPlugins.Add(new MemoryStoreContextPlugin(
_shortTermMemoryStore,
_settings.StaticKnowledgeIndexing,
_loggerFactory.CreateLogger<MemoryStoreContextPlugin>()));
_contextPlugins.AddRange(
_settings.SystemCommandPlugins.Select(
sp => new SystemCommandPlugin(sp.Name, sp.Description, sp.PromptName)));
}
private async Task EnsureShortTermMemory()
{
try
{
// The memories collection in the short term memory store must be created explicitly
await _shortTermMemoryStore.MemoryStore.CreateCollectionAsync(
_settings.StaticKnowledgeIndexing.IndexName);
// Get current short term memories. Short term memories are generated or loaded at runtime and kept in SK's volatile memory.
//The content here has embeddings generated on it so it can be used in a vector query by the user.
// TODO: Explore the option of moving static memories loaded from blob storage into the long-term memory (e.g., the Azure Cosmos DB vector store collection).
// For now, the static memories are re-loaded each time.
var shortTermMemories = new List<string>();
foreach (var memorySource in _memorySources)
{
shortTermMemories.AddRange(await memorySource.GetMemories());
}
foreach (var itemTransformer in shortTermMemories
.Select(m => _itemTransformerFactory.CreateItemTransformer(new ShortTermMemory
{
entityType__ = nameof(ShortTermMemory),
memory__ = m
})))
{
await _shortTermMemoryStore.AddMemory(itemTransformer);
}
_logger.LogInformation("Semantic Kernel RAG service short-term memory initialized.");
}
catch (Exception ex)
{
_logger.LogError(ex, "The Semantic Kernel RAG service short-term memory failed to initialize.");
}
}
private List<MemoryStoreContextPlugin> GetMemoryPluginsToRun(List<string> pluginNames) =>
_contextPlugins
.Where(cp => pluginNames.Contains(cp.Name) && (cp is MemoryStoreContextPlugin))
.Select(cp => (cp as MemoryStoreContextPlugin)!)
.ToList();
private async Task<string> ExecuteSystemCommands(List<string> pluginNames, string userPompt)
{
var results = new List<string>();
foreach (var pluginName in pluginNames)
{
switch (pluginName)
{
case SystemCommands.ResetSemanticCache:
await _semanticCache.Reset();
results.Add("The content of the semantic cache was reset.");
break;
case SystemCommands.SetSemanticCacheSimilarityScore:
var similarityScore = await GetSemanticCacheSimilarityScore(userPompt, pluginName);
var newSimilarityScore = similarityScore == 1
? 1
: similarityScore;
_semanticCache.SetMinRelevanceOverride(newSimilarityScore);
results.Add(similarityScore == 1
? "The similarity score parser was not able to parse a value for the similarity score of the semantic cache. The default value of 0.95 will be used."
: $"The similarity score {similarityScore} was set for the semantic cache. The new score will be in effect until the backend API is restarted.");
break;
default:
break;
}
}
results.Add("Because your request contained system commands, all other requests were ignored.");
return string.Join(Environment.NewLine, results);
}
private bool HasSystemCommands(List<string> pluginNames) =>
pluginNames
.Intersect([
SystemCommands.ResetSemanticCache,
SystemCommands.SetSemanticCacheSimilarityScore
])
.Any();
private async Task<double> GetSemanticCacheSimilarityScore(string userPrompt, string pluginName)
{
var plugin = _contextPlugins.SingleOrDefault(p => p.Name == pluginName);
if (plugin == null)
return 1;
var pluginPrompt = await _systemPromptService.GetPrompt(plugin.PromptName!);
var result = await _semanticKernel.InvokePromptAsync(
pluginPrompt,
new KernelArguments()
{
["userPrompt"] = userPrompt
});
var serializedSimilarityScore = result.GetValue<string>();
try
{
var score = JsonSerializer.Deserialize<ParsedSimilarityScore>(serializedSimilarityScore!);
return score == null
? 1
: score.SimilarityScore;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error when parsing similarity score: {ErrorMessage}", ex.Message);
return 1;
}
}
public async Task<CompletionResult> GetResponse(string userPrompt, List<Message> messageHistory)
{
var cacheItem = await _semanticCache.GetCacheItem(userPrompt, messageHistory);
if (!string.IsNullOrEmpty(cacheItem.Completion))
// If the Completion property is set, it means the cache item was populated with a hit from the cache
return new CompletionResult
{
UserPrompt = userPrompt,
UserPromptTokens = cacheItem.UserPromptTokens,
UserPromptEmbedding = cacheItem.UserPromptEmbedding.ToArray(),
RenderedPrompt = cacheItem.ConversationContext,
RenderedPromptTokens = cacheItem.ConversationContextTokens,
Completion = cacheItem.Completion,
CompletionTokens = cacheItem.CompletionTokens,
FromCache = true
};
// The semantic cache was not able to retrieve a hit from the cache so we are moving on with the normal flow.
// We still need to keep the cache item around as it contains the properties we need later on to update the cache with the new entry.
// Use observability features to capture the fully rendered prompts.
var promptFilter = new DefaultPromptFilter();
_semanticKernel.PromptRenderFilters.Add(promptFilter);
var result = await _semanticKernel.InvokePromptAsync(
_contextSelectorPrompt,
new KernelArguments
{
["userPrompt"] = userPrompt
});
var pluginNamesList = result.GetValue<string>();
if (string.IsNullOrWhiteSpace(pluginNamesList))
{
return new CompletionResult
{
UserPrompt = userPrompt,
UserPromptTokens = cacheItem.UserPromptTokens,
UserPromptEmbedding = cacheItem.UserPromptEmbedding.ToArray(),
RenderedPrompt = promptFilter.RenderedPrompt,
RenderedPromptTokens = 0,
Completion = "I am sorry, I was not able to determine a suitable action based on your request.",
CompletionTokens = 0,
FromCache = false
};
}
var pluginNames = pluginNamesList
.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
.Select(pn => pn.ToLower())
.ToList();
if (HasSystemCommands(pluginNames))
{
var systemCommandsResult = await ExecuteSystemCommands(pluginNames, userPrompt);
return new CompletionResult
{
UserPrompt = userPrompt,
UserPromptTokens = cacheItem.UserPromptTokens,
UserPromptEmbedding = cacheItem.UserPromptEmbedding.ToArray(),
RenderedPrompt = promptFilter.RenderedPrompt,
RenderedPromptTokens = 0,
Completion = systemCommandsResult,
CompletionTokens = 0,
FromCache = false
};
}
var pluginsToRun = GetMemoryPluginsToRun(pluginNames);
_kmContextPlugin.SetContextPlugins(pluginsToRun);
result = await _semanticKernel.InvokePromptAsync(
_prompt,
new KernelArguments()
{
["userPrompt"] = userPrompt,
["messageHistory"] = messageHistory
});
var completion = result.GetValue<string>()!;
var completionUsage = (result.Metadata!["Usage"] as CompletionsUsage)!;
// Add the completion to the semantic memory
cacheItem.Completion = completion;
cacheItem.CompletionTokens = completionUsage!.CompletionTokens;
await _semanticCache.SetCacheItem(cacheItem);
return new CompletionResult
{
UserPrompt = userPrompt,
UserPromptTokens = cacheItem.UserPromptTokens,
UserPromptEmbedding = cacheItem.UserPromptEmbedding.ToArray(),
RenderedPrompt = promptFilter.RenderedPrompt,
RenderedPromptTokens = completionUsage.PromptTokens,
Completion = completion,
CompletionTokens = completionUsage.CompletionTokens,
FromCache = false
};
}
public async Task<string> Summarize(string sessionId, string userPrompt)
{
var summarizerPlugin = new TextSummaryPlugin(
await _systemPromptService.GetPrompt(_settings.OpenAI.ShortSummaryPromptName),
500,
_semanticKernel);
var updatedContext = await summarizerPlugin.SummarizeTextAsync(
userPrompt);
//Remove all non-alpha numeric characters (Turbo has a habit of putting things in quotes even when you tell it not to)
var summary = Regex.Replace(updatedContext, @"[^a-zA-Z0-9.\s]", "");
return summary;
}
public async Task AddMemory(IItemTransformer itemTransformer)
{
if (!string.IsNullOrWhiteSpace(itemTransformer.VectorIndexName))
{
await _longTermMemoryStores[itemTransformer.VectorIndexName].AddMemory(itemTransformer);
}
else
_logger.LogWarning("Object with embedding id {EmbeddingId} and name {Name} has an invalid vector index name.",
itemTransformer.EmbeddingId,
itemTransformer.Name);
}
public async Task RemoveMemory(IItemTransformer itemTransformer)
{
if (!string.IsNullOrWhiteSpace(itemTransformer.VectorIndexName))
{
await _longTermMemoryStores[itemTransformer.VectorIndexName].RemoveMemory(itemTransformer);
}
else
_logger.LogWarning("Object with embedding id {EmbeddingId} and name {Name} has an invalid vector index name.",
itemTransformer.EmbeddingId,
itemTransformer.Name);
}
public async Task ResetSemanticCache() =>
await _semanticCache.Reset();
}