基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-12 da97410f48a1e94d7e1fe019c69a7c847fe67ddf
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
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)
    {
        using var httpRequest = new HttpRequestMessage(HttpMethod.Post, request.Model.Endpoint);
        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 };
    }
 
    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; }
}