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.8 kB

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