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.

GrammarSampling.cs 1.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using LLama.Grammars;
  3. using LLama.Native;
  4. namespace LLama.Sampling.Tokens;
  5. /// <summary>
  6. /// Apply a grammar to prevent sampling tokens which do not match the grammar
  7. /// </summary>
  8. public sealed class GrammarSampling
  9. : ITokenDataProcessor
  10. {
  11. private SafeLLamaGrammarHandle? _handle;
  12. /// <summary>
  13. /// Grammar to use for sampling
  14. /// </summary>
  15. public Grammar? Grammar { get; set; }
  16. /// <summary>
  17. /// Create a new
  18. /// </summary>
  19. /// <param name="grammar"></param>
  20. public GrammarSampling(Grammar grammar)
  21. {
  22. Grammar = grammar;
  23. }
  24. /// <inheritdoc />
  25. public void Reset()
  26. {
  27. _handle?.Dispose();
  28. _handle = null;
  29. }
  30. /// <inheritdoc />
  31. public void ProcessTokens(SafeLLamaContextHandle ctx, LLamaTokenDataArray tokens, ReadOnlySpan<int> lastTokens)
  32. {
  33. // Create a new grammar instance if necessary
  34. _handle ??= Grammar?.CreateInstance();
  35. // Apply it
  36. if (_handle != null)
  37. tokens.ApplyGrammar(ctx, _handle);
  38. }
  39. /// <inheritdoc />
  40. public void AcceptToken(SafeLLamaContextHandle ctx, int token)
  41. {
  42. _handle?.AcceptToken(ctx, token);
  43. }
  44. /// <inheritdoc />
  45. public void Dispose()
  46. {
  47. _handle?.Dispose();
  48. _handle = null;
  49. }
  50. }