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.

ChatSession.cs 1.7 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. namespace LLama.OldVersion
  6. {
  7. public class ChatSession<T> where T : IChatModel
  8. {
  9. IChatModel _model;
  10. List<ChatMessageRecord> History { get; } = new List<ChatMessageRecord>();
  11. public ChatSession(T model)
  12. {
  13. _model = model;
  14. }
  15. public IEnumerable<string> Chat(string text, string? prompt = null, string encoding = "UTF-8")
  16. {
  17. History.Add(new ChatMessageRecord(new ChatCompletionMessage(ChatRole.Human, text), DateTime.Now));
  18. string totalResponse = "";
  19. foreach (var response in _model.Chat(text, prompt, encoding))
  20. {
  21. totalResponse += response;
  22. yield return response;
  23. }
  24. History.Add(new ChatMessageRecord(new ChatCompletionMessage(ChatRole.Assistant, totalResponse), DateTime.Now));
  25. }
  26. public ChatSession<T> WithPrompt(string prompt, string encoding = "UTF-8")
  27. {
  28. _model.InitChatPrompt(prompt, encoding);
  29. return this;
  30. }
  31. public ChatSession<T> WithPromptFile(string promptFilename, string encoding = "UTF-8")
  32. {
  33. return WithPrompt(File.ReadAllText(promptFilename), encoding);
  34. }
  35. /// <summary>
  36. /// Set the keywords to split the return value of chat AI.
  37. /// </summary>
  38. /// <param name="antiprompt"></param>
  39. /// <returns></returns>
  40. public ChatSession<T> WithAntiprompt(string[] antiprompt)
  41. {
  42. _model.InitChatAntiprompt(antiprompt);
  43. return this;
  44. }
  45. }
  46. }