| | | 1 | | using System.ClientModel; |
| | | 2 | | using Microsoft.Extensions.Options; |
| | | 3 | | using OpenAI; |
| | | 4 | | using OpenAI.Embeddings; |
| | | 5 | | |
| | | 6 | | namespace GistBackend.Handlers.AIHandler; |
| | | 7 | | |
| | | 8 | | public interface IEmbeddingClientHandler |
| | | 9 | | { |
| | | 10 | | public Task<float[]> GenerateEmbeddingAsync(string input, CancellationToken ct); |
| | | 11 | | public string Model { get; } |
| | | 12 | | } |
| | | 13 | | |
| | | 14 | | public class EmbeddingClientHandler : IEmbeddingClientHandler |
| | | 15 | | { |
| | | 16 | | private readonly EmbeddingClient _client; |
| | 0 | 17 | | public string Model { get; } |
| | | 18 | | |
| | 0 | 19 | | public EmbeddingClientHandler(IOptions<EmbeddingClientHandlerOptions> options) |
| | | 20 | | { |
| | 0 | 21 | | if (string.IsNullOrWhiteSpace(options.Value.ApiKey)) |
| | 0 | 22 | | throw new ArgumentException("API key is not set in the options."); |
| | 0 | 23 | | Model = options.Value.Model; |
| | 0 | 24 | | _client = options.Value.ProjectId is not null |
| | 0 | 25 | | ? new EmbeddingClient(Model, new ApiKeyCredential(options.Value.ApiKey), |
| | 0 | 26 | | new OpenAIClientOptions { ProjectId = options.Value.ProjectId }) |
| | 0 | 27 | | : new EmbeddingClient(Model, new ApiKeyCredential(options.Value.ApiKey)); |
| | 0 | 28 | | } |
| | | 29 | | |
| | | 30 | | public async Task<float[]> GenerateEmbeddingAsync(string input, CancellationToken ct) |
| | | 31 | | { |
| | 0 | 32 | | var result = await _client.GenerateEmbeddingAsync(input, cancellationToken: ct); |
| | 0 | 33 | | return result.Value.ToFloats().ToArray(); |
| | 0 | 34 | | } |
| | | 35 | | } |
| | | 36 | | |