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.

LLamaTransforms.cs 9.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. using LLama.Abstractions;
  2. using LLama.Common;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. namespace LLama
  7. {
  8. /// <summary>
  9. /// A class that contains all the transforms provided internally by LLama.
  10. /// </summary>
  11. public class LLamaTransforms
  12. {
  13. /// <summary>
  14. /// The default history transform.
  15. /// Uses plain text with the following format:
  16. /// [Author]: [Message]
  17. /// </summary>
  18. public class DefaultHistoryTransform : IHistoryTransform
  19. {
  20. private const string defaultUserName = "User";
  21. private const string defaultAssistantName = "Assistant";
  22. private const string defaultSystemName = "System";
  23. private const string defaultUnknownName = "??";
  24. private readonly string _userName;
  25. private readonly string _assistantName;
  26. private readonly string _systemName;
  27. private readonly string _unknownName;
  28. private readonly bool _isInstructMode;
  29. /// <summary>
  30. ///
  31. /// </summary>
  32. /// <param name="userName"></param>
  33. /// <param name="assistantName"></param>
  34. /// <param name="systemName"></param>
  35. /// <param name="unknownName"></param>
  36. /// <param name="isInstructMode"></param>
  37. public DefaultHistoryTransform(string? userName = null, string? assistantName = null,
  38. string? systemName = null, string? unknownName = null, bool isInstructMode = false)
  39. {
  40. _userName = userName ?? defaultUserName;
  41. _assistantName = assistantName ?? defaultAssistantName;
  42. _systemName = systemName ?? defaultSystemName;
  43. _unknownName = unknownName ?? defaultUnknownName;
  44. _isInstructMode = isInstructMode;
  45. }
  46. /// <inheritdoc />
  47. public IHistoryTransform Clone()
  48. {
  49. return new DefaultHistoryTransform(_userName, _assistantName, _systemName, _unknownName, _isInstructMode);
  50. }
  51. /// <inheritdoc />
  52. public virtual string HistoryToText(ChatHistory history)
  53. {
  54. StringBuilder sb = new();
  55. foreach (var message in history.Messages)
  56. {
  57. if (message.AuthorRole == AuthorRole.User)
  58. {
  59. sb.AppendLine($"{_userName}: {message.Content}");
  60. }
  61. else if (message.AuthorRole == AuthorRole.System)
  62. {
  63. sb.AppendLine($"{_systemName}: {message.Content}");
  64. }
  65. else if (message.AuthorRole == AuthorRole.Unknown)
  66. {
  67. sb.AppendLine($"{_unknownName}: {message.Content}");
  68. }
  69. else if (message.AuthorRole == AuthorRole.Assistant)
  70. {
  71. sb.AppendLine($"{_assistantName}: {message.Content}");
  72. }
  73. }
  74. return sb.ToString();
  75. }
  76. /// <inheritdoc />
  77. public virtual ChatHistory TextToHistory(AuthorRole role, string text)
  78. {
  79. ChatHistory history = new ChatHistory();
  80. history.AddMessage(role, TrimNamesFromText(text, role));
  81. return history;
  82. }
  83. /// <summary>
  84. /// Drop the name at the beginning and the end of the text.
  85. /// </summary>
  86. /// <param name="text"></param>
  87. /// <param name="role"></param>
  88. /// <returns></returns>
  89. public virtual string TrimNamesFromText(string text, AuthorRole role)
  90. {
  91. if (role == AuthorRole.User && text.StartsWith($"{_userName}:"))
  92. {
  93. text = text.Substring($"{_userName}:".Length).TrimStart();
  94. }
  95. else if (role == AuthorRole.Assistant && text.EndsWith($"{_assistantName}:"))
  96. {
  97. text = text.Substring(0, text.Length - $"{_assistantName}:".Length).TrimEnd();
  98. }
  99. if (_isInstructMode && role == AuthorRole.Assistant && text.EndsWith("\n> "))
  100. {
  101. text = text.Substring(0, text.Length - "\n> ".Length).TrimEnd();
  102. }
  103. return text;
  104. }
  105. }
  106. /// <summary>
  107. /// A text input transform that only trims the text.
  108. /// </summary>
  109. public class NaiveTextInputTransform
  110. : ITextTransform
  111. {
  112. /// <inheritdoc />
  113. public string Transform(string text)
  114. {
  115. return text.Trim();
  116. }
  117. /// <inheritdoc />
  118. public ITextTransform Clone()
  119. {
  120. return new NaiveTextInputTransform();
  121. }
  122. }
  123. /// <summary>
  124. /// A no-op text input transform.
  125. /// </summary>
  126. public class EmptyTextOutputStreamTransform
  127. : ITextStreamTransform
  128. {
  129. /// <inheritdoc />
  130. public IAsyncEnumerable<string> TransformAsync(IAsyncEnumerable<string> tokens)
  131. {
  132. return tokens;
  133. }
  134. /// <inheritdoc />
  135. public ITextStreamTransform Clone()
  136. {
  137. return new EmptyTextOutputStreamTransform();
  138. }
  139. }
  140. /// <summary>
  141. /// A text output transform that removes the keywords from the response.
  142. /// </summary>
  143. public class KeywordTextOutputStreamTransform : ITextStreamTransform
  144. {
  145. private readonly HashSet<string> _keywords;
  146. private readonly int _maxKeywordLength;
  147. private readonly bool _removeAllMatchedTokens;
  148. /// <summary>
  149. ///
  150. /// </summary>
  151. /// <param name="keywords">Keywords that you want to remove from the response.</param>
  152. /// <param name="redundancyLength">The extra length when searching for the keyword. For example, if your only keyword is "highlight",
  153. /// maybe the token you get is "\r\nhighligt". In this condition, if redundancyLength=0, the token cannot be successfully matched because the length of "\r\nhighligt" (10)
  154. /// has already exceeded the maximum length of the keywords (8). On the contrary, setting redundancyLengyh &gt;= 2 leads to successful match.
  155. /// The larger the redundancyLength is, the lower the processing speed. But as an experience, it won't introduce too much performance impact when redundancyLength &lt;= 5 </param>
  156. /// <param name="removeAllMatchedTokens">If set to true, when getting a matched keyword, all the related tokens will be removed. Otherwise only the part of keyword will be removed.</param>
  157. public KeywordTextOutputStreamTransform(IEnumerable<string> keywords, int redundancyLength = 3, bool removeAllMatchedTokens = false)
  158. {
  159. _keywords = new(keywords);
  160. _maxKeywordLength = _keywords.Max(x => x.Length) + redundancyLength;
  161. _maxKeywordLength = _keywords.Select(x => x.Length).Max() + redundancyLength;
  162. _removeAllMatchedTokens = removeAllMatchedTokens;
  163. }
  164. /// <inheritdoc />
  165. public ITextStreamTransform Clone()
  166. {
  167. return new KeywordTextOutputStreamTransform(_keywords, _maxKeywordLength, _removeAllMatchedTokens);
  168. }
  169. /// <inheritdoc />
  170. public async IAsyncEnumerable<string> TransformAsync(IAsyncEnumerable<string> tokens)
  171. {
  172. var window = new Queue<string>();
  173. await foreach (var s in tokens)
  174. {
  175. window.Enqueue(s);
  176. var current = string.Join("", window);
  177. if (_keywords.Any(x => current.Contains(x)))
  178. {
  179. var matchedKeyword = _keywords.First(x => current.Contains(x));
  180. int total = window.Count;
  181. for (int i = 0; i < total; i++)
  182. {
  183. window.Dequeue();
  184. }
  185. if (!_removeAllMatchedTokens)
  186. {
  187. yield return current.Replace(matchedKeyword, "");
  188. }
  189. }
  190. if (current.Length >= _maxKeywordLength)
  191. {
  192. int total = window.Count;
  193. for (int i = 0; i < total; i++)
  194. {
  195. yield return window.Dequeue();
  196. }
  197. }
  198. }
  199. int totalCount = window.Count;
  200. for (int i = 0; i < totalCount; i++)
  201. {
  202. yield return window.Dequeue();
  203. }
  204. }
  205. }
  206. }
  207. }