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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Security.Cryptography;
  2. using LLama.Common;
  3. using Microsoft.SemanticKernel.AI.ChatCompletion;
  4. using LLamaSharp.SemanticKernel.ChatCompletion;
  5. namespace LLama.Examples.NewVersion
  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. {
  17. Seed = unchecked((uint)RandomNumberGenerator.GetInt32(int.MaxValue)),
  18. };
  19. using var model = LLamaWeights.LoadFromFile(parameters);
  20. using var context = model.CreateContext(parameters);
  21. var ex = new InteractiveExecutor(context);
  22. var chatGPT = new LLamaSharpChatCompletion(ex);
  23. var chatHistory = chatGPT.CreateNewChat("You are a librarian, expert about books");
  24. Console.WriteLine("Chat content:");
  25. Console.WriteLine("------------------------");
  26. chatHistory.AddUserMessage("Hi, I'm looking for book suggestions");
  27. await MessageOutputAsync(chatHistory);
  28. // First bot assistant message
  29. string reply = await chatGPT.GenerateMessageAsync(chatHistory);
  30. chatHistory.AddAssistantMessage(reply);
  31. await MessageOutputAsync(chatHistory);
  32. // Second user message
  33. chatHistory.AddUserMessage("I love history and philosophy, I'd like to learn something new about Greece, any suggestion");
  34. await MessageOutputAsync(chatHistory);
  35. // Second bot assistant message
  36. reply = await chatGPT.GenerateMessageAsync(chatHistory);
  37. chatHistory.AddAssistantMessage(reply);
  38. await MessageOutputAsync(chatHistory);
  39. }
  40. /// <summary>
  41. /// Outputs the last message of the chat history
  42. /// </summary>
  43. private static Task MessageOutputAsync(Microsoft.SemanticKernel.AI.ChatCompletion.ChatHistory chatHistory)
  44. {
  45. var message = chatHistory.Messages.Last();
  46. Console.WriteLine($"{message.Role}: {message.Content}");
  47. Console.WriteLine("------------------------");
  48. return Task.CompletedTask;
  49. }
  50. }
  51. }