From 4df6165fa93c7caeea86385312415e312de4d11f Mon Sep 17 00:00:00 2001
From: Moli <13026959681@163.com>
Date: 星期二, 05 五月 2026 01:10:39 +0800
Subject: [PATCH] 暂存

---
 src/Moli.Desktop/Llm/LlmGatewayService.cs |  356 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 356 insertions(+), 0 deletions(-)

diff --git a/src/Moli.Desktop/Llm/LlmGatewayService.cs b/src/Moli.Desktop/Llm/LlmGatewayService.cs
new file mode 100644
index 0000000..472ecda
--- /dev/null
+++ b/src/Moli.Desktop/Llm/LlmGatewayService.cs
@@ -0,0 +1,356 @@
+using System.Collections.Concurrent;
+using System.Net.Http;
+using System.Runtime.CompilerServices;
+using Moli.Desktop.Diagnostics;
+
+namespace Moli.Desktop.Llm;
+
+public sealed class LlmGatewayService : ILlmGatewayService
+{
+    private static readonly HashSet<string> AllowedRoles = new(StringComparer.OrdinalIgnoreCase)
+    {
+        "system",
+        "user",
+        "assistant"
+    };
+
+    private readonly ILlmModelRegistry _registry;
+    private readonly ICredentialStore _credentialStore;
+    private readonly ILlmProviderAdapterFactory _adapterFactory;
+    private readonly IDiagnosticsService _diagnostics;
+    private readonly IAiChatClient? _aiChatClient;
+    private readonly ConcurrentDictionary<string, CancellationTokenSource> _activeRequests = new(StringComparer.OrdinalIgnoreCase);
+
+    public LlmGatewayService(
+        ILlmModelRegistry registry,
+        ICredentialStore credentialStore,
+        ILlmProviderAdapterFactory adapterFactory,
+        IDiagnosticsService diagnostics,
+        IAiChatClient? aiChatClient = null)
+    {
+        _registry = registry;
+        _credentialStore = credentialStore;
+        _adapterFactory = adapterFactory;
+        _diagnostics = diagnostics;
+        _aiChatClient = aiChatClient;
+    }
+
+    public async Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(CancellationToken cancellationToken = default)
+    {
+        var document = await _registry.LoadAsync(cancellationToken).ConfigureAwait(false);
+        return document.Models
+            .Where(model => model.Enabled)
+            .Select(model => new LlmModelSummary
+            {
+                Id = model.Id,
+                Label = model.Label,
+                Provider = model.Provider,
+                SupportsStreaming = model.SupportsStreaming,
+                Enabled = model.Enabled
+            })
+            .ToList();
+    }
+
+    public async Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(
+        LlmPluginRuntimeConfig runtimeConfig,
+        CancellationToken cancellationToken = default)
+    {
+        if (runtimeConfig.IsAiChatMode)
+        {
+            return _aiChatClient is null
+                ? []
+                : await _aiChatClient.GetModelsAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
+        }
+
+        var configuredModels = runtimeConfig.Models
+            .Where(IsUsableRuntimeModel)
+            .Select(model => new LlmModelSummary
+            {
+                Id = model.Id,
+                Label = string.Equals(model.Id, runtimeConfig.DefaultModel, StringComparison.OrdinalIgnoreCase)
+                    ? $"{model.Label} *"
+                    : model.Label,
+                Provider = model.Provider,
+                SupportsStreaming = model.SupportsStreaming,
+                Enabled = model.Enabled
+            })
+            .ToList();
+        if (configuredModels.Count > 0)
+        {
+            return configuredModels;
+        }
+
+        return await GetModelsAsync(cancellationToken).ConfigureAwait(false);
+    }
+
+    public Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(
+        LlmPluginRuntimeConfig runtimeConfig,
+        CancellationToken cancellationToken = default)
+        => _aiChatClient is null
+            ? Task.FromResult<IReadOnlyList<AiChatProjectSummary>>([])
+            : _aiChatClient.GetProjectsAsync(runtimeConfig, cancellationToken);
+
+    public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(
+        LlmPluginRuntimeConfig runtimeConfig,
+        CancellationToken cancellationToken = default)
+        => _aiChatClient is null
+            ? Task.FromResult(new AiChatMemoryCapabilities())
+            : _aiChatClient.GetMemoryCapabilitiesAsync(runtimeConfig, cancellationToken);
+
+    public Task<AiChatJsonResult> GetMemoriesAsync(
+        LlmPluginRuntimeConfig runtimeConfig,
+        AiChatGetMemoriesRequest request,
+        CancellationToken cancellationToken = default)
+        => _aiChatClient is null
+            ? Task.FromResult(new AiChatJsonResult())
+            : _aiChatClient.GetMemoriesAsync(runtimeConfig, request, cancellationToken);
+
+    public Task<AiChatJsonResult> CreateMemoryAsync(
+        LlmPluginRuntimeConfig runtimeConfig,
+        AiChatCreateMemoryRequest request,
+        CancellationToken cancellationToken = default)
+        => _aiChatClient is null
+            ? Task.FromResult(new AiChatJsonResult())
+            : _aiChatClient.CreateMemoryAsync(runtimeConfig, request, cancellationToken);
+
+    public Task DeleteMemoryAsync(
+        LlmPluginRuntimeConfig runtimeConfig,
+        string memoryId,
+        CancellationToken cancellationToken = default)
+        => _aiChatClient is null
+            ? Task.CompletedTask
+            : _aiChatClient.DeleteMemoryAsync(runtimeConfig, memoryId, cancellationToken);
+
+    public Task<AiChatJsonResult> RecallMemoriesAsync(
+        LlmPluginRuntimeConfig runtimeConfig,
+        AiChatRecallMemoriesRequest request,
+        CancellationToken cancellationToken = default)
+        => _aiChatClient is null
+            ? Task.FromResult(new AiChatJsonResult())
+            : _aiChatClient.RecallMemoriesAsync(runtimeConfig, request, cancellationToken);
+
+    public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
+        LlmChatRequest request,
+        [EnumeratorCancellation] CancellationToken cancellationToken = default)
+    {
+        if (!IsValidRequest(request, out var validationError))
+        {
+            yield return new LlmErrorEvent
+            {
+                RequestId = request.RequestId,
+                Code = LlmErrorCodes.RequestInvalid,
+                Message = validationError
+            };
+            yield break;
+        }
+
+        if (string.Equals(request.Mode, LlmConnectionModes.AiChatApi, StringComparison.OrdinalIgnoreCase))
+        {
+            if (_aiChatClient is null)
+            {
+                yield return new LlmErrorEvent
+                {
+                    RequestId = request.RequestId,
+                    Code = LlmErrorCodes.AiChatApiFailed,
+                    Message = "AiChat client is not available."
+                };
+                yield break;
+            }
+
+            await foreach (var streamEvent in _aiChatClient.StreamChatAsync(request, request.RuntimeConfig, cancellationToken).ConfigureAwait(false))
+            {
+                yield return streamEvent;
+            }
+
+            yield break;
+        }
+
+        var model = request.RuntimeConfig.Models.FirstOrDefault(model =>
+            IsUsableRuntimeModel(model) &&
+            string.Equals(model.Id, request.ModelId, StringComparison.OrdinalIgnoreCase));
+        model ??= await _registry.GetEnabledModelAsync(request.ModelId, cancellationToken).ConfigureAwait(false);
+        if (model is null)
+        {
+            yield return new LlmErrorEvent
+            {
+                RequestId = request.RequestId,
+                Code = LlmErrorCodes.ModelNotFound,
+                Message = "Selected LLM model is unavailable."
+            };
+            yield break;
+        }
+
+        var adapter = _adapterFactory.Get(model.Provider);
+        if (adapter is null)
+        {
+            yield return new LlmErrorEvent
+            {
+                RequestId = request.RequestId,
+                Code = LlmErrorCodes.ProviderUnsupported,
+                Message = "Selected LLM provider is unsupported."
+            };
+            yield break;
+        }
+
+        var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+        var timeoutMs = request.Options.TimeoutMs ?? model.RequestDefaults.TimeoutMs;
+        linkedCts.CancelAfter(TimeSpan.FromMilliseconds(timeoutMs));
+        _activeRequests[request.RequestId] = linkedCts;
+
+        var secret = await _credentialStore.ResolveSecretAsync(model.AuthRef, linkedCts.Token).ConfigureAwait(false);
+        if (!string.IsNullOrWhiteSpace(model.AuthRef) && string.IsNullOrWhiteSpace(secret))
+        {
+            yield return new LlmErrorEvent
+            {
+                RequestId = request.RequestId,
+                Code = LlmErrorCodes.CredentialMissing,
+                Message = "LLM credential is missing. Check the model authRef configuration."
+            };
+            yield break;
+        }
+
+        var providerRequest = new LlmProviderRequest
+        {
+            RequestId = request.RequestId,
+            Model = model,
+            Messages = request.Messages,
+            Options = request.Options,
+            ApiKey = secret
+        };
+
+        await using var enumerator = adapter.StreamAsync(providerRequest, linkedCts.Token).GetAsyncEnumerator(linkedCts.Token);
+        while (true)
+        {
+            LlmStreamEvent? nextEvent = null;
+            try
+            {
+                if (!await enumerator.MoveNextAsync().ConfigureAwait(false))
+                {
+                    _activeRequests.TryRemove(request.RequestId, out _);
+                    linkedCts.Dispose();
+                    yield break;
+                }
+
+                var chunk = enumerator.Current;
+                if (!string.IsNullOrEmpty(chunk.Delta))
+                {
+                    nextEvent = new LlmDeltaEvent { RequestId = request.RequestId, Delta = chunk.Delta };
+                }
+                if (chunk.IsCompleted)
+                {
+                    nextEvent = new LlmCompletedEvent { RequestId = request.RequestId, Usage = chunk.Usage };
+                }
+            }
+            catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
+            {
+                nextEvent = new LlmErrorEvent
+                {
+                    RequestId = request.RequestId,
+                    Code = LlmErrorCodes.Timeout,
+                    Message = "LLM request timed out."
+                };
+            }
+            catch (HttpRequestException ex)
+            {
+                RecordFailure(request, model, LlmErrorCodes.EndpointUnavailable, ex.GetType().Name);
+                nextEvent = new LlmErrorEvent
+                {
+                    RequestId = request.RequestId,
+                    Code = LlmErrorCodes.EndpointUnavailable,
+                    Message = "LLM endpoint is unavailable."
+                };
+            }
+            catch (LlmProviderException ex)
+            {
+                RecordFailure(request, model, ex.Code, ex.GetType().Name);
+                nextEvent = new LlmErrorEvent
+                {
+                    RequestId = request.RequestId,
+                    Code = ex.Code,
+                    Message = ex.Message
+                };
+            }
+            finally
+            {
+                if (nextEvent is LlmCompletedEvent or LlmErrorEvent)
+                {
+                    _activeRequests.TryRemove(request.RequestId, out _);
+                    linkedCts.Dispose();
+                }
+            }
+
+            if (nextEvent is null)
+            {
+                continue;
+            }
+
+            yield return nextEvent;
+            if (nextEvent is LlmCompletedEvent or LlmErrorEvent)
+            {
+                yield break;
+            }
+        }
+    }
+
+    public Task CancelAsync(string requestId, CancellationToken cancellationToken = default)
+    {
+        cancellationToken.ThrowIfCancellationRequested();
+        if (_activeRequests.TryRemove(requestId, out var cts))
+        {
+            cts.Cancel();
+            cts.Dispose();
+        }
+
+        return Task.CompletedTask;
+    }
+
+    private static bool IsValidRequest(LlmChatRequest request, out string error)
+    {
+        if (string.IsNullOrWhiteSpace(request.RequestId) ||
+            string.IsNullOrWhiteSpace(request.PluginId) ||
+            string.IsNullOrWhiteSpace(request.InstanceId) ||
+            string.IsNullOrWhiteSpace(request.ModelId))
+        {
+            error = "requestId, pluginId, instanceId and modelId are required.";
+            return false;
+        }
+
+        if (request.Messages.Count == 0 || request.Messages.Any(message =>
+                string.IsNullOrWhiteSpace(message.Content) ||
+                !AllowedRoles.Contains(message.Role)))
+        {
+            error = "At least one valid message is required.";
+            return false;
+        }
+
+        error = "";
+        return true;
+    }
+
+    private static bool IsUsableRuntimeModel(LlmModelConfig model)
+        => model.Enabled &&
+           !string.IsNullOrWhiteSpace(model.Id) &&
+           !string.IsNullOrWhiteSpace(model.Label) &&
+           !string.IsNullOrWhiteSpace(model.Provider) &&
+           !string.IsNullOrWhiteSpace(model.Endpoint) &&
+           !string.IsNullOrWhiteSpace(model.ApiModel);
+
+    private void RecordFailure(LlmChatRequest request, LlmModelConfig model, string code, string exception)
+    {
+        var host = Uri.TryCreate(model.Endpoint, UriKind.Absolute, out var endpoint)
+            ? endpoint.Host
+            : "";
+        _diagnostics.Record(
+            DiagnosticSeverity.Warning,
+            code,
+            "LLM request failed.",
+            new Dictionary<string, string>
+            {
+                ["requestId"] = request.RequestId,
+                ["modelId"] = request.ModelId,
+                ["provider"] = model.Provider,
+                ["endpointHost"] = host,
+                ["exception"] = exception
+            });
+    }
+}

--
Gitblit v1.9.1