基于WebView2实现的Win11桌面框架,利用插件自定义
Moli
2026-05-04 b3bde921167ee0a7dc21cf7e3d642840a0fcc11e
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
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)
        {
            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 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
    };
}
 
public sealed class LlmProviderException : Exception
{
    public LlmProviderException(string code, string message, Exception? innerException = null)
        : base(message, innerException)
    {
        Code = code;
    }
 
    public string Code { get; }
}