| | | 1 | | namespace NexusLabs.Needlr.AgentFramework.Langfuse; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Default <see cref="ILangfuseScoreConfigClient"/> that ensures score configs via the shared |
| | | 5 | | /// <see cref="LangfuseApiClient"/>. Existence is checked by paging |
| | | 6 | | /// <c>GET /api/public/score-configs</c> and matching on name; a config is created only when absent. |
| | | 7 | | /// </summary> |
| | | 8 | | internal sealed class LangfuseScoreConfigClient : ILangfuseScoreConfigClient |
| | | 9 | | { |
| | | 10 | | private const int PageSize = 100; |
| | | 11 | | |
| | | 12 | | private readonly LangfuseApiClient _apiClient; |
| | | 13 | | |
| | 4 | 14 | | public LangfuseScoreConfigClient(LangfuseApiClient apiClient) |
| | | 15 | | { |
| | 4 | 16 | | ArgumentNullException.ThrowIfNull(apiClient); |
| | | 17 | | |
| | 4 | 18 | | _apiClient = apiClient; |
| | 4 | 19 | | } |
| | | 20 | | |
| | | 21 | | /// <inheritdoc /> |
| | 0 | 22 | | public bool IsEnabled => true; |
| | | 23 | | |
| | | 24 | | /// <inheritdoc /> |
| | | 25 | | public async Task EnsureScoreConfigAsync(LangfuseScoreConfig config, CancellationToken cancellationToken = default) |
| | | 26 | | { |
| | 3 | 27 | | ArgumentNullException.ThrowIfNull(config); |
| | 3 | 28 | | ArgumentException.ThrowIfNullOrWhiteSpace(config.Name); |
| | | 29 | | |
| | 3 | 30 | | if (await ConfigExistsAsync(config.Name, cancellationToken).ConfigureAwait(false)) |
| | | 31 | | { |
| | 1 | 32 | | return; |
| | | 33 | | } |
| | | 34 | | |
| | 2 | 35 | | await _apiClient |
| | 2 | 36 | | .PostAsync("api/public/score-configs", LangfuseScoreConfigRequest.From(config), cancellationToken) |
| | 2 | 37 | | .ConfigureAwait(false); |
| | 3 | 38 | | } |
| | | 39 | | |
| | | 40 | | private async Task<bool> ConfigExistsAsync(string name, CancellationToken cancellationToken) |
| | | 41 | | { |
| | 3 | 42 | | var page = 1; |
| | 0 | 43 | | while (true) |
| | | 44 | | { |
| | 3 | 45 | | var response = await _apiClient |
| | 3 | 46 | | .GetAsync<LangfuseScoreConfigsResponse>( |
| | 3 | 47 | | $"api/public/score-configs?page={page}&limit={PageSize}", |
| | 3 | 48 | | cancellationToken) |
| | 3 | 49 | | .ConfigureAwait(false); |
| | | 50 | | |
| | 3 | 51 | | if (response?.Data is not { Count: > 0 } items) |
| | | 52 | | { |
| | 2 | 53 | | return false; |
| | | 54 | | } |
| | | 55 | | |
| | 2 | 56 | | if (items.Any(c => string.Equals(c.Name, name, StringComparison.Ordinal))) |
| | | 57 | | { |
| | 1 | 58 | | return true; |
| | | 59 | | } |
| | | 60 | | |
| | 0 | 61 | | if (response.Meta is not { } meta || page >= meta.TotalPages) |
| | | 62 | | { |
| | 0 | 63 | | return false; |
| | | 64 | | } |
| | | 65 | | |
| | 0 | 66 | | page++; |
| | | 67 | | } |
| | 3 | 68 | | } |
| | | 69 | | } |