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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System.Security.Cryptography;
  2. using LLama.Common;
  3. using Microsoft.SemanticKernel.AI.ChatCompletion;
  4. using LLamaSharp.SemanticKernel.ChatCompletion;
  5. namespace LLama.Examples.Examples
  6. {
  7. public class SemanticKernelChat
  8. {
  9. public static async Task Run()
  10. {
  11. Console.WriteLine("Example from: https://github.com/microsoft/semantic-kernel/blob/main/dotnet/README.md");
  12. Console.Write("Please input your model path: ");
  13. var modelPath = Console.ReadLine();
  14. // Load weights into memory
  15. var parameters = new ModelParams(modelPath);
  16. using var model = LLamaWeights.LoadFromFile(parameters);
  17. using var context = model.CreateContext(parameters);
  18. var ex = new InteractiveExecutor(context);
  19. var chatGPT = new LLamaSharpChatCompletion(ex);
  20. var chatHistory = chatGPT.CreateNewChat("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. string reply = await chatGPT.GenerateMessageAsync(chatHistory);
  27. chatHistory.AddAssistantMessage(reply);
  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.GenerateMessageAsync(chatHistory);
  34. chatHistory.AddAssistantMessage(reply);
  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.AI.ChatCompletion.ChatHistory chatHistory)
  41. {
  42. var message = chatHistory.Messages.Last();
  43. Console.WriteLine($"{message.Role}: {message.Content}");
  44. Console.WriteLine("------------------------");
  45. return Task.CompletedTask;
  46. }
  47. }
  48. }