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