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.

LLamaSharpTextEmbeddingGeneration.cs 1.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using LLama;
  2. using LLama.Common;
  3. using Microsoft.SemanticKernel.AI.Embeddings;
  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. /// <summary>
  12. /// Provides text embedding generation for LLamaSharp.
  13. /// </summary>
  14. public class LLamaSharpTextEmbeddingGeneration : ITextEmbeddingGeneration, IDisposable
  15. {
  16. private readonly LLamaSharpConfig _config;
  17. private readonly LLamaEmbedder _embedder;
  18. private readonly LLamaWeights _weights;
  19. /// <summary>
  20. /// Initializes a new instance of the <see cref="LLamaSharpTextEmbeddingGeneration"/> class.
  21. /// </summary>
  22. /// <param name="config">The configuration for LLamaSharp.</param>
  23. public LLamaSharpTextEmbeddingGeneration(LLamaSharpConfig config)
  24. {
  25. this._config = config;
  26. var @params = new ModelParams(_config.ModelPath);
  27. _weights = LLamaWeights.LoadFromFile(@params);
  28. _embedder = new LLamaEmbedder(_weights, @params);
  29. }
  30. /// <inheritdoc/>
  31. public void Dispose()
  32. {
  33. _embedder.Dispose();
  34. _weights.Dispose();
  35. }
  36. /// <inheritdoc/>
  37. public Task<IList<ReadOnlyMemory<float>>> GenerateEmbeddingsAsync(IList<string> data, CancellationToken cancellationToken = default)
  38. {
  39. IList<ReadOnlyMemory<float>> results = new List<ReadOnlyMemory<float>>();
  40. foreach (var d in data)
  41. {
  42. var embeddings = _embedder.GetEmbeddings(d);
  43. results.Add(new ReadOnlyMemory<float>(embeddings));
  44. }
  45. return Task.FromResult(results);
  46. }
  47. }
  48. }