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

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