< Summary

Information
Class: Intentum.AI.OpenAI.OpenAIEmbeddingProvider
Assembly: Intentum.AI.OpenAI
File(s): /home/runner/work/Intentum/Intentum/src/Intentum.AI.OpenAI/OpenAIEmbeddingProvider.cs
Line coverage
90%
Covered lines: 20
Uncovered lines: 2
Coverable lines: 22
Total lines: 50
Line coverage: 90.9%
Branch coverage
50%
Covered branches: 3
Total branches: 6
Branch coverage: 50%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
.ctor(...)100%11100%
Embed(...)100%11100%
EmbedAsync()50%66100%
.ctor(...)100%11100%
.ctor(...)100%11100%
.ctor(...)100%11100%

File(s)

/home/runner/work/Intentum/Intentum/src/Intentum.AI.OpenAI/OpenAIEmbeddingProvider.cs

#LineLine coverage
 1using System.Net.Http.Json;
 2using System.Text.Json.Serialization;
 3using Intentum.AI.Embeddings;
 4using Intentum.AI.Http;
 5using JetBrains.Annotations;
 6
 7namespace Intentum.AI.OpenAI;
 8
 9/// <summary>
 10/// OpenAI embedding provider. Calls the OpenAI embeddings API; on 429 after retries throws <see cref="OpenAIRateLimitEx
 11/// Built-in retry for 429 (up to 5 attempts, respects Retry-After).
 12/// </summary>
 313public sealed class OpenAIEmbeddingProvider(OpenAIOptions options, HttpClient httpClient) : IIntentEmbeddingProvider
 14{
 15    /// <inheritdoc />
 16    public IntentEmbedding Embed(string behaviorKey)
 217        => EmbedAsync(behaviorKey, CancellationToken.None).GetAwaiter().GetResult();
 18
 19    /// <inheritdoc />
 20    public async Task<IntentEmbedding> EmbedAsync(string behaviorKey, CancellationToken cancellationToken = default)
 221    {
 222        options.Validate();
 23
 224        var request = new OpenAIEmbeddingRequest(options.EmbeddingModel, behaviorKey);
 25
 226        var response = await EmbeddingHttpRetryHandler.SendWithRetryAsync(
 227            ct => httpClient.PostAsJsonAsync("embeddings", request, ct),
 028            (retryAfterSec, body) => throw new OpenAIRateLimitException(retryAfterSec, body),
 229            cancellationToken: cancellationToken);
 30
 131        var payload = await response.Content
 132            .ReadFromJsonAsync<OpenAIEmbeddingResponse>(cancellationToken);
 33
 134        var values = payload?.Data.FirstOrDefault()?.Embedding ?? [];
 135        var score = EmbeddingScore.Normalize(values);
 36
 137        return new IntentEmbedding(Source: behaviorKey, Score: score);
 138    }
 39
 40    [UsedImplicitly]
 241    private sealed record OpenAIEmbeddingRequest(
 042        [property: JsonPropertyName("model")] string Model,
 243        [property: JsonPropertyName("input")] string Input);
 44
 145    private sealed record OpenAIEmbeddingResponse(
 246        [property: JsonPropertyName("data")] List<OpenAIEmbeddingData> Data);
 47
 148    private sealed record OpenAIEmbeddingData(
 249        [property: JsonPropertyName("embedding")] List<double> Embedding);
 50}