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

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