using System.Collections.Concurrent; 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; using Moli.Desktop.Diagnostics; namespace Moli.Desktop.Llm; public sealed class AiChatClient : IAiChatClient { private readonly HttpClient _httpClient; private readonly IDiagnosticsService _diagnostics; private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); private readonly ConcurrentDictionary _sessionTokens = new(StringComparer.OrdinalIgnoreCase); public AiChatClient(HttpClient httpClient, IDiagnosticsService diagnostics) { _httpClient = httpClient; _diagnostics = diagnostics; } public async Task> GetModelsAsync( LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default) { using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, "/api/chat/models", null, cancellationToken).ConfigureAwait(false); if (!TryGetData(document.RootElement, out var data) || !data.TryGetProperty("models", out var modelsElement) || modelsElement.ValueKind != JsonValueKind.Array) { return []; } var defaultModel = data.TryGetProperty("defaultModel", out var defaultModelElement) ? defaultModelElement.GetString() : null; return modelsElement .EnumerateArray() .Where(item => item.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(item.GetString())) .Select(item => { var id = item.GetString()!; return new LlmModelSummary { Id = id, Label = id == defaultModel ? $"{id} *" : id, Provider = "aichat", SupportsStreaming = true, Enabled = true }; }) .ToList(); } public async Task> GetProjectsAsync( LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default) { try { using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, "/api/projects", null, cancellationToken).ConfigureAwait(false); if (!TryGetProjectsData(document.RootElement, out var data)) { _diagnostics.Record( DiagnosticSeverity.Warning, LlmErrorCodes.AiChatProjectLoadFailed, "AiChat project response did not contain a project array.", new Dictionary { ["baseUrl"] = runtimeConfig.AiChat.BaseUrl }); return []; } return data.EnumerateArray() .Select(ParseProject) .Where(project => project is not null) .Select(project => project!) .ToList(); } catch (AiChatClientException ex) { _diagnostics.Record( DiagnosticSeverity.Warning, ex.Code, "AiChat projects could not be loaded.", new Dictionary { ["baseUrl"] = runtimeConfig.AiChat.BaseUrl, ["exception"] = ex.GetType().Name }); throw; } } public async IAsyncEnumerable StreamChatAsync( LlmChatRequest request, LlmPluginRuntimeConfig runtimeConfig, [EnumeratorCancellation] CancellationToken cancellationToken = default) { JsonDocument? sendDocument = null; LlmErrorEvent? startError = null; try { var message = request.Messages.LastOrDefault(message => string.Equals(message.Role, "user", StringComparison.OrdinalIgnoreCase))?.Content ?? request.Messages.Last().Content; var payload = new { projectId = request.ProjectId, modelName = request.ModelId, message }; sendDocument = await SendJsonAsync(runtimeConfig, HttpMethod.Post, "/api/chat/send", payload, cancellationToken).ConfigureAwait(false); } catch (AiChatClientException ex) { startError = new LlmErrorEvent { RequestId = request.RequestId, Code = ex.Code, Message = ex.Message }; } if (startError is not null) { yield return startError; yield break; } var generationDocument = sendDocument; if (generationDocument is null) { yield return new LlmErrorEvent { RequestId = request.RequestId, Code = LlmErrorCodes.AiChatApiFailed, Message = "AiChat did not return a valid generation stream." }; yield break; } using (generationDocument) { if (!TryGetData(generationDocument.RootElement, out var data) || !data.TryGetProperty("generationId", out var generationIdElement) || !data.TryGetProperty("streamToken", out var streamTokenElement) || string.IsNullOrWhiteSpace(generationIdElement.GetString()) || string.IsNullOrWhiteSpace(streamTokenElement.GetString())) { yield return new LlmErrorEvent { RequestId = request.RequestId, Code = LlmErrorCodes.AiChatApiFailed, Message = "AiChat did not return a valid generation stream." }; yield break; } var path = $"/api/chat/generations/{Uri.EscapeDataString(generationIdElement.GetString()!)}/stream?token={Uri.EscapeDataString(streamTokenElement.GetString()!)}"; await foreach (var streamEvent in StreamAiChatEventsAsync(runtimeConfig, request.RequestId, path, cancellationToken).ConfigureAwait(false)) { yield return streamEvent; } } } public async Task GetMemoryCapabilitiesAsync( LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default) { using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, "/api/auth/me", null, cancellationToken).ConfigureAwait(false); if (!TryGetData(document.RootElement, out var data)) { return new AiChatMemoryCapabilities(); } return new AiChatMemoryCapabilities { CanUseMemory = ReadBool(data, "canUseMemory"), CanViewMemory = ReadBool(data, "canViewMemory"), CanManageMemory = ReadBool(data, "canManageMemory") }; } public async Task GetMemoriesAsync( LlmPluginRuntimeConfig runtimeConfig, AiChatGetMemoriesRequest request, CancellationToken cancellationToken = default) { var query = new List(); if (!string.IsNullOrWhiteSpace(request.Scope)) { query.Add($"scope={Uri.EscapeDataString(request.Scope)}"); } if (!string.IsNullOrWhiteSpace(request.ProjectId)) { query.Add($"projectId={Uri.EscapeDataString(request.ProjectId)}"); } var path = "/api/memories" + (query.Count > 0 ? "?" + string.Join("&", query) : ""); using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, path, null, cancellationToken).ConfigureAwait(false); return CloneData(document); } public async Task CreateMemoryAsync( LlmPluginRuntimeConfig runtimeConfig, AiChatCreateMemoryRequest request, CancellationToken cancellationToken = default) { using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Post, "/api/memories", request, cancellationToken).ConfigureAwait(false); return CloneData(document); } public async Task DeleteMemoryAsync( LlmPluginRuntimeConfig runtimeConfig, string memoryId, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(memoryId)) { throw new AiChatClientException(LlmErrorCodes.RequestInvalid, "memoryId is required."); } using var _ = await SendJsonAsync(runtimeConfig, HttpMethod.Delete, $"/api/memories/{Uri.EscapeDataString(memoryId)}", null, cancellationToken).ConfigureAwait(false); } public async Task RecallMemoriesAsync( LlmPluginRuntimeConfig runtimeConfig, AiChatRecallMemoriesRequest request, CancellationToken cancellationToken = default) { using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Post, "/api/memories/recall", request, cancellationToken).ConfigureAwait(false); return CloneData(document); } private async IAsyncEnumerable StreamAiChatEventsAsync( LlmPluginRuntimeConfig runtimeConfig, string requestId, string path, [EnumeratorCancellation] CancellationToken cancellationToken) { using var request = await CreateRequestAsync(runtimeConfig, HttpMethod.Get, path, null, cancellationToken).ConfigureAwait(false); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { yield return new LlmErrorEvent { RequestId = requestId, Code = MapStatusCode(response.StatusCode), Message = $"AiChat stream returned {(int)response.StatusCode}." }; yield break; } await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); using var reader = new StreamReader(stream, Encoding.UTF8); var eventName = "message"; var dataLines = new List(); while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line) { cancellationToken.ThrowIfCancellationRequested(); if (line.StartsWith(":", StringComparison.Ordinal)) { continue; } if (line.Length == 0) { foreach (var streamEvent in ParseSseEvent(requestId, eventName, string.Join('\n', dataLines))) { yield return streamEvent; if (streamEvent is LlmCompletedEvent or LlmErrorEvent) { yield break; } } eventName = "message"; dataLines.Clear(); continue; } if (line.StartsWith("event:", StringComparison.OrdinalIgnoreCase)) { eventName = line["event:".Length..].Trim(); continue; } if (line.StartsWith("data:", StringComparison.OrdinalIgnoreCase)) { dataLines.Add(line["data:".Length..].TrimStart()); } } if (dataLines.Count > 0) { foreach (var streamEvent in ParseSseEvent(requestId, eventName, string.Join('\n', dataLines))) { yield return streamEvent; if (streamEvent is LlmCompletedEvent or LlmErrorEvent) { yield break; } } } yield return new LlmErrorEvent { RequestId = requestId, Code = LlmErrorCodes.AiChatSseInterrupted, Message = "AiChat stream ended before completion." }; } private IEnumerable ParseSseEvent(string requestId, string eventName, string data) { if (string.IsNullOrWhiteSpace(data)) { yield break; } JsonDocument document; try { document = JsonDocument.Parse(data); } catch (JsonException ex) { throw new AiChatClientException(LlmErrorCodes.StreamParseFailed, "Failed to parse AiChat stream chunk.", ex); } using (document) { var root = document.RootElement; if (eventName.Equals("chunk", StringComparison.OrdinalIgnoreCase) && root.TryGetProperty("delta", out var delta) && delta.ValueKind == JsonValueKind.String) { yield return new LlmDeltaEvent { RequestId = requestId, Delta = delta.GetString() ?? "" }; yield break; } if (eventName.Equals("snapshot", StringComparison.OrdinalIgnoreCase) && root.TryGetProperty("content", out var content) && content.ValueKind == JsonValueKind.String && !string.IsNullOrEmpty(content.GetString())) { yield return new LlmDeltaEvent { RequestId = requestId, Delta = content.GetString() ?? "" }; yield break; } if (eventName.Equals("done", StringComparison.OrdinalIgnoreCase)) { yield return new LlmCompletedEvent { RequestId = requestId }; yield break; } if (eventName.Equals("failed", StringComparison.OrdinalIgnoreCase) || eventName.Equals("aborted", StringComparison.OrdinalIgnoreCase)) { var message = root.TryGetProperty("error", out var error) && error.ValueKind == JsonValueKind.String ? error.GetString() ?? "AiChat request failed." : eventName.Equals("aborted", StringComparison.OrdinalIgnoreCase) ? "AiChat request was aborted." : "AiChat request failed."; yield return new LlmErrorEvent { RequestId = requestId, Code = LlmErrorCodes.AiChatApiFailed, Message = message }; } } } private async Task SendJsonAsync( LlmPluginRuntimeConfig runtimeConfig, HttpMethod method, string path, object? payload, CancellationToken cancellationToken) { using var request = await CreateRequestAsync(runtimeConfig, method, path, payload, cancellationToken).ConfigureAwait(false); using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (response.StatusCode == HttpStatusCode.Unauthorized) { ClearSession(runtimeConfig); using var retry = await CreateRequestAsync(runtimeConfig, method, path, payload, cancellationToken).ConfigureAwait(false); using var retryResponse = await _httpClient.SendAsync(retry, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); return await ReadJsonResponseAsync(retryResponse, cancellationToken).ConfigureAwait(false); } return await ReadJsonResponseAsync(response, cancellationToken).ConfigureAwait(false); } private async Task CreateRequestAsync( LlmPluginRuntimeConfig runtimeConfig, HttpMethod method, string path, object? payload, CancellationToken cancellationToken) { var uri = BuildUri(runtimeConfig, path); var request = new HttpRequestMessage(method, uri); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (!path.Equals("/api/auth/login", StringComparison.OrdinalIgnoreCase)) { var sessionToken = await EnsureSessionAsync(runtimeConfig, cancellationToken).ConfigureAwait(false); request.Headers.Add("x-session-token", sessionToken); } if (payload is not null) { request.Content = new StringContent(JsonSerializer.Serialize(payload, _jsonOptions), Encoding.UTF8, "application/json"); } return request; } private async Task EnsureSessionAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken) { var key = SessionKey(runtimeConfig); if (_sessionTokens.TryGetValue(key, out var existing) && !string.IsNullOrWhiteSpace(existing)) { return existing; } var email = runtimeConfig.AiChat.Account.Email; var password = ResolvePassword(runtimeConfig); if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password)) { throw new AiChatClientException(LlmErrorCodes.AiChatCredentialMissing, "AiChat account or password is missing."); } using var request = new HttpRequestMessage(HttpMethod.Post, BuildUri(runtimeConfig, "/api/auth/login")) { Content = new StringContent( JsonSerializer.Serialize(new { email, password }, _jsonOptions), Encoding.UTF8, "application/json") }; using var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); using var document = await ReadJsonResponseAsync(response, cancellationToken).ConfigureAwait(false); if (!TryGetData(document.RootElement, out var data) || !data.TryGetProperty("sessionToken", out var token) || token.ValueKind != JsonValueKind.String || string.IsNullOrWhiteSpace(token.GetString())) { throw new AiChatClientException(LlmErrorCodes.AiChatLoginFailed, "AiChat login did not return a session token."); } _sessionTokens[key] = token.GetString()!; return token.GetString()!; } private async Task ReadJsonResponseAsync(HttpResponseMessage response, CancellationToken cancellationToken) { await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); JsonDocument document; try { document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); } catch (JsonException) when (response.Content.Headers.ContentLength == 0) { document = JsonDocument.Parse("""{"ok":true}"""); } if (!response.IsSuccessStatusCode) { var (code, message) = ExtractError(document.RootElement, response.StatusCode); document.Dispose(); throw new AiChatClientException(code, message); } if (document.RootElement.TryGetProperty("ok", out var ok) && ok.ValueKind == JsonValueKind.False) { var (code, message) = ExtractError(document.RootElement, response.StatusCode); document.Dispose(); throw new AiChatClientException(code, message); } return document; } private static AiChatProjectSummary? ParseProject(JsonElement item) { if (!item.TryGetProperty("id", out var id) || id.ValueKind != JsonValueKind.String) { return null; } return new AiChatProjectSummary { Id = id.GetString()!, Name = item.TryGetProperty("name", out var name) && name.ValueKind == JsonValueKind.String ? name.GetString() ?? id.GetString()! : id.GetString()!, ProjectType = item.TryGetProperty("projectType", out var projectType) && projectType.ValueKind == JsonValueKind.String ? projectType.GetString() ?? "CHAT" : "CHAT", MemoryMode = item.TryGetProperty("memoryMode", out var memoryMode) && memoryMode.ValueKind == JsonValueKind.String ? memoryMode.GetString() ?? "ISOLATED" : "ISOLATED" }; } private static AiChatJsonResult CloneData(JsonDocument document) { if (!TryGetData(document.RootElement, out var data)) { return new AiChatJsonResult(); } return new AiChatJsonResult { Data = JsonSerializer.Deserialize(data.GetRawText()) }; } private static bool TryGetData(JsonElement root, out JsonElement data) { if (root.TryGetProperty("data", out data)) { return true; } data = default; return false; } private static bool TryGetProjectsData(JsonElement root, out JsonElement projects) { if (TryGetData(root, out var data)) { if (data.ValueKind == JsonValueKind.Array) { projects = data; return true; } if (data.ValueKind == JsonValueKind.Object && data.TryGetProperty("projects", out var nestedProjects) && nestedProjects.ValueKind == JsonValueKind.Array) { projects = nestedProjects; return true; } } projects = default; return false; } private static bool ReadBool(JsonElement root, string property) => root.TryGetProperty(property, out var value) && (value.ValueKind == JsonValueKind.True || (value.ValueKind == JsonValueKind.String && bool.TryParse(value.GetString(), out var parsed) && parsed)); private static (string Code, string Message) ExtractError(JsonElement root, HttpStatusCode statusCode) { var apiCode = root.TryGetProperty("code", out var codeElement) && codeElement.ValueKind == JsonValueKind.String ? codeElement.GetString() : null; var message = root.TryGetProperty("error", out var errorElement) && errorElement.ValueKind == JsonValueKind.String ? errorElement.GetString() ?? $"AiChat returned {(int)statusCode}." : $"AiChat returned {(int)statusCode}."; return (MapApiCode(apiCode, statusCode), message); } private static string MapApiCode(string? apiCode, HttpStatusCode statusCode) { if (string.Equals(apiCode, "TOKEN_TOTAL_LIMIT_REACHED", StringComparison.OrdinalIgnoreCase) || string.Equals(apiCode, "TOKEN_PER_REQUEST_LIMIT_REACHED", StringComparison.OrdinalIgnoreCase)) { return LlmErrorCodes.AiChatQuotaExceeded; } if (string.Equals(apiCode, "PERMISSION_DENIED", StringComparison.OrdinalIgnoreCase)) { return LlmErrorCodes.AiChatMemoryPermissionDenied; } if (statusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) { return LlmErrorCodes.AiChatLoginFailed; } return apiCode ?? LlmErrorCodes.AiChatApiFailed; } private static string MapStatusCode(HttpStatusCode statusCode) => statusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden ? LlmErrorCodes.AiChatLoginFailed : LlmErrorCodes.AiChatApiFailed; private static Uri BuildUri(LlmPluginRuntimeConfig runtimeConfig, string path) { var baseUrl = string.IsNullOrWhiteSpace(runtimeConfig.AiChat.BaseUrl) ? "http://192.168.1.111:13000" : runtimeConfig.AiChat.BaseUrl; if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out var baseUri) || baseUri.Scheme is not ("http" or "https")) { throw new AiChatClientException(LlmErrorCodes.RequestInvalid, "AiChat baseUrl must be an absolute HTTP or HTTPS URL."); } return new Uri(baseUri, path); } private static string? ResolvePassword(LlmPluginRuntimeConfig runtimeConfig) { var envName = runtimeConfig.AiChat.Account.PasswordEnv; if (!string.IsNullOrWhiteSpace(envName)) { var envValue = Environment.GetEnvironmentVariable(envName) ?? Environment.GetEnvironmentVariable(envName, EnvironmentVariableTarget.User) ?? Environment.GetEnvironmentVariable(envName, EnvironmentVariableTarget.Machine); if (!string.IsNullOrWhiteSpace(envValue)) { return envValue; } } return runtimeConfig.AiChat.Account.Password; } private void ClearSession(LlmPluginRuntimeConfig runtimeConfig) { _sessionTokens.TryRemove(SessionKey(runtimeConfig), out _); } private static string SessionKey(LlmPluginRuntimeConfig runtimeConfig) => $"{runtimeConfig.AiChat.BaseUrl}|{runtimeConfig.AiChat.Account.Email}"; }