using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.CompilerServices; using System.Text; using System.Text.Json; using System.IO; namespace Moli.Desktop.Llm; public sealed class OpenAICompatibleAdapter : ILlmProviderAdapter { private readonly HttpClient _httpClient; private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); public OpenAICompatibleAdapter(HttpClient httpClient) { _httpClient = httpClient; } public string Provider => "openai-compatible"; public async IAsyncEnumerable StreamAsync( LlmProviderRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default) { using var httpRequest = new HttpRequestMessage(HttpMethod.Post, request.Model.Endpoint); if (!string.IsNullOrWhiteSpace(request.ApiKey)) { httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", request.ApiKey); } var payload = new { model = request.Model.ApiModel, messages = request.Messages.Select(message => new { role = message.Role, content = message.Content }).ToArray(), temperature = request.Options.Temperature ?? request.Model.RequestDefaults.Temperature, max_tokens = request.Options.MaxTokens ?? request.Model.RequestDefaults.MaxTokens, stream = request.Model.SupportsStreaming }; httpRequest.Content = new StringContent(JsonSerializer.Serialize(payload, _jsonOptions), Encoding.UTF8, "application/json"); using var response = await _httpClient.SendAsync( httpRequest, HttpCompletionOption.ResponseHeadersRead, 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 reader = new StreamReader(stream, Encoding.UTF8); while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line) { cancellationToken.ThrowIfCancellationRequested(); if (string.IsNullOrWhiteSpace(line) || !line.StartsWith("data:", StringComparison.OrdinalIgnoreCase)) { continue; } var data = line["data:".Length..].Trim(); if (data == "[DONE]") { yield return new LlmProviderChunk { IsCompleted = true }; yield break; } LlmProviderChunk? chunk; try { chunk = ParseChunk(data); } catch (JsonException ex) { throw new LlmProviderException(LlmErrorCodes.StreamParseFailed, "Failed to parse LLM stream chunk.", ex); } if (chunk is not null) { yield return chunk; } } yield return new LlmProviderChunk { IsCompleted = true }; } private LlmProviderChunk? ParseChunk(string data) { using var document = JsonDocument.Parse(data); var root = document.RootElement; if (!root.TryGetProperty("choices", out var choices) || choices.ValueKind != JsonValueKind.Array || choices.GetArrayLength() == 0) { return null; } var first = choices[0]; if (first.TryGetProperty("delta", out var delta) && delta.TryGetProperty("content", out var content) && content.ValueKind == JsonValueKind.String) { return new LlmProviderChunk { Delta = content.GetString() ?? string.Empty }; } if (first.TryGetProperty("message", out var message) && message.TryGetProperty("content", out content) && content.ValueKind == JsonValueKind.String) { return new LlmProviderChunk { Delta = content.GetString() ?? string.Empty, IsCompleted = true }; } if (first.TryGetProperty("finish_reason", out var finishReason) && finishReason.ValueKind != JsonValueKind.Null) { return new LlmProviderChunk { IsCompleted = true }; } return null; } private static string MapStatusCode(HttpStatusCode statusCode) => statusCode switch { HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden => LlmErrorCodes.Unauthorized, (HttpStatusCode)429 => LlmErrorCodes.RateLimited, _ => LlmErrorCodes.EndpointUnavailable }; } public sealed class LlmProviderException : Exception { public LlmProviderException(string code, string message, Exception? innerException = null) : base(message, innerException) { Code = code; } public string Code { get; } }