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.

AntipromptProcessor.cs 2.4 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Collections.Generic;
  3. namespace LLama
  4. {
  5. internal sealed class AntipromptProcessor
  6. {
  7. private int _longestAntiprompt;
  8. private readonly List<string> _antiprompts = new();
  9. private string? _string;
  10. public AntipromptProcessor(IEnumerable<string>? antiprompts = null)
  11. {
  12. if (antiprompts != null)
  13. SetAntiprompts(antiprompts);
  14. }
  15. /// <summary>
  16. /// Add an antiprompt to the collection
  17. /// </summary>
  18. /// <param name="antiprompt"></param>
  19. public void AddAntiprompt(string antiprompt)
  20. {
  21. _antiprompts.Add(antiprompt);
  22. _longestAntiprompt = Math.Max(_longestAntiprompt, antiprompt.Length);
  23. }
  24. /// <summary>
  25. /// Overwrite all current antiprompts with a new set
  26. /// </summary>
  27. /// <param name="antiprompts"></param>
  28. public void SetAntiprompts(IEnumerable<string> antiprompts)
  29. {
  30. _antiprompts.Clear();
  31. _antiprompts.AddRange(antiprompts);
  32. _longestAntiprompt = 0;
  33. foreach (var antiprompt in _antiprompts)
  34. _longestAntiprompt = Math.Max(_longestAntiprompt, antiprompt.Length);
  35. }
  36. /// <summary>
  37. /// Add some text and check if the buffer now ends with any antiprompt
  38. /// </summary>
  39. /// <param name="text"></param>
  40. /// <returns>true if the text buffer ends with any antiprompt</returns>
  41. public bool Add(string text)
  42. {
  43. _string += text;
  44. // When the string gets very long (4x antiprompt length) trim it down (to 2x antiprompt length).
  45. // This trimming leaves a lot of extra characters because two sequences can be considered "equal" in unicode
  46. // even with different numbers of characters. Hopefully there are enough characters here to handle all those weird circumstances!
  47. var maxLength = Math.Max(32, _longestAntiprompt * 4);
  48. var trimLength = Math.Max(16, _longestAntiprompt * 2);
  49. if (_string.Length > maxLength)
  50. _string = _string.Substring(_string.Length - trimLength);
  51. foreach (var antiprompt in _antiprompts)
  52. if (_string.EndsWith(antiprompt, StringComparison.CurrentCulture))
  53. return true;
  54. return false;
  55. }
  56. }
  57. }