|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using System.Runtime.CompilerServices; |
| 4 | +using Microsoft.Extensions.DependencyInjection; |
| 5 | +using Microsoft.SemanticKernel; |
| 6 | +using Microsoft.SemanticKernel.ChatCompletion; |
| 7 | +using Microsoft.SemanticKernel.Embeddings; |
| 8 | +using Microsoft.SemanticKernel.Memory; |
| 9 | +using Microsoft.SemanticKernel.PromptTemplates.Handlebars; |
| 10 | +using Microsoft.SemanticKernel.Services; |
| 11 | + |
| 12 | +namespace Optimization; |
| 13 | + |
| 14 | +/// <summary> |
| 15 | +/// This example shows how to use FrugalGPT techniques to reduce cost and improve LLM-related task performance. |
| 16 | +/// More information here: https://arxiv.org/abs/2305.05176. |
| 17 | +/// </summary> |
| 18 | +public sealed class FrugalGPT(ITestOutputHelper output) : BaseTest(output) |
| 19 | +{ |
| 20 | + /// <summary> |
| 21 | + /// One of the FrugalGPT techniques is to reduce prompt size when using few-shot prompts. |
| 22 | + /// If prompt contains a lof of examples to help LLM to provide the best result, it's possible to send only a couple of them to reduce amount of tokens. |
| 23 | + /// Vector similarity can be used to pick the best examples from example set for specific request. |
| 24 | + /// Following example shows how to optimize email classification request by reducing prompt size with vector similarity search. |
| 25 | + /// </summary> |
| 26 | + [Fact] |
| 27 | + public async Task ReducePromptSizeAsync() |
| 28 | + { |
| 29 | + // Define email classification examples with email body and labels. |
| 30 | + var examples = new List<string> |
| 31 | + { |
| 32 | + "Hey, just checking in to see how you're doing! - Personal", |
| 33 | + "Can you pick up some groceries on your way back home? We need milk and bread. - Personal, Tasks", |
| 34 | + "Happy Birthday! Wishing you a fantastic day filled with love and joy. - Personal", |
| 35 | + "Let's catch up over coffee this Saturday. It's been too long! - Personal, Events", |
| 36 | + "Please review the attached document and provide your feedback by EOD. - Work", |
| 37 | + "Our team meeting is scheduled for 10 AM tomorrow in the main conference room. - Work", |
| 38 | + "The quarterly financial report is due next Monday. Ensure all data is updated. - Work, Tasks", |
| 39 | + "Can you send me the latest version of the project plan? Thanks! - Work", |
| 40 | + "You're invited to our annual summer picnic! RSVP by June 25th. - Events", |
| 41 | + "Join us for a webinar on digital marketing trends this Thursday at 3 PM. - Events", |
| 42 | + "Save the date for our charity gala on September 15th. We hope to see you there! - Events", |
| 43 | + "Don't miss our customer appreciation event next week. Sign up now! - Events, Notifications", |
| 44 | + "Your order has been shipped and will arrive by June 20th. - Notifications", |
| 45 | + "We've updated our policies. Please review the changes. - Notifications", |
| 46 | + "Your username was successfully changed. If this wasn't you, contact support immediately. - Notifications", |
| 47 | + "The system upgrade will occur this weekend. - Notifications, Work", |
| 48 | + "Don't forget to submit your timesheet by 5 PM today. - Tasks, Work", |
| 49 | + "Pick up the dry cleaning before they close at 7 PM. - Tasks", |
| 50 | + "Complete the online training module by the end of the week. - Tasks, Work", |
| 51 | + "Send out the meeting invites for next week's project kickoff. - Tasks, Work" |
| 52 | + }; |
| 53 | + |
| 54 | + // Initialize kernel with chat completion and embedding generation services. |
| 55 | + // It's possible to combine different models from different AI providers to achieve the lowest token usage. |
| 56 | + var kernel = Kernel.CreateBuilder() |
| 57 | + .AddOpenAIChatCompletion( |
| 58 | + modelId: "gpt-4", |
| 59 | + apiKey: TestConfiguration.OpenAI.ApiKey) |
| 60 | + .AddOpenAITextEmbeddingGeneration( |
| 61 | + modelId: "text-embedding-3-small", |
| 62 | + apiKey: TestConfiguration.OpenAI.ApiKey) |
| 63 | + .Build(); |
| 64 | + |
| 65 | + // Initialize few-shot prompt. |
| 66 | + var function = kernel.CreateFunctionFromPrompt( |
| 67 | + new() |
| 68 | + { |
| 69 | + Template = |
| 70 | + """ |
| 71 | + Available classification labels: Personal, Work, Events, Notifications, Tasks |
| 72 | + Email classification examples: |
| 73 | + {{#each Examples}} |
| 74 | + {{this}} |
| 75 | + {{/each}} |
| 76 | +
|
| 77 | + Email body to classify: |
| 78 | + {{Request}} |
| 79 | + """, |
| 80 | + TemplateFormat = "handlebars" |
| 81 | + }, |
| 82 | + new HandlebarsPromptTemplateFactory() |
| 83 | + ); |
| 84 | + |
| 85 | + // Define arguments with few-shot examples and actual email for classification. |
| 86 | + var arguments = new KernelArguments |
| 87 | + { |
| 88 | + ["Examples"] = examples, |
| 89 | + ["Request"] = "Your dentist appointment is tomorrow at 10 AM. Please remember to bring your insurance card." |
| 90 | + }; |
| 91 | + |
| 92 | + // Invoke defined function to see initial result. |
| 93 | + var result = await kernel.InvokeAsync(function, arguments); |
| 94 | + |
| 95 | + Console.WriteLine(result); // Personal, Notifications |
| 96 | + Console.WriteLine(result.Metadata?["Usage"]?.AsJson()); // Total tokens: ~430 |
| 97 | + |
| 98 | + // Add few-shot prompt optimization filter. |
| 99 | + // The filter uses in-memory store for vector similarity search and text embedding generation service to generate embeddings. |
| 100 | + var memoryStore = new VolatileMemoryStore(); |
| 101 | + var textEmbeddingGenerationService = kernel.GetRequiredService<ITextEmbeddingGenerationService>(); |
| 102 | + |
| 103 | + // Register optimization filter. |
| 104 | + kernel.PromptRenderFilters.Add(new FewShotPromptOptimizationFilter(memoryStore, textEmbeddingGenerationService)); |
| 105 | + |
| 106 | + // Get result again and compare the usage. |
| 107 | + result = await kernel.InvokeAsync(function, arguments); |
| 108 | + |
| 109 | + Console.WriteLine(result); // Personal, Notifications |
| 110 | + Console.WriteLine(result.Metadata?["Usage"]?.AsJson()); // Total tokens: ~150 |
| 111 | + } |
| 112 | + |
| 113 | + /// <summary> |
| 114 | + /// LLM cascade technique allows to use multiple LLMs sequentially starting from cheaper model, |
| 115 | + /// evaluate LLM result and return it in case it meets the quality criteria. Otherwise, proceed with next LLM in queue, |
| 116 | + /// until the result will be acceptable. |
| 117 | + /// Following example uses mock result generation and evaluation for demonstration purposes. |
| 118 | + /// Result evaluation examples including BERTScore, BLEU, METEOR and COMET metrics can be found here: |
| 119 | + /// https://github.com/microsoft/semantic-kernel/tree/main/dotnet/samples/Demos/QualityCheck. |
| 120 | + /// </summary> |
| 121 | + [Fact] |
| 122 | + public async Task LLMCascadeAsync() |
| 123 | + { |
| 124 | + // Create kernel builder. |
| 125 | + var builder = Kernel.CreateBuilder(); |
| 126 | + |
| 127 | + // Register chat completion services for demonstration purposes. |
| 128 | + // This registration is similar to AddAzureOpenAIChatCompletion and AddOpenAIChatCompletion methods. |
| 129 | + builder.Services.AddSingleton<IChatCompletionService>(new MockChatCompletionService("model1", "Hi there! I'm doing well, thank you! How about yourself?")); |
| 130 | + builder.Services.AddSingleton<IChatCompletionService>(new MockChatCompletionService("model2", "Hello! I'm great, thanks for asking. How are you doing today?")); |
| 131 | + builder.Services.AddSingleton<IChatCompletionService>(new MockChatCompletionService("model3", "Hey! I'm fine, thanks. How's your day going so far?")); |
| 132 | + |
| 133 | + // Register LLM cascade filter with model execution order, acceptance criteria for result and service for output. |
| 134 | + // In real use-cases, execution order should start from cheaper to more expensive models. |
| 135 | + // If first model will produce acceptable result, then it will be returned immediately. |
| 136 | + builder.Services.AddSingleton<IFunctionInvocationFilter>(new LLMCascadeFilter( |
| 137 | + modelExecutionOrder: ["model1", "model2", "model3"], |
| 138 | + acceptanceCriteria: result => result.Contains("Hey!"), |
| 139 | + output: this.Output)); |
| 140 | + |
| 141 | + // Build kernel. |
| 142 | + var kernel = builder.Build(); |
| 143 | + |
| 144 | + // Send a request. |
| 145 | + var result = await kernel.InvokePromptAsync("Hi, how are you today?"); |
| 146 | + |
| 147 | + Console.WriteLine($"\nFinal result: {result}"); |
| 148 | + |
| 149 | + // Output: |
| 150 | + // Executing request with model: model1 |
| 151 | + // Result from model1: Hi there! I'm doing well, thank you! How about yourself? |
| 152 | + // Result does not meet the acceptance criteria, moving to the next model. |
| 153 | + |
| 154 | + // Executing request with model: model2 |
| 155 | + // Result from model2: Hello! I'm great, thanks for asking. How are you doing today? |
| 156 | + // Result does not meet the acceptance criteria, moving to the next model. |
| 157 | + |
| 158 | + // Executing request with model: model3 |
| 159 | + // Result from model3: Hey! I'm fine, thanks. How's your day going so far? |
| 160 | + // Returning result as it meets the acceptance criteria. |
| 161 | + |
| 162 | + // Final result: Hey! I'm fine, thanks. How's your day going so far? |
| 163 | + } |
| 164 | + |
| 165 | + /// <summary> |
| 166 | + /// Few-shot prompt optimization filter which takes all examples from kernel arguments and selects first <see cref="TopN"/> examples, |
| 167 | + /// which are similar to original request. |
| 168 | + /// </summary> |
| 169 | + private sealed class FewShotPromptOptimizationFilter( |
| 170 | + IMemoryStore memoryStore, |
| 171 | + ITextEmbeddingGenerationService textEmbeddingGenerationService) : IPromptRenderFilter |
| 172 | + { |
| 173 | + /// <summary> |
| 174 | + /// Maximum number of examples to use which are similar to original request. |
| 175 | + /// </summary> |
| 176 | + private const int TopN = 5; |
| 177 | + |
| 178 | + /// <summary> |
| 179 | + /// Collection name to use in memory store. |
| 180 | + /// </summary> |
| 181 | + private const string CollectionName = "examples"; |
| 182 | + |
| 183 | + public async Task OnPromptRenderAsync(PromptRenderContext context, Func<PromptRenderContext, Task> next) |
| 184 | + { |
| 185 | + // Get examples and original request from arguments. |
| 186 | + var examples = context.Arguments["Examples"] as List<string>; |
| 187 | + var request = context.Arguments["Request"] as string; |
| 188 | + |
| 189 | + if (examples is { Count: > 0 } && !string.IsNullOrEmpty(request)) |
| 190 | + { |
| 191 | + var memoryRecords = new List<MemoryRecord>(); |
| 192 | + |
| 193 | + // Generate embedding for each example. |
| 194 | + var embeddings = await textEmbeddingGenerationService.GenerateEmbeddingsAsync(examples); |
| 195 | + |
| 196 | + // Create memory record instances with example text and embedding. |
| 197 | + for (var i = 0; i < examples.Count; i++) |
| 198 | + { |
| 199 | + memoryRecords.Add(MemoryRecord.LocalRecord(Guid.NewGuid().ToString(), examples[i], "description", embeddings[i])); |
| 200 | + } |
| 201 | + |
| 202 | + // Create collection and upsert all memory records for search. |
| 203 | + // It's possible to do it only once and re-use the same examples for future requests. |
| 204 | + await memoryStore.CreateCollectionAsync(CollectionName); |
| 205 | + await memoryStore.UpsertBatchAsync(CollectionName, memoryRecords).ToListAsync(); |
| 206 | + |
| 207 | + // Generate embedding for original request. |
| 208 | + var requestEmbedding = await textEmbeddingGenerationService.GenerateEmbeddingAsync(request); |
| 209 | + |
| 210 | + // Find top N examples which are similar to original request. |
| 211 | + var topNExamples = await memoryStore.GetNearestMatchesAsync(CollectionName, requestEmbedding, TopN).ToListAsync(); |
| 212 | + |
| 213 | + // Override arguments to use only top N examples, which will be sent to LLM. |
| 214 | + context.Arguments["Examples"] = topNExamples.Select(l => l.Item1.Metadata.Text); |
| 215 | + } |
| 216 | + |
| 217 | + // Continue prompt rendering operation. |
| 218 | + await next(context); |
| 219 | + } |
| 220 | + } |
| 221 | + |
| 222 | + /// <summary> |
| 223 | + /// Example of LLM cascade filter which will invoke a function using multiple LLMs in specific order, |
| 224 | + /// until the result will meet specified acceptance criteria. |
| 225 | + /// </summary> |
| 226 | + private sealed class LLMCascadeFilter( |
| 227 | + List<string> modelExecutionOrder, |
| 228 | + Predicate<string> acceptanceCriteria, |
| 229 | + ITestOutputHelper output) : IFunctionInvocationFilter |
| 230 | + { |
| 231 | + public async Task OnFunctionInvocationAsync(FunctionInvocationContext context, Func<FunctionInvocationContext, Task> next) |
| 232 | + { |
| 233 | + // Get registered chat completion services from kernel. |
| 234 | + var registeredServices = context.Kernel |
| 235 | + .GetAllServices<IChatCompletionService>() |
| 236 | + .Select(service => (ModelId: service.GetModelId()!, Service: service)); |
| 237 | + |
| 238 | + // Define order of execution. |
| 239 | + var order = modelExecutionOrder |
| 240 | + .Select((value, index) => new { Value = value, Index = index }) |
| 241 | + .ToDictionary(k => k.Value, v => v.Index); |
| 242 | + |
| 243 | + // Sort services by specified order. |
| 244 | + var orderedServices = registeredServices.OrderBy(service => order[service.ModelId]); |
| 245 | + |
| 246 | + // Try to invoke a function with each service and check the result. |
| 247 | + foreach (var service in orderedServices) |
| 248 | + { |
| 249 | + // Define execution settings with model ID. |
| 250 | + context.Arguments.ExecutionSettings = new Dictionary<string, PromptExecutionSettings> |
| 251 | + { |
| 252 | + { PromptExecutionSettings.DefaultServiceId, new() { ModelId = service.ModelId } } |
| 253 | + }; |
| 254 | + |
| 255 | + output.WriteLine($"Executing request with model: {service.ModelId}"); |
| 256 | + |
| 257 | + // Invoke a function. |
| 258 | + await next(context); |
| 259 | + |
| 260 | + // Get a result. |
| 261 | + var result = context.Result.ToString()!; |
| 262 | + |
| 263 | + output.WriteLine($"Result from {service.ModelId}: {result}"); |
| 264 | + |
| 265 | + // Check if result meets specified acceptance criteria. |
| 266 | + // If yes, stop execution loop, so last result will be returned. |
| 267 | + if (acceptanceCriteria(result)) |
| 268 | + { |
| 269 | + output.WriteLine("Returning result as it meets the acceptance criteria."); |
| 270 | + return; |
| 271 | + } |
| 272 | + |
| 273 | + // Otherwise, proceed with next model. |
| 274 | + output.WriteLine("Result does not meet the acceptance criteria, moving to the next model.\n"); |
| 275 | + } |
| 276 | + |
| 277 | + // If LLMs didn't return acceptable result, the last result will be returned. |
| 278 | + // It's also possible to throw an exception in such cases if needed. |
| 279 | + // throw new Exception("Models didn't return a result that meets the acceptance criteria"). |
| 280 | + } |
| 281 | + } |
| 282 | + |
| 283 | + /// <summary> |
| 284 | + /// Mock chat completion service for demonstration purposes. |
| 285 | + /// </summary> |
| 286 | + private sealed class MockChatCompletionService(string modelId, string mockResult) : IChatCompletionService |
| 287 | + { |
| 288 | + public IReadOnlyDictionary<string, object?> Attributes => new Dictionary<string, object?> { { AIServiceExtensions.ModelIdKey, modelId } }; |
| 289 | + |
| 290 | + public Task<IReadOnlyList<ChatMessageContent>> GetChatMessageContentsAsync( |
| 291 | + ChatHistory chatHistory, |
| 292 | + PromptExecutionSettings? executionSettings = null, |
| 293 | + Kernel? kernel = null, |
| 294 | + CancellationToken cancellationToken = default) |
| 295 | + { |
| 296 | + return Task.FromResult<IReadOnlyList<ChatMessageContent>>([new ChatMessageContent(AuthorRole.Assistant, mockResult)]); |
| 297 | + } |
| 298 | + |
| 299 | + public async IAsyncEnumerable<StreamingChatMessageContent> GetStreamingChatMessageContentsAsync( |
| 300 | + ChatHistory chatHistory, |
| 301 | + PromptExecutionSettings? executionSettings = null, |
| 302 | + Kernel? kernel = null, |
| 303 | + [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| 304 | + { |
| 305 | + yield return new StreamingChatMessageContent(AuthorRole.Assistant, mockResult); |
| 306 | + } |
| 307 | + } |
| 308 | +} |
0 commit comments