| | | 1 | | using System.Net.Http.Json; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using System.Text.Json.Serialization; |
| | | 4 | | |
| | | 5 | | namespace NexusLabs.Needlr.AgentFramework.Langfuse; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Minimal typed transport over the Langfuse public REST API (<c>/api/public/*</c>). Backs the |
| | | 9 | | /// dataset, experiment, score-config, and comment features. Authenticates with HTTP Basic auth and |
| | | 10 | | /// turns non-success responses into <see cref="LangfuseException"/>; per-feature mapping and |
| | | 11 | | /// failure policy live in the recorders that compose it. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <remarks> |
| | | 14 | | /// This is deliberately separate from <see cref="LangfuseScoreApiClient"/>, which predates it and |
| | | 15 | | /// owns the hot score-ingestion path. The underlying <see cref="HttpClient"/> is owned by the |
| | | 16 | | /// caller and disposed with it. |
| | | 17 | | /// </remarks> |
| | | 18 | | internal sealed class LangfuseApiClient |
| | | 19 | | { |
| | 1 | 20 | | private static readonly JsonSerializerOptions SerializerOptions = new() |
| | 1 | 21 | | { |
| | 1 | 22 | | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| | 1 | 23 | | DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, |
| | 1 | 24 | | }; |
| | | 25 | | |
| | | 26 | | private readonly HttpClient _httpClient; |
| | | 27 | | private readonly Uri _baseUrl; |
| | | 28 | | |
| | 16 | 29 | | public LangfuseApiClient(HttpClient httpClient, Uri baseUrl, string authorizationHeaderValue) |
| | | 30 | | { |
| | 16 | 31 | | ArgumentNullException.ThrowIfNull(httpClient); |
| | 16 | 32 | | ArgumentNullException.ThrowIfNull(baseUrl); |
| | 16 | 33 | | ArgumentException.ThrowIfNullOrWhiteSpace(authorizationHeaderValue); |
| | | 34 | | |
| | 16 | 35 | | _httpClient = httpClient; |
| | 16 | 36 | | _baseUrl = baseUrl; |
| | | 37 | | |
| | 16 | 38 | | if (_httpClient.DefaultRequestHeaders.Authorization is null) |
| | | 39 | | { |
| | 15 | 40 | | var space = authorizationHeaderValue.IndexOf(' '); |
| | 15 | 41 | | _httpClient.DefaultRequestHeaders.Authorization = space > 0 |
| | 15 | 42 | | ? new System.Net.Http.Headers.AuthenticationHeaderValue( |
| | 15 | 43 | | authorizationHeaderValue[..space], |
| | 15 | 44 | | authorizationHeaderValue[(space + 1)..]) |
| | 15 | 45 | | : new System.Net.Http.Headers.AuthenticationHeaderValue(authorizationHeaderValue); |
| | | 46 | | } |
| | 16 | 47 | | } |
| | | 48 | | |
| | | 49 | | /// <summary>Sends a POST and ignores the response body.</summary> |
| | | 50 | | /// <typeparam name="TRequest">The request payload type.</typeparam> |
| | | 51 | | /// <param name="relativePath">The API path relative to the base URL (no leading slash).</param> |
| | | 52 | | /// <param name="payload">The request payload, serialized as camelCase JSON.</param> |
| | | 53 | | /// <param name="cancellationToken">A cancellation token.</param> |
| | | 54 | | /// <exception cref="LangfuseException">The request failed or returned a non-success status.</exception> |
| | | 55 | | public async Task PostAsync<TRequest>(string relativePath, TRequest payload, CancellationToken cancellationToken) |
| | | 56 | | { |
| | 12 | 57 | | using var response = await SendAsync(HttpMethod.Post, relativePath, payload, cancellationToken) |
| | 12 | 58 | | .ConfigureAwait(false); |
| | 9 | 59 | | } |
| | | 60 | | |
| | | 61 | | /// <summary>Sends a POST and deserializes the response body.</summary> |
| | | 62 | | /// <typeparam name="TRequest">The request payload type.</typeparam> |
| | | 63 | | /// <typeparam name="TResponse">The response type.</typeparam> |
| | | 64 | | /// <param name="relativePath">The API path relative to the base URL (no leading slash).</param> |
| | | 65 | | /// <param name="payload">The request payload, serialized as camelCase JSON.</param> |
| | | 66 | | /// <param name="cancellationToken">A cancellation token.</param> |
| | | 67 | | /// <returns>The deserialized response, or <see langword="null"/> when the body is empty.</returns> |
| | | 68 | | /// <exception cref="LangfuseException">The request failed or returned a non-success status.</exception> |
| | | 69 | | public async Task<TResponse?> PostAsync<TRequest, TResponse>(string relativePath, TRequest payload, CancellationToke |
| | | 70 | | { |
| | 1 | 71 | | using var response = await SendAsync(HttpMethod.Post, relativePath, payload, cancellationToken) |
| | 1 | 72 | | .ConfigureAwait(false); |
| | 1 | 73 | | return await ReadAsync<TResponse>(response, cancellationToken).ConfigureAwait(false); |
| | 1 | 74 | | } |
| | | 75 | | |
| | | 76 | | /// <summary>Sends a GET and deserializes the response body.</summary> |
| | | 77 | | /// <typeparam name="TResponse">The response type.</typeparam> |
| | | 78 | | /// <param name="relativePath">The API path relative to the base URL (no leading slash).</param> |
| | | 79 | | /// <param name="cancellationToken">A cancellation token.</param> |
| | | 80 | | /// <returns>The deserialized response, or <see langword="null"/> when the body is empty.</returns> |
| | | 81 | | /// <exception cref="LangfuseException">The request failed or returned a non-success status.</exception> |
| | | 82 | | public async Task<TResponse?> GetAsync<TResponse>(string relativePath, CancellationToken cancellationToken) |
| | | 83 | | { |
| | 7 | 84 | | using var response = await SendAsync<object?>(HttpMethod.Get, relativePath, payload: null, allowNotFound: false, |
| | 7 | 85 | | .ConfigureAwait(false); |
| | 7 | 86 | | return await ReadAsync<TResponse>(response, cancellationToken).ConfigureAwait(false); |
| | 7 | 87 | | } |
| | | 88 | | |
| | | 89 | | /// <summary> |
| | | 90 | | /// Sends a GET and deserializes the body, returning <see langword="null"/> on <c>404 Not |
| | | 91 | | /// Found</c> instead of throwing. Used for existence checks (for example "does this dataset |
| | | 92 | | /// already exist?"). |
| | | 93 | | /// </summary> |
| | | 94 | | /// <typeparam name="TResponse">The response type.</typeparam> |
| | | 95 | | /// <param name="relativePath">The API path relative to the base URL (no leading slash).</param> |
| | | 96 | | /// <param name="cancellationToken">A cancellation token.</param> |
| | | 97 | | /// <returns>The deserialized response, or <see langword="null"/> when not found or empty.</returns> |
| | | 98 | | /// <exception cref="LangfuseException">The request failed or returned a non-success status other than 404.</excepti |
| | | 99 | | public async Task<TResponse?> GetOrDefaultAsync<TResponse>(string relativePath, CancellationToken cancellationToken) |
| | | 100 | | { |
| | 2 | 101 | | using var response = await SendAsync<object?>(HttpMethod.Get, relativePath, payload: null, allowNotFound: true, |
| | 2 | 102 | | .ConfigureAwait(false); |
| | | 103 | | |
| | 2 | 104 | | return response.StatusCode is System.Net.HttpStatusCode.NotFound |
| | 2 | 105 | | ? default |
| | 2 | 106 | | : await ReadAsync<TResponse>(response, cancellationToken).ConfigureAwait(false); |
| | 2 | 107 | | } |
| | | 108 | | |
| | | 109 | | private async Task<HttpResponseMessage> SendAsync<TRequest>( |
| | | 110 | | HttpMethod method, |
| | | 111 | | string relativePath, |
| | | 112 | | TRequest payload, |
| | | 113 | | CancellationToken cancellationToken) |
| | 13 | 114 | | => await SendAsync(method, relativePath, payload, allowNotFound: false, cancellationToken).ConfigureAwait(false) |
| | | 115 | | |
| | | 116 | | private async Task<HttpResponseMessage> SendAsync<TRequest>( |
| | | 117 | | HttpMethod method, |
| | | 118 | | string relativePath, |
| | | 119 | | TRequest payload, |
| | | 120 | | bool allowNotFound, |
| | | 121 | | CancellationToken cancellationToken) |
| | | 122 | | { |
| | 22 | 123 | | ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); |
| | | 124 | | |
| | 22 | 125 | | var uri = new Uri(_baseUrl, relativePath); |
| | 22 | 126 | | using var request = new HttpRequestMessage(method, uri); |
| | 22 | 127 | | if (payload is not null) |
| | | 128 | | { |
| | 13 | 129 | | request.Content = JsonContent.Create(payload, mediaType: null, SerializerOptions); |
| | | 130 | | } |
| | | 131 | | |
| | | 132 | | HttpResponseMessage response; |
| | | 133 | | try |
| | | 134 | | { |
| | 22 | 135 | | response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); |
| | 22 | 136 | | } |
| | 0 | 137 | | catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) |
| | | 138 | | { |
| | 0 | 139 | | throw new LangfuseException($"Langfuse request {method} '{uri}' failed.", ex); |
| | | 140 | | } |
| | | 141 | | |
| | 22 | 142 | | if (response.IsSuccessStatusCode |
| | 22 | 143 | | || (allowNotFound && response.StatusCode is System.Net.HttpStatusCode.NotFound)) |
| | | 144 | | { |
| | 19 | 145 | | return response; |
| | | 146 | | } |
| | | 147 | | |
| | 3 | 148 | | var status = (int)response.StatusCode; |
| | 3 | 149 | | var reason = response.ReasonPhrase; |
| | 3 | 150 | | var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); |
| | 3 | 151 | | response.Dispose(); |
| | | 152 | | |
| | 3 | 153 | | throw new LangfuseException( |
| | 3 | 154 | | $"Langfuse rejected {method} '{uri}' with status {status} ({reason}): {body}"); |
| | 19 | 155 | | } |
| | | 156 | | |
| | | 157 | | private static async Task<TResponse?> ReadAsync<TResponse>(HttpResponseMessage response, CancellationToken cancellat |
| | | 158 | | { |
| | 9 | 159 | | if (response.Content.Headers.ContentLength is 0) |
| | | 160 | | { |
| | 0 | 161 | | return default; |
| | | 162 | | } |
| | | 163 | | |
| | 9 | 164 | | return await response.Content |
| | 9 | 165 | | .ReadFromJsonAsync<TResponse>(SerializerOptions, cancellationToken) |
| | 9 | 166 | | .ConfigureAwait(false); |
| | 9 | 167 | | } |
| | | 168 | | } |