From 9b5711d3124622b1f1b18500d442c76492da877a Mon Sep 17 00:00:00 2001
From: chunhualin1 <chunhualin1@lenovo.com>
Date: 星期一, 17 八月 2026 16:52:33 +0800
Subject: [PATCH] 优化llm插件及bug修复

---
 src/Moli.Desktop/Llm/OpenAICompatibleAdapter.cs |  105 +++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 files changed, 103 insertions(+), 2 deletions(-)

diff --git a/src/Moli.Desktop/Llm/OpenAICompatibleAdapter.cs b/src/Moli.Desktop/Llm/OpenAICompatibleAdapter.cs
index 9517eda..5700ec8 100644
--- a/src/Moli.Desktop/Llm/OpenAICompatibleAdapter.cs
+++ b/src/Moli.Desktop/Llm/OpenAICompatibleAdapter.cs
@@ -24,7 +24,13 @@
         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);
@@ -48,7 +54,11 @@
 
         if (!response.IsSuccessStatusCode)
         {
-            throw new LlmProviderException(MapStatusCode(response.StatusCode), $"LLM provider returned {(int)response.StatusCode}.");
+            var providerMessage = await ReadProviderErrorMessageAsync(response, cancellationToken).ConfigureAwait(false);
+            var message = string.IsNullOrWhiteSpace(providerMessage)
+                ? $"LLM provider returned {(int)response.StatusCode}."
+                : $"LLM provider returned {(int)response.StatusCode}: {providerMessage}";
+            throw new LlmProviderException(MapStatusCode(response.StatusCode), message);
         }
 
         await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
@@ -85,6 +95,55 @@
         }
 
         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)
@@ -125,6 +184,48 @@
         (HttpStatusCode)429 => LlmErrorCodes.RateLimited,
         _ => LlmErrorCodes.EndpointUnavailable
     };
+
+    private async Task<string?> ReadProviderErrorMessageAsync(HttpResponseMessage response, CancellationToken cancellationToken)
+    {
+        var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
+        if (string.IsNullOrWhiteSpace(body))
+        {
+            return null;
+        }
+
+        try
+        {
+            using var document = JsonDocument.Parse(body);
+            var root = document.RootElement;
+            if (root.TryGetProperty("error", out var error))
+            {
+                if (error.ValueKind == JsonValueKind.Object &&
+                    error.TryGetProperty("message", out var message) &&
+                    message.ValueKind == JsonValueKind.String)
+                {
+                    return message.GetString();
+                }
+
+                if (error.ValueKind == JsonValueKind.String)
+                {
+                    return error.GetString();
+                }
+            }
+
+            if (root.TryGetProperty("message", out var rootMessage) &&
+                rootMessage.ValueKind == JsonValueKind.String)
+            {
+                return rootMessage.GetString();
+            }
+        }
+        catch (JsonException)
+        {
+            // Fall through to a trimmed body snippet for non-JSON provider errors.
+        }
+
+        var trimmed = body.Trim();
+        return trimmed.Length <= 500 ? trimmed : trimmed[..500];
+    }
 }
 
 public sealed class LlmProviderException : Exception

--
Gitblit v1.9.1