| | | 1 | | using System.IO; |
| | | 2 | | using System.Runtime.CompilerServices; |
| | | 3 | | using System.Text; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | using Newtonsoft.Json; |
| | | 6 | | using Services.ApiServices.OpenRouterApi.Models; |
| | | 7 | | |
| | | 8 | | namespace Services.ApiServices.OpenRouterApi; |
| | | 9 | | |
| | | 10 | | public class OpenRouterApiClient |
| | | 11 | | { |
| | | 12 | | private readonly HttpClient _httpClient; |
| | | 13 | | private readonly ILogger<OpenRouterApiClient> _logger; |
| | | 14 | | private readonly OpenRouterApiConfig? _config; |
| | | 15 | | |
| | 41 | 16 | | public OpenRouterApiClient( |
| | 41 | 17 | | HttpClient httpClient, |
| | 41 | 18 | | ILogger<OpenRouterApiClient> logger, |
| | 41 | 19 | | OpenRouterApiConfig? config = null) |
| | | 20 | | { |
| | 41 | 21 | | _httpClient = httpClient; |
| | 41 | 22 | | _logger = logger; |
| | 41 | 23 | | _config = config; |
| | 41 | 24 | | } |
| | | 25 | | |
| | 33 | 26 | | public bool IsConfigured => _config != null |
| | 33 | 27 | | ? _config.IsConfigured |
| | 33 | 28 | | : (_httpClient.DefaultRequestHeaders.Authorization == null || !string.IsNullOrWhiteSpace(_httpClient.DefaultRequ |
| | | 29 | | |
| | | 30 | | public async Task<ChatCompletionResponse?> CompleteChatAsync( |
| | | 31 | | ChatCompletionRequest request, |
| | | 32 | | CancellationToken ct = default) |
| | | 33 | | { |
| | 27 | 34 | | if (!IsConfigured) |
| | | 35 | | { |
| | 1 | 36 | | _logger.LogInformation("OpenRouter: API-ключ не настроен, исходящий запрос пропущен"); |
| | 1 | 37 | | return null; |
| | | 38 | | } |
| | | 39 | | |
| | | 40 | | try |
| | | 41 | | { |
| | 26 | 42 | | var json = JsonConvert.SerializeObject(request); |
| | 26 | 43 | | var content = new StringContent(json, Encoding.UTF8, "application/json"); |
| | | 44 | | |
| | 26 | 45 | | using var response = await _httpClient.PostAsync("chat/completions", content, ct); |
| | 21 | 46 | | response.EnsureSuccessStatusCode(); |
| | | 47 | | |
| | 18 | 48 | | var body = await response.Content.ReadAsStringAsync(ct); |
| | 18 | 49 | | _logger.LogDebug("OpenRouter response received, length={Length}", body.Length); |
| | 18 | 50 | | return JsonConvert.DeserializeObject<ChatCompletionResponse>(body); |
| | | 51 | | } |
| | | 52 | | // Регрессия #2161: сетевой сбой (нет HTTP-ответа) — недоступность openrouter.ai, а не ошибка |
| | | 53 | | // запроса; OutboundRequestLoggingHandler уже записал детали. |
| | 5 | 54 | | catch (HttpRequestException ex) when (IsNetworkUnavailable(ex)) |
| | | 55 | | { |
| | 1 | 56 | | _logger.LogInformation("OpenRouter недоступен: {Message}", ex.Message); |
| | 1 | 57 | | return null; |
| | | 58 | | } |
| | | 59 | | // Регрессия #2163: 401 Unauthorized при отсутствующем/недействительном ключе логируется |
| | | 60 | | // информационно, не засоряя errors-*.log. |
| | 4 | 61 | | catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.Unauthorized) |
| | | 62 | | { |
| | 1 | 63 | | _logger.LogInformation("OpenRouter: авторизация не пройдена (HTTP 401). Проверьте OpenRouter:ApiKey в конфиг |
| | 1 | 64 | | return null; |
| | | 65 | | } |
| | 3 | 66 | | catch (HttpRequestException ex) |
| | | 67 | | { |
| | 3 | 68 | | _logger.LogWarning(ex, "OpenRouter HTTP error"); |
| | 3 | 69 | | return null; |
| | | 70 | | } |
| | 2 | 71 | | catch (OperationCanceledException ex) |
| | | 72 | | { |
| | 2 | 73 | | if (ct.IsCancellationRequested) |
| | | 74 | | { |
| | 1 | 75 | | _logger.LogInformation("OpenRouter request canceled by caller"); |
| | | 76 | | } |
| | | 77 | | else |
| | | 78 | | { |
| | 1 | 79 | | _logger.LogInformation("OpenRouter timeout: {Message}", ex.Message); |
| | | 80 | | } |
| | 2 | 81 | | return null; |
| | | 82 | | } |
| | 1 | 83 | | catch (Exception ex) |
| | | 84 | | { |
| | 1 | 85 | | _logger.LogError(ex, "OpenRouter unexpected error"); |
| | 1 | 86 | | return null; |
| | | 87 | | } |
| | 27 | 88 | | } |
| | | 89 | | |
| | | 90 | | /// <summary> |
| | | 91 | | /// Стриминг ответа через SSE. Возвращает текстовые чанки по мере поступления. |
| | | 92 | | /// Когда стриминг завершается, вызывает <paramref name="onUsage"/> с данными о потреблении токенов. |
| | | 93 | | /// </summary> |
| | | 94 | | public async IAsyncEnumerable<string> StreamChatAsync( |
| | | 95 | | ChatCompletionRequest request, |
| | | 96 | | Action<UsageInfo>? onUsage = null, |
| | | 97 | | [EnumeratorCancellation] CancellationToken ct = default) |
| | | 98 | | { |
| | 5 | 99 | | if (!IsConfigured) |
| | | 100 | | { |
| | 1 | 101 | | _logger.LogInformation("OpenRouter stream: API-ключ не настроен, исходящий запрос пропущен"); |
| | 1 | 102 | | yield break; |
| | | 103 | | } |
| | | 104 | | |
| | 4 | 105 | | request.Stream = true; |
| | 4 | 106 | | request.StreamOptions = new StreamOptions { IncludeUsage = true }; |
| | | 107 | | |
| | 4 | 108 | | var json = JsonConvert.SerializeObject(request); |
| | 4 | 109 | | var content = new StringContent(json, Encoding.UTF8, "application/json"); |
| | | 110 | | |
| | | 111 | | HttpResponseMessage response; |
| | | 112 | | try |
| | | 113 | | { |
| | 4 | 114 | | var req = new HttpRequestMessage(HttpMethod.Post, "chat/completions") { Content = content }; |
| | 4 | 115 | | response = await _httpClient.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct); |
| | 2 | 116 | | response.EnsureSuccessStatusCode(); |
| | 1 | 117 | | } |
| | 1 | 118 | | catch (HttpRequestException ex) when (ex.StatusCode == System.Net.HttpStatusCode.Unauthorized) |
| | | 119 | | { |
| | 1 | 120 | | _logger.LogInformation("OpenRouter stream: авторизация не пройдена (HTTP 401). Проверьте OpenRouter:ApiKey в |
| | 1 | 121 | | yield break; |
| | | 122 | | } |
| | 2 | 123 | | catch (OperationCanceledException ex) |
| | | 124 | | { |
| | 2 | 125 | | if (ct.IsCancellationRequested) |
| | | 126 | | { |
| | 1 | 127 | | _logger.LogInformation("OpenRouter stream: canceled by caller"); |
| | | 128 | | } |
| | | 129 | | else |
| | | 130 | | { |
| | 1 | 131 | | _logger.LogInformation("OpenRouter stream: request timed out ({Message})", ex.Message); |
| | | 132 | | } |
| | 2 | 133 | | yield break; |
| | | 134 | | } |
| | 0 | 135 | | catch (Exception ex) |
| | | 136 | | { |
| | 0 | 137 | | _logger.LogWarning(ex, "OpenRouter stream: request failed"); |
| | 0 | 138 | | yield break; |
| | | 139 | | } |
| | | 140 | | |
| | 1 | 141 | | using var _ = response; |
| | | 142 | | Stream stream; |
| | | 143 | | try |
| | | 144 | | { |
| | 1 | 145 | | stream = await response.Content.ReadAsStreamAsync(ct); |
| | 1 | 146 | | } |
| | 0 | 147 | | catch (OperationCanceledException ex) |
| | | 148 | | { |
| | 0 | 149 | | if (ct.IsCancellationRequested) |
| | | 150 | | { |
| | 0 | 151 | | _logger.LogInformation("OpenRouter stream: canceled while opening body stream"); |
| | | 152 | | } |
| | | 153 | | else |
| | | 154 | | { |
| | 0 | 155 | | _logger.LogInformation("OpenRouter stream: timed out while opening body stream ({Message})", ex.Message) |
| | | 156 | | } |
| | 0 | 157 | | yield break; |
| | | 158 | | } |
| | 0 | 159 | | catch (Exception ex) |
| | | 160 | | { |
| | 0 | 161 | | _logger.LogWarning(ex, "OpenRouter stream: cannot read body"); |
| | 0 | 162 | | yield break; |
| | | 163 | | } |
| | | 164 | | |
| | 1 | 165 | | UsageInfo? lastUsage = null; |
| | | 166 | | |
| | 1 | 167 | | using var reader = new StreamReader(stream, Encoding.UTF8); |
| | 5 | 168 | | while (!reader.EndOfStream && !ct.IsCancellationRequested) |
| | | 169 | | { |
| | | 170 | | string? line; |
| | 10 | 171 | | try { line = await reader.ReadLineAsync(ct); } |
| | 0 | 172 | | catch { yield break; } |
| | | 173 | | |
| | 5 | 174 | | if (line == null) break; |
| | 5 | 175 | | if (!line.StartsWith("data: ", StringComparison.Ordinal)) continue; |
| | | 176 | | |
| | 3 | 177 | | var data = line["data: ".Length..]; |
| | 3 | 178 | | if (data == "[DONE]") break; |
| | | 179 | | |
| | | 180 | | ChatCompletionChunk? chunk; |
| | 4 | 181 | | try { chunk = JsonConvert.DeserializeObject<ChatCompletionChunk>(data); } |
| | 0 | 182 | | catch { continue; } |
| | | 183 | | |
| | 2 | 184 | | if (chunk?.Usage != null) |
| | 1 | 185 | | lastUsage = chunk.Usage; |
| | | 186 | | |
| | 2 | 187 | | var text = chunk?.Choices?.FirstOrDefault()?.Delta?.Content; |
| | 2 | 188 | | if (!string.IsNullOrEmpty(text)) |
| | 2 | 189 | | yield return text; |
| | | 190 | | } |
| | | 191 | | |
| | 1 | 192 | | if (lastUsage != null) |
| | 1 | 193 | | onUsage?.Invoke(lastUsage); |
| | 5 | 194 | | } |
| | | 195 | | |
| | | 196 | | private static bool IsNetworkUnavailable(HttpRequestException exception) => |
| | 5 | 197 | | exception.HttpRequestError is HttpRequestError.NameResolutionError or HttpRequestError.ConnectionError |
| | 5 | 198 | | || exception.InnerException is System.Net.Sockets.SocketException; |
| | | 199 | | } |