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.

ModelSession.cs 2.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using LLama.Abstractions;
  2. using LLama.Web.Common;
  3. namespace LLama.Web.Models
  4. {
  5. public class ModelSession : IDisposable
  6. {
  7. private bool _isFirstInteraction = true;
  8. private ModelOptions _modelOptions;
  9. private PromptOptions _promptOptions;
  10. private ParameterOptions _inferenceOptions;
  11. private ITextStreamTransform _outputTransform;
  12. private ILLamaExecutor _executor;
  13. private CancellationTokenSource _cancellationTokenSource;
  14. public ModelSession(ILLamaExecutor executor, ModelOptions modelOptions, PromptOptions promptOptions, ParameterOptions parameterOptions)
  15. {
  16. _executor = executor;
  17. _modelOptions = modelOptions;
  18. _promptOptions = promptOptions;
  19. _inferenceOptions = parameterOptions;
  20. _inferenceOptions.AntiPrompts = _promptOptions.AntiPrompt?.Concat(_inferenceOptions.AntiPrompts ?? Enumerable.Empty<string>()).Distinct() ?? _inferenceOptions.AntiPrompts;
  21. if (_promptOptions.OutputFilter?.Count > 0)
  22. _outputTransform = new LLamaTransforms.KeywordTextOutputStreamTransform(_promptOptions.OutputFilter, redundancyLength: 5);
  23. }
  24. public IAsyncEnumerable<string> InferAsync(string message, CancellationTokenSource cancellationTokenSource)
  25. {
  26. _cancellationTokenSource = cancellationTokenSource;
  27. if (_isFirstInteraction)
  28. {
  29. _isFirstInteraction = false;
  30. message = _promptOptions.Prompt + message;
  31. }
  32. if (_outputTransform is not null)
  33. return _outputTransform.TransformAsync(_executor.InferAsync(message, _inferenceOptions, _cancellationTokenSource.Token));
  34. return _executor.InferAsync(message, _inferenceOptions, _cancellationTokenSource.Token);
  35. }
  36. public void CancelInfer()
  37. {
  38. _cancellationTokenSource?.Cancel();
  39. }
  40. public bool IsInferCanceled()
  41. {
  42. return _cancellationTokenSource.IsCancellationRequested;
  43. }
  44. public void Dispose()
  45. {
  46. _inferenceOptions = null;
  47. _outputTransform = null;
  48. _executor.Model?.Dispose();
  49. _executor = null;
  50. }
  51. }
  52. }