|
| 1 | +using KernelMemory.Extensions.ConsoleTest.Helper; |
| 2 | +using Microsoft.Extensions.DependencyInjection; |
| 3 | +using Microsoft.Extensions.Http.Resilience; |
| 4 | +using Microsoft.Extensions.Logging; |
| 5 | +using Microsoft.KernelMemory; |
| 6 | +using Microsoft.KernelMemory.Context; |
| 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 | + |
| 13 | +namespace SemanticMemory.Samples; |
| 14 | + |
| 15 | +internal class CustomParsersSample : ISample |
| 16 | +{ |
| 17 | + public async Task RunSample(string fileToParse) |
| 18 | + { |
| 19 | + var services = new ServiceCollection(); |
| 20 | + |
| 21 | + services.AddLogging(l => l |
| 22 | + .SetMinimumLevel(LogLevel.Trace) |
| 23 | + .AddConsole() |
| 24 | + .AddDebug() |
| 25 | + ); |
| 26 | + |
| 27 | + var builder = CreateBasicKernelMemoryBuilder(services); |
| 28 | + |
| 29 | + var serviceProvider = services.BuildServiceProvider(); |
| 30 | + var parserClient = serviceProvider.GetRequiredService<LLamaCloudParserClient>(); |
| 31 | + |
| 32 | + //This is not so goot, but it seems that when we build the ServerlessMemory object |
| 33 | + //it cannot access the http services registered in the service collection |
| 34 | + builder.Services.AddSingleton(parserClient); |
| 35 | + |
| 36 | + var kernelMemory = builder.Build<MemoryServerless>(); |
| 37 | + |
| 38 | + var orchestrator = builder.GetOrchestrator(); |
| 39 | + |
| 40 | + var decoders = serviceProvider.GetServices<IContentDecoder>(); |
| 41 | + |
| 42 | + // Add pipeline handlers |
| 43 | + Console.WriteLine("* Defining pipeline handlers..."); |
| 44 | + |
| 45 | + TextExtractionHandler textExtraction = new("extract", orchestrator, decoders); |
| 46 | + await orchestrator.AddHandlerAsync(textExtraction); |
| 47 | + |
| 48 | + TextPartitioningHandler textPartitioning = new("partition", orchestrator); |
| 49 | + await orchestrator.AddHandlerAsync(textPartitioning); |
| 50 | + |
| 51 | + GenerateEmbeddingsHandler textEmbedding = new("gen_embeddings", orchestrator); |
| 52 | + await orchestrator.AddHandlerAsync(textEmbedding); |
| 53 | + |
| 54 | + SaveRecordsHandler saveRecords = new("save_records", orchestrator); |
| 55 | + await orchestrator.AddHandlerAsync(saveRecords); |
| 56 | + |
| 57 | + var fileName = Path.GetFileName(fileToParse); |
| 58 | + |
| 59 | + var contextProvider = serviceProvider.GetRequiredService<IContextProvider>(); |
| 60 | + |
| 61 | + // now we are going to index document, llamacloud can use caching so we can avoid asking for file. |
| 62 | + var pipelineBuilder = orchestrator |
| 63 | + .PrepareNewDocumentUpload( |
| 64 | + index: "llamacloud", |
| 65 | + documentId: fileName, |
| 66 | + new TagCollection { { "example", "books" } }) |
| 67 | + .AddUploadFile(fileName, fileName, fileToParse) |
| 68 | + .Then("extract") |
| 69 | + .Then("partition") |
| 70 | + .Then("gen_embeddings") |
| 71 | + .Then("save_records"); |
| 72 | + |
| 73 | + contextProvider.AddLLamaCloudParserOptions(fileName, "This is a manual for Dreame vacuum cleaner, I need you to extract a series of sections that can be useful for an helpdesk to answer user questions. You will create sections where each sections contains a question and an answer taken from the text."); |
| 74 | + |
| 75 | + var pipeline = pipelineBuilder.Build(); |
| 76 | + await orchestrator.RunPipelineAsync(pipeline); |
| 77 | + |
| 78 | + // now ask a question to the user continuously until the user ask an empty question |
| 79 | + string question; |
| 80 | + do |
| 81 | + { |
| 82 | + Console.WriteLine("Ask a question to the kernel memory:"); |
| 83 | + question = Console.ReadLine(); |
| 84 | + if (!string.IsNullOrWhiteSpace(question)) |
| 85 | + { |
| 86 | + var response = await kernelMemory.AskAsync(question); |
| 87 | + Console.WriteLine(response.Result); |
| 88 | + } |
| 89 | + } while (!string.IsNullOrWhiteSpace(question)); |
| 90 | + } |
| 91 | + |
| 92 | + private static IKernelMemoryBuilder CreateBasicKernelMemoryBuilder( |
| 93 | + ServiceCollection services) |
| 94 | + { |
| 95 | + // we need a series of services to use Kernel Memory, the first one is |
| 96 | + // an embedding service that will be used to create dense vector for |
| 97 | + // pieces of test. We can use standard ADA embedding service |
| 98 | + var embeddingConfig = new AzureOpenAIConfig |
| 99 | + { |
| 100 | + APIKey = Dotenv.Get("OPENAI_API_KEY"), |
| 101 | + Deployment = "text-embedding-ada-002", |
| 102 | + Endpoint = Dotenv.Get("AZURE_ENDPOINT"), |
| 103 | + APIType = AzureOpenAIConfig.APITypes.EmbeddingGeneration, |
| 104 | + Auth = AzureOpenAIConfig.AuthTypes.APIKey |
| 105 | + }; |
| 106 | + |
| 107 | + // Now kenel memory needs the LLM data to be able to pass question |
| 108 | + // and retreived segments to the model. We can Use GPT35 |
| 109 | + var chatConfig = new AzureOpenAIConfig |
| 110 | + { |
| 111 | + APIKey = Dotenv.Get("OPENAI_API_KEY"), |
| 112 | + Deployment = Dotenv.Get("KERNEL_MEMORY_DEPLOYMENT_NAME"), |
| 113 | + Endpoint = Dotenv.Get("AZURE_ENDPOINT"), |
| 114 | + APIType = AzureOpenAIConfig.APITypes.ChatCompletion, |
| 115 | + Auth = AzureOpenAIConfig.AuthTypes.APIKey, |
| 116 | + MaxTokenTotal = 4096 |
| 117 | + }; |
| 118 | + |
| 119 | + var kernelMemoryBuilder = new KernelMemoryBuilder(services) |
| 120 | + .WithAzureOpenAITextGeneration(chatConfig) |
| 121 | + .WithAzureOpenAITextEmbeddingGeneration(embeddingConfig); |
| 122 | + |
| 123 | + kernelMemoryBuilder |
| 124 | + .WithSimpleFileStorage(new SimpleFileStorageConfig() |
| 125 | + { |
| 126 | + Directory = "c:\\temp\\kmcps\\storage", |
| 127 | + StorageType = FileSystemTypes.Disk |
| 128 | + }) |
| 129 | + .WithSimpleVectorDb(new SimpleVectorDbConfig() |
| 130 | + { |
| 131 | + Directory = "c:\\temp\\kmcps\\vectorstorage", |
| 132 | + StorageType = FileSystemTypes.Disk |
| 133 | + }); |
| 134 | + |
| 135 | + kernelMemoryBuilder.WithContentDecoder<LLamaCloudParserDocumentDecoder>(); |
| 136 | + |
| 137 | + var llamaApiKey = Environment.GetEnvironmentVariable("LLAMA_API_KEY"); |
| 138 | + if (string.IsNullOrEmpty(llamaApiKey)) |
| 139 | + { |
| 140 | + throw new Exception("LLAMA_API_KEY is not set"); |
| 141 | + } |
| 142 | + |
| 143 | + //Create llamaparser client |
| 144 | + services.AddSingleton(new CloudParserConfiguration |
| 145 | + { |
| 146 | + ApiKey = llamaApiKey, |
| 147 | + }); |
| 148 | + |
| 149 | + services.AddHttpClient<LLamaCloudParserClient>() |
| 150 | + .AddStandardResilienceHandler(options => |
| 151 | + { |
| 152 | + // Configure standard resilience options here |
| 153 | + options.TotalRequestTimeout = new HttpTimeoutStrategyOptions() |
| 154 | + { |
| 155 | + Timeout = TimeSpan.FromMinutes(10), |
| 156 | + }; |
| 157 | + }); |
| 158 | + |
| 159 | + services.AddSingleton(sp => sp.GetRequiredService<ILoggerFactory>().CreateLogger<LLamaCloudParserClient>()); |
| 160 | + |
| 161 | + services.AddSingleton<IKernelMemoryBuilder>(kernelMemoryBuilder); |
| 162 | + return kernelMemoryBuilder; |
| 163 | + } |
| 164 | +} |
0 commit comments