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.

LlamaSharpTextGeneration.cs 2.0 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using LLama;
  2. using LLama.Common;
  3. using Microsoft.SemanticMemory.AI;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace LLamaSharp.KernelMemory
  10. {
  11. public class LlamaSharpTextGeneration : ITextGeneration, IDisposable
  12. {
  13. private readonly LlamaSharpConfig _config;
  14. private readonly LLamaWeights _weights;
  15. private readonly InstructExecutor _executor;
  16. private readonly LLamaContext _context;
  17. public LlamaSharpTextGeneration(LlamaSharpConfig config)
  18. {
  19. this._config = config;
  20. var parameters = new ModelParams(config.ModelPath)
  21. {
  22. ContextSize = config?.ContextSize ?? 1024,
  23. Seed = config?.Seed ?? 0,
  24. GpuLayerCount = config?.GpuLayerCount ?? 20
  25. };
  26. _weights = LLamaWeights.LoadFromFile(parameters);
  27. _context = _weights.CreateContext(parameters);
  28. _executor = new InstructExecutor(_context);
  29. }
  30. public void Dispose()
  31. {
  32. _context.Dispose();
  33. _weights.Dispose();
  34. }
  35. public IAsyncEnumerable<string> GenerateTextAsync(string prompt, TextGenerationOptions options, CancellationToken cancellationToken = default)
  36. {
  37. return _executor.InferAsync(prompt, OptionsToParams(options), cancellationToken: cancellationToken);
  38. }
  39. private static InferenceParams OptionsToParams(TextGenerationOptions options)
  40. {
  41. return new InferenceParams()
  42. {
  43. AntiPrompts = options.StopSequences,
  44. Temperature = (float)options.Temperature,
  45. MaxTokens = options.MaxTokens ?? 1024,
  46. FrequencyPenalty = (float)options.FrequencyPenalty,
  47. PresencePenalty = (float)options.PresencePenalty,
  48. TopP = (float)options.TopP,
  49. };
  50. }
  51. }
  52. }