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.

ConversationExtensions.cs 2.2 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. namespace LLama.Batched;
  3. /// <summary>
  4. /// Extension method for <see cref="Conversation"/>
  5. /// </summary>
  6. public static class ConversationExtensions
  7. {
  8. /// <summary>
  9. /// Rewind a <see cref="Conversation"/> back to an earlier state by removing tokens from the end
  10. /// </summary>
  11. /// <param name="conversation">The conversation to rewind</param>
  12. /// <param name="tokens">The number of tokens to rewind</param>
  13. /// <exception cref="ArgumentOutOfRangeException">Thrown if `tokens` parameter is larger than TokenCount</exception>
  14. public static void Rewind(this Conversation conversation, int tokens)
  15. {
  16. if (tokens > conversation.TokenCount)
  17. throw new ArgumentOutOfRangeException(nameof(tokens), "Cannot rewind more than the total number of tokens");
  18. conversation.Modify((end, kv) =>
  19. {
  20. // Remove those tokens from KV
  21. kv.Remove(end.Value - tokens, tokens);
  22. // Return adjusted end position
  23. return end.Value - tokens;
  24. });
  25. }
  26. /// <summary>
  27. /// Shift all tokens over to the left, removing "count" tokens from the start and shifting everything over.
  28. /// Leaves "keep" tokens at the start completely untouched. This can be used to free up space when the context
  29. /// gets full, keeping the prompt at the start intact.
  30. /// </summary>
  31. /// <param name="conversation">The conversation to rewind</param>
  32. /// <param name="count">How much to shift tokens over by</param>
  33. /// <param name="keep">The number of tokens at the start which should <b>not</b> be shifted</param>
  34. public static void ShiftLeft(this Conversation conversation, int count, int keep)
  35. {
  36. // Given a setup like this (shift=5, keep=3):
  37. //
  38. // AAABBBBBCCCCCCCCC...
  39. //
  40. // We want to remove all the B's, shift all the C's and leave all the A's untouched
  41. conversation.Modify((end, kv) =>
  42. {
  43. // Remove the B's
  44. kv.Remove(keep, count);
  45. // Shift the C's
  46. kv.Shift(keep + count, end, -count);
  47. // Update total count
  48. return end.Value - count;
  49. });
  50. }
  51. }