From 09d4e2f1a1bc206c80d8d3287d070c70ec7fd63d Mon Sep 17 00:00:00 2001
From: chunhualin1 <chunhualin1@lenovo.com>
Date: 星期五, 14 八月 2026 20:00:52 +0800
Subject: [PATCH] Merge branch 'master' of http://git.linmoli.cn/r/Moli.Desktop
---
src/Moli.Desktop/Llm/LlmGatewayService.cs | 240 +++++++++++++++++++++++++++++++++++++++++++++++++++--------
1 files changed, 205 insertions(+), 35 deletions(-)
diff --git a/src/Moli.Desktop/Llm/LlmGatewayService.cs b/src/Moli.Desktop/Llm/LlmGatewayService.cs
index e068be6..06e7f65 100644
--- a/src/Moli.Desktop/Llm/LlmGatewayService.cs
+++ b/src/Moli.Desktop/Llm/LlmGatewayService.cs
@@ -58,43 +58,77 @@
{
if (runtimeConfig.IsAiChatMode)
{
- return _aiChatClient is null
- ? []
- : await _aiChatClient.GetModelsAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
+ if (!runtimeConfig.HasAiChatAccount || _aiChatClient is null)
+ {
+ return [];
+ }
+
+ var aiChatModels = await _aiChatClient.GetModelsAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
+ return aiChatModels
+ .Select(model => model with { Label = FormatAiChatLabel(model) })
+ .ToList();
}
- var configuredModels = runtimeConfig.Models
+ var customModels = 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
- })
+ .Select(model => ToCustomSummary(model, runtimeConfig.DefaultModel))
.ToList();
- if (configuredModels.Count > 0)
+ var providerModels = await GetProviderModelSummariesAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
+ if (customModels.Count > 0 || providerModels.Count > 0)
{
- return configuredModels;
+ return [.. customModels, .. providerModels];
}
return await GetModelsAsync(cancellationToken).ConfigureAwait(false);
}
- public Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(
+ public async Task<AiChatProjectsResult> GetProjectsAsync(
LlmPluginRuntimeConfig runtimeConfig,
CancellationToken cancellationToken = default)
- => _aiChatClient is null
- ? Task.FromResult<IReadOnlyList<AiChatProjectSummary>>([])
- : _aiChatClient.GetProjectsAsync(runtimeConfig, cancellationToken);
+ {
+ if (!runtimeConfig.HasAiChatAccount)
+ {
+ return new AiChatProjectsResult
+ {
+ Status = AiChatProjectStatuses.NotConfigured,
+ Projects = []
+ };
+ }
+
+ if (_aiChatClient is null)
+ {
+ return new AiChatProjectsResult
+ {
+ Status = AiChatProjectStatuses.NotConnected,
+ Message = "AiChat client is not available.",
+ Projects = []
+ };
+ }
+
+ try
+ {
+ var projects = await _aiChatClient.GetProjectsAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
+ return new AiChatProjectsResult
+ {
+ Status = AiChatProjectStatuses.Ready,
+ Projects = projects
+ };
+ }
+ catch (Exception ex) when (ex is AiChatClientException or HttpRequestException)
+ {
+ return new AiChatProjectsResult
+ {
+ Status = AiChatProjectStatuses.NotConnected,
+ Message = ex.Message,
+ Projects = []
+ };
+ }
+ }
public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(
LlmPluginRuntimeConfig runtimeConfig,
CancellationToken cancellationToken = default)
- => _aiChatClient is null
+ => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
? Task.FromResult(new AiChatMemoryCapabilities())
: _aiChatClient.GetMemoryCapabilitiesAsync(runtimeConfig, cancellationToken);
@@ -102,7 +136,7 @@
LlmPluginRuntimeConfig runtimeConfig,
AiChatGetMemoriesRequest request,
CancellationToken cancellationToken = default)
- => _aiChatClient is null
+ => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
? Task.FromResult(new AiChatJsonResult())
: _aiChatClient.GetMemoriesAsync(runtimeConfig, request, cancellationToken);
@@ -110,7 +144,7 @@
LlmPluginRuntimeConfig runtimeConfig,
AiChatCreateMemoryRequest request,
CancellationToken cancellationToken = default)
- => _aiChatClient is null
+ => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
? Task.FromResult(new AiChatJsonResult())
: _aiChatClient.CreateMemoryAsync(runtimeConfig, request, cancellationToken);
@@ -118,7 +152,7 @@
LlmPluginRuntimeConfig runtimeConfig,
string memoryId,
CancellationToken cancellationToken = default)
- => _aiChatClient is null
+ => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
? Task.CompletedTask
: _aiChatClient.DeleteMemoryAsync(runtimeConfig, memoryId, cancellationToken);
@@ -126,7 +160,7 @@
LlmPluginRuntimeConfig runtimeConfig,
AiChatRecallMemoriesRequest request,
CancellationToken cancellationToken = default)
- => _aiChatClient is null
+ => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
? Task.FromResult(new AiChatJsonResult())
: _aiChatClient.RecallMemoriesAsync(runtimeConfig, request, cancellationToken);
@@ -166,10 +200,7 @@
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);
+ var model = await ResolveDirectModelAsync(request, cancellationToken).ConfigureAwait(false);
if (model is null)
{
yield return new LlmErrorEvent
@@ -358,14 +389,139 @@
!string.IsNullOrWhiteSpace(model.Id) &&
!string.IsNullOrWhiteSpace(model.Label) &&
!string.IsNullOrWhiteSpace(model.Provider) &&
- !string.IsNullOrWhiteSpace(model.Endpoint) &&
- !string.IsNullOrWhiteSpace(model.ApiModel);
+ !string.IsNullOrWhiteSpace(model.ApiModel) &&
+ LlmOpenAiUrls.IsAbsoluteHttpUrl(model.GetBaseUrl());
+
+ private async Task<LlmModelConfig?> ResolveDirectModelAsync(LlmChatRequest request, CancellationToken cancellationToken)
+ {
+ var custom = request.RuntimeConfig.Models.FirstOrDefault(model =>
+ IsUsableRuntimeModel(model) &&
+ string.Equals(model.Id, request.ModelId, StringComparison.OrdinalIgnoreCase));
+ if (custom is not null)
+ {
+ return custom;
+ }
+
+ if (LlmProviderModelIds.TryParse(request.ModelId, out var providerId, out var apiModel))
+ {
+ var provider = request.RuntimeConfig.Providers.FirstOrDefault(item =>
+ IsUsableProvider(item) &&
+ string.Equals(item.Id, providerId, StringComparison.OrdinalIgnoreCase));
+ if (provider is not null)
+ {
+ return CreateProviderModel(provider, apiModel);
+ }
+ }
+
+ return await _registry.GetEnabledModelAsync(request.ModelId, cancellationToken).ConfigureAwait(false);
+ }
+
+ private async Task<IReadOnlyList<LlmModelSummary>> GetProviderModelSummariesAsync(
+ LlmPluginRuntimeConfig runtimeConfig,
+ CancellationToken cancellationToken)
+ {
+ var providers = runtimeConfig.Providers.Where(IsUsableProvider).ToList();
+ if (providers.Count == 0)
+ {
+ return [];
+ }
+
+ var tasks = providers.Select(provider => LoadProviderModelsAsync(provider, runtimeConfig.DefaultModel, cancellationToken)).ToList();
+ var batches = await Task.WhenAll(tasks).ConfigureAwait(false);
+ return batches.SelectMany(item => item).ToList();
+ }
+
+ private async Task<IReadOnlyList<LlmModelSummary>> LoadProviderModelsAsync(
+ LlmProviderConfig provider,
+ string? defaultModel,
+ CancellationToken cancellationToken)
+ {
+ try
+ {
+ var adapter = _adapterFactory.Get(ResolveProtocol(provider));
+ if (adapter is null)
+ {
+ return [];
+ }
+
+ var apiKey = await _credentialStore.ResolveSecretAsync(provider.AuthRef, cancellationToken).ConfigureAwait(false);
+ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ timeout.CancelAfter(TimeSpan.FromSeconds(10));
+ var ids = await adapter.ListModelIdsAsync(provider.BaseUrl, apiKey, timeout.Token).ConfigureAwait(false);
+ return ids
+ .Where(id => !string.IsNullOrWhiteSpace(id))
+ .Select(apiModel => ToProviderSummary(provider, apiModel, defaultModel))
+ .ToList();
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ RecordProviderCatalogFailure(provider, ex);
+ return [];
+ }
+ }
+
+ private static LlmModelSummary ToCustomSummary(LlmModelConfig model, string? defaultModel)
+ => new()
+ {
+ Id = model.Id,
+ Label = WithDefaultMark($"{model.Label}(Custom)", model.Id, defaultModel),
+ Provider = model.Provider,
+ SupportsStreaming = model.SupportsStreaming,
+ Enabled = model.Enabled
+ };
+
+ private static LlmModelSummary ToProviderSummary(LlmProviderConfig provider, string apiModel, string? defaultModel)
+ {
+ var id = LlmProviderModelIds.Create(provider.Id, apiModel);
+ return new LlmModelSummary
+ {
+ Id = id,
+ Label = WithDefaultMark($"{apiModel}({provider.Label})", id, defaultModel),
+ Provider = ResolveProtocol(provider),
+ SupportsStreaming = true,
+ Enabled = true
+ };
+ }
+
+ private static string FormatAiChatLabel(LlmModelSummary model)
+ {
+ var isDefault = model.Label.EndsWith(" *", StringComparison.Ordinal);
+ return isDefault ? $"{model.Id}(AiChat) *" : $"{model.Id}(AiChat)";
+ }
+
+ private static string WithDefaultMark(string label, string id, string? defaultModel)
+ => string.Equals(id, defaultModel, StringComparison.OrdinalIgnoreCase)
+ ? $"{label} *"
+ : label;
+
+ private static bool IsUsableProvider(LlmProviderConfig provider)
+ => provider.Enabled &&
+ !string.IsNullOrWhiteSpace(provider.Id) &&
+ !string.IsNullOrWhiteSpace(provider.Label) &&
+ LlmOpenAiUrls.IsAbsoluteHttpUrl(LlmOpenAiUrls.ResolveBaseUrl(provider.BaseUrl, null));
+
+ private static string ResolveProtocol(LlmProviderConfig provider)
+ => string.IsNullOrWhiteSpace(provider.Protocol) ? "openai-compatible" : provider.Protocol;
+
+ private static LlmModelConfig CreateProviderModel(LlmProviderConfig provider, string apiModel)
+ => new()
+ {
+ Id = LlmProviderModelIds.Create(provider.Id, apiModel),
+ Label = $"{apiModel}({provider.Label})",
+ Provider = ResolveProtocol(provider),
+ BaseUrl = LlmOpenAiUrls.ResolveBaseUrl(provider.BaseUrl, null),
+ AuthRef = provider.AuthRef,
+ ApiModel = apiModel,
+ SupportsStreaming = true,
+ Enabled = true
+ };
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,
@@ -375,8 +531,22 @@
["requestId"] = request.RequestId,
["modelId"] = request.ModelId,
["provider"] = model.Provider,
- ["endpointHost"] = host,
+ ["endpointHost"] = LlmOpenAiUrls.Host(model.GetBaseUrl()),
["exception"] = exception
});
}
+
+ private void RecordProviderCatalogFailure(LlmProviderConfig provider, Exception exception)
+ {
+ _diagnostics.Record(
+ DiagnosticSeverity.Warning,
+ LlmErrorCodes.EndpointUnavailable,
+ "LLM provider model catalog could not be loaded.",
+ new Dictionary<string, string>
+ {
+ ["providerId"] = provider.Id,
+ ["endpointHost"] = LlmOpenAiUrls.Host(LlmOpenAiUrls.ResolveBaseUrl(provider.BaseUrl, null)),
+ ["exception"] = exception.GetType().Name
+ });
+ }
}
--
Gitblit v1.9.1