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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. string modelPath = UserSettings.GetModelPath();
  11. Console.ForegroundColor = ConsoleColor.Yellow;
  12. Console.WriteLine("This example is from: \n" +
  13. "https://github.com/microsoft/semantic-kernel/blob/main/dotnet/samples/KernelSyntaxExamples/Example17_ChatGPT.cs");
  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 " +
  20. "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 " +
  31. "something new about Greece, any suggestion");
  32. await MessageOutputAsync(chatHistory);
  33. // Second bot assistant message
  34. reply = await chatGPT.GetChatMessageContentAsync(chatHistory);
  35. chatHistory.AddAssistantMessage(reply.Content);
  36. await MessageOutputAsync(chatHistory);
  37. }
  38. /// <summary>
  39. /// Outputs the last message of the chat history
  40. /// </summary>
  41. private static Task MessageOutputAsync(Microsoft.SemanticKernel.ChatCompletion.ChatHistory chatHistory)
  42. {
  43. var message = chatHistory.Last();
  44. Console.WriteLine($"{message.Role}: {message.Content}");
  45. Console.WriteLine("------------------------");
  46. return Task.CompletedTask;
  47. }
  48. }
  49. }