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.

SemanticKernelMemorySkill.cs 8.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. using System.Reflection.Metadata;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. using LLama.Abstractions;
  5. using LLama.Common;
  6. using LLamaSharp.SemanticKernel.TextCompletion;
  7. using LLamaSharp.SemanticKernel.TextEmbedding;
  8. using Microsoft.Extensions.Logging;
  9. using Microsoft.SemanticKernel;
  10. using Microsoft.SemanticKernel.AI.ChatCompletion;
  11. using Microsoft.SemanticKernel.AI.Embeddings;
  12. using Microsoft.SemanticKernel.AI.TextCompletion;
  13. using Microsoft.SemanticKernel.Memory;
  14. using Microsoft.SemanticKernel.Skills.Core;
  15. namespace LLama.Examples.NewVersion
  16. {
  17. public class SemanticKernelMemorySkill
  18. {
  19. private const string MemoryCollectionName = "aboutMe";
  20. public static async Task Run()
  21. {
  22. var loggerFactory = ConsoleLogger.LoggerFactory;
  23. Console.WriteLine("Example from: https://github.com/microsoft/semantic-kernel/blob/main/dotnet/samples/KernelSyntaxExamples/Example15_MemorySkill.cs");
  24. Console.Write("Please input your model path: ");
  25. var modelPath = Console.ReadLine();
  26. var seed = 1337;
  27. // Load weights into memory
  28. var parameters = new ModelParams(modelPath)
  29. {
  30. Seed = seed,
  31. EmbeddingMode = true,
  32. GpuLayerCount = 50,
  33. };
  34. using var model = LLamaWeights.LoadFromFile(parameters);
  35. var embedding = new LLamaEmbedder(model, parameters);
  36. using var context = model.CreateContext(parameters);
  37. // TODO: This executor is most likely incorrect.
  38. var ex = new InteractiveExecutor(context);
  39. var builder = new KernelBuilder();
  40. builder.WithLoggerFactory(loggerFactory);
  41. builder.WithAIService<ITextCompletion>("local-llama-text", new LLamaSharpTextCompletion(ex), true);
  42. builder.WithAIService<ITextEmbeddingGeneration>("local-llama-embed", new LLamaSharpEmbeddingGeneration(embedding), true);
  43. builder.WithMemoryStorage(new VolatileMemoryStore());
  44. var kernel = builder.Build();
  45. // ========= Store memories using the kernel =========
  46. await kernel.Memory.SaveInformationAsync(MemoryCollectionName, id: "info1", text: "My name is Andrea");
  47. await kernel.Memory.SaveInformationAsync(MemoryCollectionName, id: "info2", text: "I work as a tourist operator");
  48. await kernel.Memory.SaveInformationAsync(MemoryCollectionName, id: "info3", text: "I've been living in Seattle since 2005");
  49. await kernel.Memory.SaveInformationAsync(MemoryCollectionName, id: "info4", text: "I visited France and Italy five times since 2015");
  50. // ========= Store memories using semantic function =========
  51. // Add Memory as a skill for other functions
  52. var memorySkill = new TextMemorySkill(kernel.Memory);
  53. kernel.ImportSkill(memorySkill);
  54. // Build a semantic function that saves info to memory
  55. const string SaveFunctionDefinition = "{{save $info}}";
  56. var memorySaver = kernel.CreateSemanticFunction(SaveFunctionDefinition);
  57. //await kernel.RunAsync(memorySaver, new()
  58. //{
  59. // [TextMemorySkill.CollectionParam] = MemoryCollectionName,
  60. // [TextMemorySkill.KeyParam] = "info5",
  61. // ["info"] = "My family is from New York"
  62. //});
  63. // ========= Test memory remember =========
  64. Console.WriteLine("========= Example: Recalling a Memory =========");
  65. var answer = await memorySkill.RetrieveAsync(MemoryCollectionName, "info1", loggerFactory);
  66. Console.WriteLine("Memory associated with 'info1': {0}", answer);
  67. answer = await memorySkill.RetrieveAsync(MemoryCollectionName, "info2", loggerFactory);
  68. Console.WriteLine("Memory associated with 'info2': {0}", answer);
  69. answer = await memorySkill.RetrieveAsync(MemoryCollectionName, "info3", loggerFactory);
  70. Console.WriteLine("Memory associated with 'info3': {0}", answer);
  71. answer = await memorySkill.RetrieveAsync(MemoryCollectionName, "info4", loggerFactory);
  72. Console.WriteLine("Memory associated with 'info4': {0}", answer);
  73. //answer = await memorySkill.RetrieveAsync(MemoryCollectionName, "info5", loggerFactory);
  74. //Console.WriteLine("Memory associated with 'info5': {0}", answer);
  75. // ========= Test memory recall =========
  76. Console.WriteLine("========= Example: Recalling an Idea =========");
  77. answer = await memorySkill.RecallAsync("where did I grow up?", MemoryCollectionName, relevance: null, limit: 2, null);
  78. Console.WriteLine("Ask: where did I grow up?");
  79. Console.WriteLine("Answer:\n{0}", answer);
  80. answer = await memorySkill.RecallAsync("where do I live?", MemoryCollectionName, relevance: null, limit: 2, null);
  81. Console.WriteLine("Ask: where do I live?");
  82. Console.WriteLine("Answer:\n{0}", answer);
  83. /*
  84. Output:
  85. Ask: where did I grow up?
  86. Answer:
  87. ["My family is from New York","I\u0027ve been living in Seattle since 2005"]
  88. Ask: where do I live?
  89. Answer:
  90. ["I\u0027ve been living in Seattle since 2005","My family is from New York"]
  91. */
  92. // ========= Use memory in a semantic function =========
  93. Console.WriteLine("========= Example: Using Recall in a Semantic Function =========");
  94. // Build a semantic function that uses memory to find facts
  95. const string RecallFunctionDefinition = @"
  96. Consider only the facts below when answering questions.
  97. About me: {{recall 'where did I grow up?'}}
  98. About me: {{recall 'where do I live?'}}
  99. Question: {{$input}}
  100. Answer:
  101. ";
  102. var aboutMeOracle = kernel.CreateSemanticFunction(RecallFunctionDefinition, maxTokens: 100);
  103. var result = await kernel.RunAsync(aboutMeOracle, new("Do I live in the same town where I grew up?")
  104. {
  105. [TextMemorySkill.CollectionParam] = MemoryCollectionName,
  106. [TextMemorySkill.RelevanceParam] = "0.8"
  107. });
  108. Console.WriteLine("Do I live in the same town where I grew up?\n");
  109. Console.WriteLine(result);
  110. /*
  111. Output:
  112. Do I live in the same town where I grew up?
  113. No, I do not live in the same town where I grew up since my family is from New York and I have been living in Seattle since 2005.
  114. */
  115. // ========= Remove a memory =========
  116. Console.WriteLine("========= Example: Forgetting a Memory =========");
  117. result = await kernel.RunAsync(aboutMeOracle, new("Tell me a bit about myself")
  118. {
  119. ["fact1"] = "What is my name?",
  120. ["fact2"] = "What do I do for a living?",
  121. [TextMemorySkill.RelevanceParam] = ".75"
  122. });
  123. Console.WriteLine("Tell me a bit about myself\n");
  124. Console.WriteLine(result);
  125. /*
  126. Approximate Output:
  127. Tell me a bit about myself
  128. My name is Andrea and my family is from New York. I work as a tourist operator.
  129. */
  130. await memorySkill.RemoveAsync(MemoryCollectionName, "info1", loggerFactory);
  131. result = await kernel.RunAsync(aboutMeOracle, new("Tell me a bit about myself"));
  132. Console.WriteLine("Tell me a bit about myself\n");
  133. Console.WriteLine(result);
  134. /*
  135. Approximate Output:
  136. Tell me a bit about myself
  137. I'm from a family originally from New York and I work as a tourist operator. I've been living in Seattle since 2005.
  138. */
  139. }
  140. }
  141. }