|
| 1 | +using LLama; |
| 2 | +using LLama.Common; |
| 3 | +using Microsoft.KernelMemory.AI; |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Linq; |
| 7 | +using System.Text; |
| 8 | +using System.Threading.Tasks; |
| 9 | + |
| 10 | +namespace LLamaSharp.KernelMemory |
| 11 | +{ |
| 12 | + /// <summary> |
| 13 | + /// Provides text generation for LLamaSharp. |
| 14 | + /// </summary> |
| 15 | + public class LlamaSharpTextGeneration : ITextGeneration, IDisposable |
| 16 | + { |
| 17 | + private readonly LLamaSharpConfig _config; |
| 18 | + private readonly LLamaWeights _weights; |
| 19 | + private readonly StatelessExecutor _executor; |
| 20 | + private readonly LLamaContext _context; |
| 21 | + |
| 22 | + /// <summary> |
| 23 | + /// Initializes a new instance of the <see cref="LlamaSharpTextGeneration"/> class. |
| 24 | + /// </summary> |
| 25 | + /// <param name="config">The configuration for LLamaSharp.</param> |
| 26 | + public LlamaSharpTextGeneration(LLamaSharpConfig config) |
| 27 | + { |
| 28 | + this._config = config; |
| 29 | + var parameters = new ModelParams(config.ModelPath) |
| 30 | + { |
| 31 | + ContextSize = config?.ContextSize ?? 2048, |
| 32 | + Seed = config?.Seed ?? 0, |
| 33 | + GpuLayerCount = config?.GpuLayerCount ?? 20 |
| 34 | + }; |
| 35 | + _weights = LLamaWeights.LoadFromFile(parameters); |
| 36 | + _context = _weights.CreateContext(parameters); |
| 37 | + _executor = new StatelessExecutor(_weights, parameters); |
| 38 | + } |
| 39 | + |
| 40 | + /// <inheritdoc/> |
| 41 | + public void Dispose() |
| 42 | + { |
| 43 | + _context.Dispose(); |
| 44 | + _weights.Dispose(); |
| 45 | + } |
| 46 | + |
| 47 | + /// <inheritdoc/> |
| 48 | + public IAsyncEnumerable<string> GenerateTextAsync(string prompt, TextGenerationOptions options, CancellationToken cancellationToken = default) |
| 49 | + { |
| 50 | + return _executor.InferAsync(prompt, OptionsToParams(options), cancellationToken: cancellationToken); |
| 51 | + } |
| 52 | + |
| 53 | + private static InferenceParams OptionsToParams(TextGenerationOptions options) |
| 54 | + { |
| 55 | + return new InferenceParams() |
| 56 | + { |
| 57 | + AntiPrompts = options.StopSequences.ToList().AsReadOnly(), |
| 58 | + Temperature = (float)options.Temperature, |
| 59 | + MaxTokens = options.MaxTokens ?? 1024, |
| 60 | + FrequencyPenalty = (float)options.FrequencyPenalty, |
| 61 | + PresencePenalty = (float)options.PresencePenalty, |
| 62 | + TopP = (float)options.TopP, |
| 63 | + }; |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments