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

2 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. var ex = new StatelessExecutor(model, parameters);
  18. var chatGPT = new LLamaSharpChatCompletion(ex);
  19. var chatHistory = chatGPT.CreateNewChat("This is a conversation between the assistant and the user. \n\n You are a librarian, expert about books. ");
  20. Console.WriteLine("Chat content:");
  21. Console.WriteLine("------------------------");
  22. chatHistory.AddUserMessage("Hi, I'm looking for book suggestions");
  23. await MessageOutputAsync(chatHistory);
  24. // First bot assistant message
  25. string reply = await chatGPT.GenerateMessageAsync(chatHistory);
  26. chatHistory.AddAssistantMessage(reply);
  27. await MessageOutputAsync(chatHistory);
  28. // Second user message
  29. chatHistory.AddUserMessage("I love history and philosophy, I'd like to learn something new about Greece, any suggestion");
  30. await MessageOutputAsync(chatHistory);
  31. // Second bot assistant message
  32. reply = await chatGPT.GenerateMessageAsync(chatHistory);
  33. chatHistory.AddAssistantMessage(reply);
  34. await MessageOutputAsync(chatHistory);
  35. }
  36. /// <summary>
  37. /// Outputs the last message of the chat history
  38. /// </summary>
  39. private static Task MessageOutputAsync(Microsoft.SemanticKernel.AI.ChatCompletion.ChatHistory chatHistory)
  40. {
  41. var message = chatHistory.Last();
  42. Console.WriteLine($"{message.Role}: {message.Content}");
  43. Console.WriteLine("------------------------");
  44. return Task.CompletedTask;
  45. }
  46. }
  47. }