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

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System.Security.Cryptography;
  2. using LLama.Common;
  3. using Microsoft.SemanticKernel.AI.ChatCompletion;
  4. using LLamaSharp.SemanticKernel.ChatCompletion;
  5. using Microsoft.SemanticKernel.ChatCompletion;
  6. namespace LLama.Examples.Examples
  7. {
  8. public class SemanticKernelChat
  9. {
  10. public static async Task Run()
  11. {
  12. Console.WriteLine("Example from: https://github.com/microsoft/semantic-kernel/blob/main/dotnet/README.md");
  13. Console.Write("Please input your model path: ");
  14. var modelPath = Console.ReadLine();
  15. // Load weights into memory
  16. var parameters = new ModelParams(modelPath);
  17. using var model = LLamaWeights.LoadFromFile(parameters);
  18. var ex = new StatelessExecutor(model, parameters);
  19. var chatGPT = new LLamaSharpChatCompletion(ex);
  20. var chatHistory = chatGPT.CreateNewChat("This is a conversation between the assistant and the user. \n\n You are a librarian, expert about books. ");
  21. Console.WriteLine("Chat content:");
  22. Console.WriteLine("------------------------");
  23. chatHistory.AddUserMessage("Hi, I'm looking for book suggestions");
  24. await MessageOutputAsync(chatHistory);
  25. // First bot assistant message
  26. var reply = await chatGPT.GetChatMessageContentAsync(chatHistory);
  27. chatHistory.AddAssistantMessage(reply.Content);
  28. await MessageOutputAsync(chatHistory);
  29. // Second user message
  30. chatHistory.AddUserMessage("I love history and philosophy, I'd like to learn something new about Greece, any suggestion");
  31. await MessageOutputAsync(chatHistory);
  32. // Second bot assistant message
  33. reply = await chatGPT.GetChatMessageContentAsync(chatHistory);
  34. chatHistory.AddAssistantMessage(reply.Content);
  35. await MessageOutputAsync(chatHistory);
  36. }
  37. /// <summary>
  38. /// Outputs the last message of the chat history
  39. /// </summary>
  40. private static Task MessageOutputAsync(Microsoft.SemanticKernel.ChatCompletion.ChatHistory chatHistory)
  41. {
  42. var message = chatHistory.Last();
  43. Console.WriteLine($"{message.Role}: {message.Content}");
  44. Console.WriteLine("------------------------");
  45. return Task.CompletedTask;
  46. }
  47. }
  48. }