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.md 2.5 kB

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