|
| 1 | +using KernelMemory.ElasticSearch.Anthropic; |
| 2 | +using KernelMemory.Extensions.Cohere; |
| 3 | +using KernelMemory.Extensions.ConsoleTest.Helper; |
| 4 | +using Microsoft.Extensions.DependencyInjection; |
| 5 | +using Microsoft.Extensions.Logging; |
| 6 | +using Microsoft.KernelMemory; |
| 7 | +using Microsoft.KernelMemory.DataFormats; |
| 8 | +using Microsoft.KernelMemory.DocumentStorage.DevTools; |
| 9 | +using Microsoft.KernelMemory.FileSystem.DevTools; |
| 10 | +using Microsoft.KernelMemory.Handlers; |
| 11 | +using Microsoft.KernelMemory.MemoryStorage.DevTools; |
| 12 | +using Spectre.Console; |
| 13 | + |
| 14 | +namespace SemanticMemory.Samples; |
| 15 | + |
| 16 | +public class ContextualRetrievalSample : ISample |
| 17 | +{ |
| 18 | + public async Task RunSample(string bookPdf) |
| 19 | + { |
| 20 | + var services = new ServiceCollection(); |
| 21 | + services.AddLogging(l => l |
| 22 | + .SetMinimumLevel(LogLevel.Trace) |
| 23 | + .AddConsole() |
| 24 | + .AddDebug() |
| 25 | + ); |
| 26 | + //do not forget to add decoders |
| 27 | + services.AddDefaultContentDecoders(); |
| 28 | + services.AddHttpClient<RawAnthropicHttpClient>() |
| 29 | + .AddStandardResilienceHandler(options => |
| 30 | + { |
| 31 | + // Configure standard resilience options here |
| 32 | + }); |
| 33 | + services.AddTransient<RawAnthropicClient>(); |
| 34 | + |
| 35 | + var anthropicApiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")!; |
| 36 | + if (string.IsNullOrEmpty(anthropicApiKey)) |
| 37 | + { |
| 38 | + throw new Exception("ANTHROPIC_API_KEY is not set"); |
| 39 | + } |
| 40 | + |
| 41 | + var config = new AnthropicTextGenerationConfiguration() |
| 42 | + { |
| 43 | + ApiKey = anthropicApiKey, |
| 44 | + }; |
| 45 | + services.AddSingleton(config); |
| 46 | + |
| 47 | + |
| 48 | + var builder = CreateBasicKernelMemoryBuilder(services); |
| 49 | + var kernelMemory = builder.Build<MemoryServerless>(); |
| 50 | + |
| 51 | + var orchestrator = builder.GetOrchestrator(); |
| 52 | + |
| 53 | + var serviceProvider = services.BuildServiceProvider(); |
| 54 | + var decoders = serviceProvider.GetServices<IContentDecoder>(); |
| 55 | + |
| 56 | + var anthropicClient = serviceProvider.GetRequiredService<RawAnthropicClient>(); |
| 57 | + // Add pipeline handlers |
| 58 | + Console.WriteLine("* Defining pipeline handlers..."); |
| 59 | + |
| 60 | + TextExtractionHandler textExtraction = new("extract", orchestrator, decoders); |
| 61 | + await orchestrator.AddHandlerAsync(textExtraction); |
| 62 | + |
| 63 | + TextCleanerHandler textCleanerHandler = new("clean", orchestrator); |
| 64 | + await orchestrator.AddHandlerAsync(textCleanerHandler); |
| 65 | + |
| 66 | + TextPartitioningHandler textPartitioning = new("partition", orchestrator); |
| 67 | + await orchestrator.AddHandlerAsync(textPartitioning); |
| 68 | + |
| 69 | + ClaudeContextualRetrievalHandler contextual = new("contextual", orchestrator, anthropicClient); |
| 70 | + await orchestrator.AddHandlerAsync(contextual); |
| 71 | + |
| 72 | + GenerateEmbeddingsHandler textEmbedding = new("gen_embeddings", orchestrator); |
| 73 | + await orchestrator.AddHandlerAsync(textEmbedding); |
| 74 | + |
| 75 | + SaveRecordsHandler saveRecords = new("save_records", orchestrator); |
| 76 | + await orchestrator.AddHandlerAsync(saveRecords); |
| 77 | + |
| 78 | + // orchestrator.AddHandlerAsync(...); |
| 79 | + // orchestrator.AddHandlerAsync(...); |
| 80 | + |
| 81 | + // Create sample pipeline with 4 files |
| 82 | + var index = AnsiConsole.Confirm("Do you want to index document?"); |
| 83 | + if (index) |
| 84 | + { |
| 85 | + Console.WriteLine("Single pipeline for single document"); |
| 86 | + var pipeline = orchestrator |
| 87 | + .PrepareNewDocumentUpload( |
| 88 | + index: "book", |
| 89 | + documentId: "grayhatpython", |
| 90 | + new TagCollection { { "security", "books" } }) |
| 91 | + .AddUploadFile("file1", Path.GetFileName(bookPdf), bookPdf) |
| 92 | + .Then("extract") |
| 93 | + .Then("clean") |
| 94 | + .Then("partition") |
| 95 | + .Then("contextual") |
| 96 | + .Then("gen_embeddings") |
| 97 | + .Then("save_records") |
| 98 | + .Build(); |
| 99 | + |
| 100 | + // Execute pipeline |
| 101 | + Console.WriteLine("* Executing pipeline..."); |
| 102 | + await orchestrator.RunPipelineAsync(pipeline); |
| 103 | + } |
| 104 | + string question; |
| 105 | + do |
| 106 | + { |
| 107 | + Console.WriteLine("Ask a question to the kernel memory:"); |
| 108 | + question = Console.ReadLine(); |
| 109 | + if (!string.IsNullOrWhiteSpace(question)) |
| 110 | + { |
| 111 | + var response = await kernelMemory.AskAsync(question, index: "book"); |
| 112 | + Console.WriteLine(response.Result); |
| 113 | + } |
| 114 | + } while (!string.IsNullOrWhiteSpace(question)); |
| 115 | + } |
| 116 | + |
| 117 | + private static IKernelMemoryBuilder CreateBasicKernelMemoryBuilder( |
| 118 | + ServiceCollection services) |
| 119 | + { |
| 120 | + // we need a series of services to use Kernel Memory, the first one is |
| 121 | + // an embedding service that will be used to create dense vector for |
| 122 | + // pieces of test. We can use standard ADA embedding service |
| 123 | + var embeddingConfig = new AzureOpenAIConfig |
| 124 | + { |
| 125 | + APIKey = Dotenv.Get("OPENAI_API_KEY"), |
| 126 | + Deployment = "text-embedding-ada-002", |
| 127 | + Endpoint = Dotenv.Get("AZURE_ENDPOINT"), |
| 128 | + APIType = AzureOpenAIConfig.APITypes.EmbeddingGeneration, |
| 129 | + Auth = AzureOpenAIConfig.AuthTypes.APIKey |
| 130 | + }; |
| 131 | + |
| 132 | + // Now kenel memory needs the LLM data to be able to pass question |
| 133 | + // and retreived segments to the model. We can Use GPT35 |
| 134 | + var chatConfig = new AzureOpenAIConfig |
| 135 | + { |
| 136 | + APIKey = Dotenv.Get("OPENAI_API_KEY"), |
| 137 | + Deployment = Dotenv.Get("KERNEL_MEMORY_DEPLOYMENT_NAME"), |
| 138 | + Endpoint = Dotenv.Get("AZURE_ENDPOINT"), |
| 139 | + APIType = AzureOpenAIConfig.APITypes.ChatCompletion, |
| 140 | + Auth = AzureOpenAIConfig.AuthTypes.APIKey, |
| 141 | + MaxTokenTotal = 4096 |
| 142 | + }; |
| 143 | + |
| 144 | + var kernelMemoryBuilder = new KernelMemoryBuilder(services) |
| 145 | + .WithAzureOpenAITextGeneration(chatConfig) |
| 146 | + .WithAzureOpenAITextEmbeddingGeneration(embeddingConfig); |
| 147 | + |
| 148 | + kernelMemoryBuilder |
| 149 | + .WithSimpleFileStorage(new SimpleFileStorageConfig() |
| 150 | + { |
| 151 | + Directory = "/tmp/km/storage", |
| 152 | + //Directory = "c:\\temp\\km2\\storage", |
| 153 | + StorageType = FileSystemTypes.Disk |
| 154 | + }) |
| 155 | + .WithSimpleVectorDb(new SimpleVectorDbConfig() |
| 156 | + { |
| 157 | + Directory = "/tmp/km/vectorstorage", |
| 158 | + //Directory = "c:\\temp\\km2\\vectorstorage", |
| 159 | + StorageType = FileSystemTypes.Disk |
| 160 | + }); |
| 161 | + |
| 162 | + services.AddSingleton<IKernelMemoryBuilder>(kernelMemoryBuilder); |
| 163 | + return kernelMemoryBuilder; |
| 164 | + } |
| 165 | +} |
0 commit comments