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

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