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 8.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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 virtual string HistoryToText(ChatHistory history)
  48. {
  49. StringBuilder sb = new();
  50. foreach (var message in history.Messages)
  51. {
  52. if (message.AuthorRole == AuthorRole.User)
  53. {
  54. sb.AppendLine($"{_userName}: {message.Content}");
  55. }
  56. else if (message.AuthorRole == AuthorRole.System)
  57. {
  58. sb.AppendLine($"{_systemName}: {message.Content}");
  59. }
  60. else if (message.AuthorRole == AuthorRole.Unknown)
  61. {
  62. sb.AppendLine($"{_unknownName}: {message.Content}");
  63. }
  64. else if (message.AuthorRole == AuthorRole.Assistant)
  65. {
  66. sb.AppendLine($"{_assistantName}: {message.Content}");
  67. }
  68. }
  69. return sb.ToString();
  70. }
  71. /// <inheritdoc />
  72. public virtual ChatHistory TextToHistory(AuthorRole role, string text)
  73. {
  74. ChatHistory history = new ChatHistory();
  75. history.AddMessage(role, TrimNamesFromText(text, role));
  76. return history;
  77. }
  78. /// <summary>
  79. /// Drop the name at the beginning and the end of the text.
  80. /// </summary>
  81. /// <param name="text"></param>
  82. /// <param name="role"></param>
  83. /// <returns></returns>
  84. public virtual string TrimNamesFromText(string text, AuthorRole role)
  85. {
  86. if (role == AuthorRole.User && text.StartsWith($"{_userName}:"))
  87. {
  88. text = text.Substring($"{_userName}:".Length).TrimStart();
  89. }
  90. else if (role == AuthorRole.Assistant && text.EndsWith($"{_assistantName}:"))
  91. {
  92. text = text.Substring(0, text.Length - $"{_assistantName}:".Length).TrimEnd();
  93. }
  94. if (_isInstructMode && role == AuthorRole.Assistant && text.EndsWith("\n> "))
  95. {
  96. text = text.Substring(0, text.Length - "\n> ".Length).TrimEnd();
  97. }
  98. return text;
  99. }
  100. }
  101. /// <summary>
  102. /// A text input transform that only trims the text.
  103. /// </summary>
  104. public class NaiveTextInputTransform
  105. : ITextTransform
  106. {
  107. /// <inheritdoc />
  108. public string Transform(string text)
  109. {
  110. return text.Trim();
  111. }
  112. }
  113. /// <summary>
  114. /// A no-op text input transform.
  115. /// </summary>
  116. public class EmptyTextOutputStreamTransform
  117. : ITextStreamTransform
  118. {
  119. /// <inheritdoc />
  120. public IAsyncEnumerable<string> TransformAsync(IAsyncEnumerable<string> tokens)
  121. {
  122. return tokens;
  123. }
  124. }
  125. /// <summary>
  126. /// A text output transform that removes the keywords from the response.
  127. /// </summary>
  128. public class KeywordTextOutputStreamTransform : ITextStreamTransform
  129. {
  130. private readonly HashSet<string> _keywords;
  131. private readonly int _maxKeywordLength;
  132. private readonly bool _removeAllMatchedTokens;
  133. /// <summary>
  134. ///
  135. /// </summary>
  136. /// <param name="keywords">Keywords that you want to remove from the response.</param>
  137. /// <param name="redundancyLength">The extra length when searching for the keyword. For example, if your only keyword is "highlight",
  138. /// 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)
  139. /// has already exceeded the maximum length of the keywords (8). On the contrary, setting redundancyLengyh &gt;= 2 leads to successful match.
  140. /// 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>
  141. /// <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>
  142. public KeywordTextOutputStreamTransform(IEnumerable<string> keywords, int redundancyLength = 3, bool removeAllMatchedTokens = false)
  143. {
  144. _keywords = new(keywords);
  145. _maxKeywordLength = _keywords.Max(x => x.Length) + redundancyLength;
  146. _maxKeywordLength = _keywords.Select(x => x.Length).Max() + redundancyLength;
  147. _removeAllMatchedTokens = removeAllMatchedTokens;
  148. }
  149. /// <inheritdoc />
  150. public async IAsyncEnumerable<string> TransformAsync(IAsyncEnumerable<string> tokens)
  151. {
  152. var window = new Queue<string>();
  153. await foreach (var s in tokens)
  154. {
  155. window.Enqueue(s);
  156. var current = string.Join("", window);
  157. if (_keywords.Any(x => current.Contains(x)))
  158. {
  159. var matchedKeyword = _keywords.First(x => current.Contains(x));
  160. int total = window.Count;
  161. for (int i = 0; i < total; i++)
  162. {
  163. window.Dequeue();
  164. }
  165. if (!_removeAllMatchedTokens)
  166. {
  167. yield return current.Replace(matchedKeyword, "");
  168. }
  169. }
  170. if (current.Length >= _maxKeywordLength)
  171. {
  172. int total = window.Count;
  173. for (int i = 0; i < total; i++)
  174. {
  175. yield return window.Dequeue();
  176. }
  177. }
  178. }
  179. int totalCount = window.Count;
  180. for (int i = 0; i < totalCount; i++)
  181. {
  182. yield return window.Dequeue();
  183. }
  184. }
  185. }
  186. }
  187. }