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