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

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