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.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. }
  76. private static async Task SearchMemoryAsync(IKernel kernel, string query)
  77. {
  78. Console.WriteLine("\nQuery: " + query + "\n");
  79. var memories = kernel.Memory.SearchAsync(MemoryCollectionName, query, limit: 2, minRelevanceScore: 0.5);
  80. int i = 0;
  81. await foreach (MemoryQueryResult memory in memories)
  82. {
  83. Console.WriteLine($"Result {++i}:");
  84. Console.WriteLine(" URL: : " + memory.Metadata.Id);
  85. Console.WriteLine(" Title : " + memory.Metadata.Description);
  86. Console.WriteLine(" Relevance: " + memory.Relevance);
  87. Console.WriteLine();
  88. }
  89. Console.WriteLine("----------------------");
  90. }
  91. private static async Task StoreMemoryAsync(IKernel kernel)
  92. {
  93. /* Store some data in the semantic memory.
  94. *
  95. * When using Azure Cognitive Search the data is automatically indexed on write.
  96. *
  97. * When using the combination of VolatileStore and Embedding generation, SK takes
  98. * care of creating and storing the index
  99. */
  100. Console.WriteLine("\nAdding some GitHub file URLs and their descriptions to the semantic memory.");
  101. var githubFiles = SampleData();
  102. var i = 0;
  103. foreach (var entry in githubFiles)
  104. {
  105. var result = await kernel.Memory.SaveReferenceAsync(
  106. collection: MemoryCollectionName,
  107. externalSourceName: "GitHub",
  108. externalId: entry.Key,
  109. description: entry.Value,
  110. text: entry.Value);
  111. Console.WriteLine($"#{++i} saved.");
  112. Console.WriteLine(result);
  113. }
  114. Console.WriteLine("\n----------------------");
  115. }
  116. private static Dictionary<string, string> SampleData()
  117. {
  118. return new Dictionary<string, string>
  119. {
  120. ["https://github.com/microsoft/semantic-kernel/blob/main/README.md"]
  121. = "README: Installation, getting started, and how to contribute",
  122. ["https://github.com/microsoft/semantic-kernel/blob/main/dotnet/notebooks/02-running-prompts-from-file.ipynb"]
  123. = "Jupyter notebook describing how to pass prompts from a file to a semantic skill or function",
  124. ["https://github.com/microsoft/semantic-kernel/blob/main/dotnet/notebooks//00-getting-started.ipynb"]
  125. = "Jupyter notebook describing how to get started with the Semantic Kernel",
  126. ["https://github.com/microsoft/semantic-kernel/tree/main/samples/skills/ChatSkill/ChatGPT"]
  127. = "Sample demonstrating how to create a chat skill interfacing with ChatGPT",
  128. ["https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel/Memory/VolatileMemoryStore.cs"]
  129. = "C# class that defines a volatile embedding store",
  130. ["https://github.com/microsoft/semantic-kernel/blob/main/samples/dotnet/KernelHttpServer/README.md"]
  131. = "README: How to set up a Semantic Kernel Service API using Azure Function Runtime v4",
  132. ["https://github.com/microsoft/semantic-kernel/blob/main/samples/apps/chat-summary-webapp-react/README.md"]
  133. = "README: README associated with a sample chat summary react-based webapp",
  134. };
  135. }
  136. }
  137. }