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

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