You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

SemanticKernelMemory.cs 7.7 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. using Microsoft.SemanticKernel.Memory;
  2. using Microsoft.SemanticKernel;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using LLama.Common;
  9. using LLamaSharp.SemanticKernel.TextEmbedding;
  10. using Microsoft.SemanticKernel.AI.Embeddings;
  11. namespace LLama.Examples.NewVersion
  12. {
  13. public class SemanticKernelMemory
  14. {
  15. private const string MemoryCollectionName = "SKGitHub";
  16. public static async Task Run()
  17. {
  18. var loggerFactory = ConsoleLogger.LoggerFactory;
  19. Console.WriteLine("Example from: https://github.com/microsoft/semantic-kernel/blob/main/dotnet/samples/KernelSyntaxExamples/Example14_SemanticMemory.cs");
  20. Console.Write("Please input your model path: ");
  21. var modelPath = Console.ReadLine();
  22. var seed = 1337;
  23. // Load weights into memory
  24. var parameters = new ModelParams(modelPath)
  25. {
  26. Seed = seed,
  27. EmbeddingMode = true,
  28. GpuLayerCount = 50,
  29. };
  30. using var model = LLamaWeights.LoadFromFile(parameters);
  31. var embedding = new LLamaEmbedder(model, parameters);
  32. Console.WriteLine("====================================================");
  33. Console.WriteLine("======== Semantic Memory (volatile, in RAM) ========");
  34. Console.WriteLine("====================================================");
  35. /* You can build your own semantic memory combining an Embedding Generator
  36. * with a Memory storage that supports search by similarity (ie semantic search).
  37. *
  38. * In this example we use a volatile memory, a local simulation of a vector DB.
  39. *
  40. * You can replace VolatileMemoryStore with Qdrant (see QdrantMemoryStore connector)
  41. * or implement your connectors for Pinecone, Vespa, Postgres + pgvector, SQLite VSS, etc.
  42. */
  43. var kernelWithCustomDb = Kernel.Builder
  44. .WithLoggerFactory(ConsoleLogger.LoggerFactory)
  45. .WithAIService<ITextEmbeddingGeneration>("local-llama-embed", new LLamaSharpEmbeddingGeneration(embedding), true)
  46. .WithMemoryStorage(new VolatileMemoryStore())
  47. .Build();
  48. await RunExampleAsync(kernelWithCustomDb);
  49. }
  50. private static async Task RunExampleAsync(IKernel kernel)
  51. {
  52. await StoreMemoryAsync(kernel);
  53. await SearchMemoryAsync(kernel, "How do I get started?");
  54. /*
  55. Output:
  56. Query: How do I get started?
  57. Result 1:
  58. URL: : https://github.com/microsoft/semantic-kernel/blob/main/README.md
  59. Title : README: Installation, getting started, and how to contribute
  60. Result 2:
  61. URL: : https://github.com/microsoft/semantic-kernel/blob/main/samples/dotnet-jupyter-notebooks/00-getting-started.ipynb
  62. Title : Jupyter notebook describing how to get started with the Semantic Kernel
  63. */
  64. await SearchMemoryAsync(kernel, "Can I build a chat with SK?");
  65. /*
  66. Output:
  67. Query: Can I build a chat with SK?
  68. Result 1:
  69. URL: : https://github.com/microsoft/semantic-kernel/tree/main/samples/skills/ChatSkill/ChatGPT
  70. Title : Sample demonstrating how to create a chat skill interfacing with ChatGPT
  71. Result 2:
  72. URL: : https://github.com/microsoft/semantic-kernel/blob/main/samples/apps/chat-summary-webapp-react/README.md
  73. Title : README: README associated with a sample chat summary react-based webapp
  74. */
  75. await SearchMemoryAsync(kernel, "Jupyter notebook");
  76. await SearchMemoryAsync(kernel, "README: README associated with a sample chat summary react-based webapp");
  77. await SearchMemoryAsync(kernel, "Jupyter notebook describing how to pass prompts from a file to a semantic skill or function");
  78. }
  79. private static async Task SearchMemoryAsync(IKernel kernel, string query)
  80. {
  81. Console.WriteLine("\nQuery: " + query + "\n");
  82. var memories = kernel.Memory.SearchAsync(MemoryCollectionName, query, limit: 10, minRelevanceScore: 0.5);
  83. int i = 0;
  84. await foreach (MemoryQueryResult memory in memories)
  85. {
  86. Console.WriteLine($"Result {++i}:");
  87. Console.WriteLine(" URL: : " + memory.Metadata.Id);
  88. Console.WriteLine(" Title : " + memory.Metadata.Description);
  89. Console.WriteLine(" Relevance: " + memory.Relevance);
  90. Console.WriteLine();
  91. }
  92. Console.WriteLine("----------------------");
  93. }
  94. private static async Task StoreMemoryAsync(IKernel kernel)
  95. {
  96. /* Store some data in the semantic memory.
  97. *
  98. * When using Azure Cognitive Search the data is automatically indexed on write.
  99. *
  100. * When using the combination of VolatileStore and Embedding generation, SK takes
  101. * care of creating and storing the index
  102. */
  103. Console.WriteLine("\nAdding some GitHub file URLs and their descriptions to the semantic memory.");
  104. var githubFiles = SampleData();
  105. var i = 0;
  106. foreach (var entry in githubFiles)
  107. {
  108. var result = await kernel.Memory.SaveReferenceAsync(
  109. collection: MemoryCollectionName,
  110. externalSourceName: "GitHub",
  111. externalId: entry.Key,
  112. description: entry.Value,
  113. text: entry.Value);
  114. Console.WriteLine($"#{++i} saved.");
  115. Console.WriteLine(result);
  116. }
  117. Console.WriteLine("\n----------------------");
  118. }
  119. private static Dictionary<string, string> SampleData()
  120. {
  121. return new Dictionary<string, string>
  122. {
  123. ["https://github.com/microsoft/semantic-kernel/blob/main/README.md"]
  124. = "README: Installation, getting started, and how to contribute",
  125. ["https://github.com/microsoft/semantic-kernel/blob/main/dotnet/notebooks/02-running-prompts-from-file.ipynb"]
  126. = "Jupyter notebook describing how to pass prompts from a file to a semantic skill or function",
  127. ["https://github.com/microsoft/semantic-kernel/blob/main/dotnet/notebooks//00-getting-started.ipynb"]
  128. = "Jupyter notebook describing how to get started with the Semantic Kernel",
  129. ["https://github.com/microsoft/semantic-kernel/tree/main/samples/skills/ChatSkill/ChatGPT"]
  130. = "Sample demonstrating how to create a chat skill interfacing with ChatGPT",
  131. ["https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel/Memory/VolatileMemoryStore.cs"]
  132. = "C# class that defines a volatile embedding store",
  133. ["https://github.com/microsoft/semantic-kernel/blob/main/samples/dotnet/KernelHttpServer/README.md"]
  134. = "README: How to set up a Semantic Kernel Service API using Azure Function Runtime v4",
  135. ["https://github.com/microsoft/semantic-kernel/blob/main/samples/apps/chat-summary-webapp-react/README.md"]
  136. = "README: README associated with a sample chat summary react-based webapp",
  137. };
  138. }
  139. }
  140. }