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.

SemanticKernelChat.cs 2.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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.SemanticKernel;
  7. using Microsoft.SemanticKernel.AI.ChatCompletion;
  8. using Microsoft.SemanticKernel.AI.TextCompletion;
  9. using LLamaSharp.SemanticKernel.ChatCompletion;
  10. using LLamaSharp.SemanticKernel.TextCompletion;
  11. namespace LLama.Examples.NewVersion
  12. {
  13. public class SemanticKernelChat
  14. {
  15. public static async Task Run()
  16. {
  17. Console.WriteLine("Example from: https://github.com/microsoft/semantic-kernel/blob/main/dotnet/README.md");
  18. Console.Write("Please input your model path: ");
  19. var modelPath = Console.ReadLine();
  20. // Load weights into memory
  21. var parameters = new ModelParams(modelPath)
  22. {
  23. Seed = RandomNumberGenerator.GetInt32(int.MaxValue),
  24. };
  25. using var model = LLamaWeights.LoadFromFile(parameters);
  26. using var context = model.CreateContext(parameters);
  27. var ex = new InteractiveExecutor(context);
  28. var chatGPT = new LLamaSharpChatCompletion(ex);
  29. var chatHistory = chatGPT.CreateNewChat("You are a librarian, expert about books");
  30. Console.WriteLine("Chat content:");
  31. Console.WriteLine("------------------------");
  32. chatHistory.AddUserMessage("Hi, I'm looking for book suggestions");
  33. await MessageOutputAsync(chatHistory);
  34. // First bot assistant message
  35. string reply = await chatGPT.GenerateMessageAsync(chatHistory);
  36. chatHistory.AddAssistantMessage(reply);
  37. await MessageOutputAsync(chatHistory);
  38. // Second user message
  39. chatHistory.AddUserMessage("I love history and philosophy, I'd like to learn something new about Greece, any suggestion");
  40. await MessageOutputAsync(chatHistory);
  41. // Second bot assistant message
  42. reply = await chatGPT.GenerateMessageAsync(chatHistory);
  43. chatHistory.AddAssistantMessage(reply);
  44. await MessageOutputAsync(chatHistory);
  45. }
  46. /// <summary>
  47. /// Outputs the last message of the chat history
  48. /// </summary>
  49. private static Task MessageOutputAsync(Microsoft.SemanticKernel.AI.ChatCompletion.ChatHistory chatHistory)
  50. {
  51. var message = chatHistory.Messages.Last();
  52. Console.WriteLine($"{message.Role}: {message.Content}");
  53. Console.WriteLine("------------------------");
  54. return Task.CompletedTask;
  55. }
  56. }
  57. }