| | |
| | | LlmProviderRequest request, |
| | | [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| | | { |
| | | using var httpRequest = new HttpRequestMessage(HttpMethod.Post, request.Model.Endpoint); |
| | | var chatUrl = request.Model.GetChatCompletionsUrl(); |
| | | if (!LlmOpenAiUrls.IsAbsoluteHttpUrl(chatUrl)) |
| | | { |
| | | throw new LlmProviderException(LlmErrorCodes.RequestInvalid, "Model baseUrl must be an absolute HTTP or HTTPS URL."); |
| | | } |
| | | |
| | | using var httpRequest = new HttpRequestMessage(HttpMethod.Post, chatUrl); |
| | | if (!string.IsNullOrWhiteSpace(request.ApiKey)) |
| | | { |
| | | httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", request.ApiKey); |
| | |
| | | yield return new LlmProviderChunk { IsCompleted = true }; |
| | | } |
| | | |
| | | public async Task<IReadOnlyList<string>> ListModelIdsAsync( |
| | | string baseUrl, |
| | | string? apiKey, |
| | | CancellationToken cancellationToken = default) |
| | | { |
| | | var modelsUrl = LlmOpenAiUrls.ToModelsUrl(baseUrl); |
| | | if (!LlmOpenAiUrls.IsAbsoluteHttpUrl(modelsUrl)) |
| | | { |
| | | throw new LlmProviderException(LlmErrorCodes.RequestInvalid, "Provider baseUrl must be an absolute HTTP or HTTPS URL."); |
| | | } |
| | | |
| | | using var httpRequest = new HttpRequestMessage(HttpMethod.Get, modelsUrl); |
| | | if (!string.IsNullOrWhiteSpace(apiKey)) |
| | | { |
| | | httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey); |
| | | } |
| | | |
| | | using var response = await _httpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); |
| | | if (!response.IsSuccessStatusCode) |
| | | { |
| | | throw new LlmProviderException(MapStatusCode(response.StatusCode), $"LLM provider returned {(int)response.StatusCode}."); |
| | | } |
| | | |
| | | await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); |
| | | using var document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); |
| | | if (!document.RootElement.TryGetProperty("data", out var data) || data.ValueKind != JsonValueKind.Array) |
| | | { |
| | | return []; |
| | | } |
| | | |
| | | return data.EnumerateArray() |
| | | .Select(ReadModelId) |
| | | .Where(id => !string.IsNullOrWhiteSpace(id)) |
| | | .Select(id => id!) |
| | | .ToList(); |
| | | } |
| | | |
| | | private static string? ReadModelId(JsonElement item) |
| | | { |
| | | if (item.ValueKind == JsonValueKind.Object && |
| | | item.TryGetProperty("id", out var id) && |
| | | id.ValueKind == JsonValueKind.String) |
| | | { |
| | | return id.GetString(); |
| | | } |
| | | |
| | | return null; |
| | | } |
| | | |
| | | private LlmProviderChunk? ParseChunk(string data) |
| | | { |
| | | using var document = JsonDocument.Parse(data); |