基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-14 09d4e2f1a1bc206c80d8d3287d070c70ec7fd63d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
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<LlmProviderChunk> StreamAsync(
        LlmProviderRequest request,
        [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        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);
        }
 
        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)
        {
            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);
        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 };
    }
 
    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)
    {
        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
    };
 
    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
{
    public LlmProviderException(string code, string message, Exception? innerException = null)
        : base(message, innerException)
    {
        Code = code;
    }
 
    public string Code { get; }
}