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

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