| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using System.Text.RegularExpressions; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | using Services.ApiServices.OpenRouterApi; |
| | | 6 | | |
| | | 7 | | namespace Services.AiAssistant; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Парсит свободный текст поиска заказов в <see cref="AiOrderFilterCriteria"/> через быстрый LLM-вызов. |
| | | 11 | | /// Regex-fallback — <see cref="AiOrderFilterParser.TryParseRegex"/>. |
| | | 12 | | /// </summary> |
| | | 13 | | public sealed class AiOrderFilterLlmParser |
| | | 14 | | { |
| | | 15 | | private const int TimeoutMs = 3000; |
| | | 16 | | |
| | | 17 | | private readonly OpenRouterDataManager _openRouter; |
| | | 18 | | private readonly ILogger<AiOrderFilterLlmParser> _logger; |
| | | 19 | | |
| | 1 | 20 | | private static readonly JsonSerializerOptions JsonOptions = new() |
| | 1 | 21 | | { |
| | 1 | 22 | | PropertyNameCaseInsensitive = true, |
| | 1 | 23 | | ReadCommentHandling = JsonCommentHandling.Skip, |
| | 1 | 24 | | AllowTrailingCommas = true, |
| | 1 | 25 | | }; |
| | | 26 | | |
| | 20 | 27 | | public AiOrderFilterLlmParser( |
| | 20 | 28 | | OpenRouterDataManager openRouter, |
| | 20 | 29 | | ILogger<AiOrderFilterLlmParser> logger) |
| | | 30 | | { |
| | 20 | 31 | | _openRouter = openRouter; |
| | 20 | 32 | | _logger = logger; |
| | 20 | 33 | | } |
| | | 34 | | |
| | | 35 | | public async Task<AiOrderFilterCriteria?> TryParseAsync( |
| | | 36 | | string message, |
| | | 37 | | DateTime nowMsk, |
| | | 38 | | CancellationToken ct = default) |
| | | 39 | | { |
| | 20 | 40 | | if (string.IsNullOrWhiteSpace(message)) |
| | 4 | 41 | | return null; |
| | | 42 | | |
| | 16 | 43 | | using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct); |
| | 16 | 44 | | timeoutCts.CancelAfter(TimeoutMs); |
| | | 45 | | |
| | | 46 | | try |
| | | 47 | | { |
| | 16 | 48 | | var prompt = BuildPrompt(message.Trim(), nowMsk); |
| | 16 | 49 | | var raw = await _openRouter.AskWithContextAsync( |
| | 16 | 50 | | prompt, |
| | 16 | 51 | | dataContext: string.Empty, |
| | 16 | 52 | | history: null, |
| | 16 | 53 | | modelOverride: null, |
| | 16 | 54 | | ct: timeoutCts.Token); |
| | | 55 | | |
| | 15 | 56 | | return DeserializeCriteria(raw); |
| | | 57 | | } |
| | 0 | 58 | | catch (OperationCanceledException) when (!ct.IsCancellationRequested) |
| | | 59 | | { |
| | 0 | 60 | | _logger.LogDebug("AiOrderFilterLlmParser: timeout after {Ms}ms", TimeoutMs); |
| | 0 | 61 | | return null; |
| | | 62 | | } |
| | 1 | 63 | | catch (Exception ex) |
| | | 64 | | { |
| | 1 | 65 | | _logger.LogWarning(ex, "AiOrderFilterLlmParser: failed, falling back to regex"); |
| | 1 | 66 | | return null; |
| | | 67 | | } |
| | 20 | 68 | | } |
| | | 69 | | |
| | | 70 | | internal static string BuildPrompt(string userMessage, DateTime nowMsk) => |
| | 17 | 71 | | $$""" |
| | 17 | 72 | | Ты парсер поисковых запросов по заказам Ozon в системе Studio2. |
| | 17 | 73 | | Ответь ТОЛЬКО валидным JSON (без markdown, без пояснений) по схеме: |
| | 17 | 74 | | { |
| | 17 | 75 | | "actionableOnly": false, |
| | 17 | 76 | | "overdueOnly": false, |
| | 17 | 77 | | "emptyPrice": false, |
| | 17 | 78 | | "includeArchived": false, |
| | 17 | 79 | | "ozonClientName": null, |
| | 17 | 80 | | "supplierName": null, |
| | 17 | 81 | | "transactionConductedBy": null, |
| | 17 | 82 | | "changedByUser": null, |
| | 17 | 83 | | "appStatusName": null, |
| | 17 | 84 | | "clientStatusName": null, |
| | 17 | 85 | | "onlyWithReturns": null, |
| | 17 | 86 | | "article": null, |
| | 17 | 87 | | "productName": null, |
| | 17 | 88 | | "manufacturerName": null, |
| | 17 | 89 | | "newCategory": null, |
| | 17 | 90 | | "minQuantity": null, |
| | 17 | 91 | | "maxQuantity": null, |
| | 17 | 92 | | "priceMin": null, |
| | 17 | 93 | | "priceMax": null, |
| | 17 | 94 | | "profitMin": null, |
| | 17 | 95 | | "profitMax": null, |
| | 17 | 96 | | "onlyNegativeProfit": null, |
| | 17 | 97 | | "purchasePriceMax": null, |
| | 17 | 98 | | "shipmentWarehouseName": null, |
| | 17 | 99 | | "deliveryProviderName": null, |
| | 17 | 100 | | "deliveryName": null, |
| | 17 | 101 | | "deliveryCity": null, |
| | 17 | 102 | | "onlyWithTrackingNumber": null, |
| | 17 | 103 | | "shippingDateFrom": null, |
| | 17 | 104 | | "shippingDateTo": null, |
| | 17 | 105 | | "processingDateFrom": null, |
| | 17 | 106 | | "processingDateTo": null, |
| | 17 | 107 | | "lastMonths": null, |
| | 17 | 108 | | "changedFrom": null, |
| | 17 | 109 | | "changedTo": null, |
| | 17 | 110 | | "fieldChangedName": null, |
| | 17 | 111 | | "fieldChangedToValue": null |
| | 17 | 112 | | } |
| | 17 | 113 | | |
| | 17 | 114 | | Правила: |
| | 17 | 115 | | - Даты в ISO 8601 (yyyy-MM-dd) или null. |
| | 17 | 116 | | - lastMonths — целое число месяцев назад от сегодня (ProcessingDate). |
| | 17 | 117 | | - «позавчера», «вчера», «прошлая неделя» → processingDateFrom/processingDateTo. |
| | 17 | 118 | | - «актуальные», «к обработке» → actionableOnly: true. |
| | 17 | 119 | | - «просроченные» → overdueOnly: true. |
| | 17 | 120 | | - «убыточные», «минусят», «в минусе» → onlyNegativeProfit: true. |
| | 17 | 121 | | - «по складу M2» → shipmentWarehouseName: «M2» (только код склада, без «на клиенте …»). |
| | 17 | 122 | | - «на клиенте Interparts RU» → ozonClientName: «Interparts RU» (Ozon-клиент, не склад). |
| | 17 | 123 | | - «за месяц», «за последний месяц» → lastMonths: 1. |
| | 17 | 124 | | - «со статусом X», «статус X» → appStatusName: X (статус в отчёте Studio2, не Ozon client status). |
| | 17 | 125 | | - «Отменен», «отменённые» → appStatusName: «Отменен», actionableOnly: false, includeArchived: true. |
| | 17 | 126 | | - Имена поставщиков/клиентов — только значение, без слова «поставщик» и без «со статусом …». |
| | 17 | 127 | | - Если запрос не про поиск заказов — верни {}. |
| | 17 | 128 | | |
| | 17 | 129 | | Сегодня (МСК): {{nowMsk:yyyy-MM-dd HH:mm}}. |
| | 17 | 130 | | |
| | 17 | 131 | | Запрос пользователя: {{userMessage}} |
| | 17 | 132 | | """; |
| | | 133 | | |
| | | 134 | | private static AiOrderFilterCriteria? DeserializeCriteria(string raw) |
| | | 135 | | { |
| | 15 | 136 | | if (string.IsNullOrWhiteSpace(raw)) |
| | 1 | 137 | | return null; |
| | | 138 | | |
| | 14 | 139 | | var json = ExtractJsonObject(raw); |
| | 14 | 140 | | if (string.IsNullOrWhiteSpace(json)) |
| | 2 | 141 | | return null; |
| | | 142 | | |
| | | 143 | | LlmFilterDto? dto; |
| | | 144 | | try |
| | | 145 | | { |
| | 12 | 146 | | dto = JsonSerializer.Deserialize<LlmFilterDto>(json, JsonOptions); |
| | 11 | 147 | | } |
| | 1 | 148 | | catch |
| | | 149 | | { |
| | 1 | 150 | | return null; |
| | | 151 | | } |
| | | 152 | | |
| | 11 | 153 | | if (dto == null) |
| | 0 | 154 | | return null; |
| | | 155 | | |
| | 11 | 156 | | var criteria = dto.ToCriteria(); |
| | 11 | 157 | | criteria = AiOrderFilterParser.NormalizeCriteria(criteria); |
| | 11 | 158 | | return criteria.HasCriteria ? criteria : null; |
| | 1 | 159 | | } |
| | | 160 | | |
| | | 161 | | private static string? ExtractJsonObject(string raw) |
| | | 162 | | { |
| | 14 | 163 | | var trimmed = raw.Trim(); |
| | 14 | 164 | | if (trimmed.StartsWith('{')) |
| | 11 | 165 | | return trimmed; |
| | | 166 | | |
| | 3 | 167 | | var match = Regex.Match(trimmed, @"\{[\s\S]*\}"); |
| | 3 | 168 | | return match.Success ? match.Value : null; |
| | | 169 | | } |
| | | 170 | | |
| | | 171 | | private sealed class LlmFilterDto |
| | | 172 | | { |
| | 20 | 173 | | public bool ActionableOnly { get; set; } |
| | 12 | 174 | | public bool OverdueOnly { get; set; } |
| | 12 | 175 | | public bool EmptyPrice { get; set; } |
| | 13 | 176 | | public bool IncludeArchived { get; set; } |
| | 13 | 177 | | public string? OzonClientName { get; set; } |
| | 14 | 178 | | public string? SupplierName { get; set; } |
| | 12 | 179 | | public string? TransactionConductedBy { get; set; } |
| | 12 | 180 | | public string? ChangedByUser { get; set; } |
| | 13 | 181 | | public string? AppStatusName { get; set; } |
| | 12 | 182 | | public string? ClientStatusName { get; set; } |
| | 12 | 183 | | public bool? OnlyWithReturns { get; set; } |
| | 15 | 184 | | public string? Article { get; set; } |
| | 13 | 185 | | public string? ProductName { get; set; } |
| | 12 | 186 | | public string? ManufacturerName { get; set; } |
| | 12 | 187 | | public string? NewCategory { get; set; } |
| | 15 | 188 | | public int? MinQuantity { get; set; } |
| | 15 | 189 | | public int? MaxQuantity { get; set; } |
| | 12 | 190 | | public decimal? PriceMin { get; set; } |
| | 12 | 191 | | public decimal? PriceMax { get; set; } |
| | 12 | 192 | | public decimal? ProfitMin { get; set; } |
| | 12 | 193 | | public decimal? ProfitMax { get; set; } |
| | 12 | 194 | | public bool? OnlyNegativeProfit { get; set; } |
| | 12 | 195 | | public decimal? PurchasePriceMax { get; set; } |
| | 13 | 196 | | public string? ShipmentWarehouseName { get; set; } |
| | 12 | 197 | | public string? DeliveryProviderName { get; set; } |
| | 12 | 198 | | public string? DeliveryName { get; set; } |
| | 13 | 199 | | public string? DeliveryCity { get; set; } |
| | 12 | 200 | | public bool? OnlyWithTrackingNumber { get; set; } |
| | 13 | 201 | | public string? ShippingDateFrom { get; set; } |
| | 13 | 202 | | public string? ShippingDateTo { get; set; } |
| | 13 | 203 | | public string? ProcessingDateFrom { get; set; } |
| | 13 | 204 | | public string? ProcessingDateTo { get; set; } |
| | 15 | 205 | | public int? LastMonths { get; set; } |
| | 13 | 206 | | public string? ChangedFrom { get; set; } |
| | 13 | 207 | | public string? ChangedTo { get; set; } |
| | 12 | 208 | | public string? FieldChangedName { get; set; } |
| | 12 | 209 | | public string? FieldChangedToValue { get; set; } |
| | | 210 | | |
| | 11 | 211 | | public AiOrderFilterCriteria ToCriteria() => new() |
| | 11 | 212 | | { |
| | 11 | 213 | | ActionableOnly = ActionableOnly, |
| | 11 | 214 | | OverdueOnly = OverdueOnly, |
| | 11 | 215 | | EmptyPrice = EmptyPrice, |
| | 11 | 216 | | IncludeArchived = IncludeArchived, |
| | 11 | 217 | | OzonClientName = NullIfEmpty(OzonClientName), |
| | 11 | 218 | | SupplierName = NullIfEmpty(SupplierName), |
| | 11 | 219 | | TransactionConductedBy = NullIfEmpty(TransactionConductedBy), |
| | 11 | 220 | | ChangedByUser = NullIfEmpty(ChangedByUser), |
| | 11 | 221 | | AppStatusName = NullIfEmpty(AppStatusName), |
| | 11 | 222 | | ClientStatusName = NullIfEmpty(ClientStatusName), |
| | 11 | 223 | | OnlyWithReturns = OnlyWithReturns, |
| | 11 | 224 | | Article = NullIfEmpty(Article), |
| | 11 | 225 | | ProductName = NullIfEmpty(ProductName), |
| | 11 | 226 | | ManufacturerName = NullIfEmpty(ManufacturerName), |
| | 11 | 227 | | NewCategory = NullIfEmpty(NewCategory), |
| | 11 | 228 | | MinQuantity = MinQuantity is > 0 ? MinQuantity : null, |
| | 11 | 229 | | MaxQuantity = MaxQuantity is > 0 ? MaxQuantity : null, |
| | 11 | 230 | | PriceMin = PriceMin, |
| | 11 | 231 | | PriceMax = PriceMax, |
| | 11 | 232 | | ProfitMin = ProfitMin, |
| | 11 | 233 | | ProfitMax = ProfitMax, |
| | 11 | 234 | | OnlyNegativeProfit = OnlyNegativeProfit, |
| | 11 | 235 | | PurchasePriceMax = PurchasePriceMax, |
| | 11 | 236 | | ShipmentWarehouseName = NullIfEmpty(ShipmentWarehouseName), |
| | 11 | 237 | | DeliveryProviderName = NullIfEmpty(DeliveryProviderName), |
| | 11 | 238 | | DeliveryName = NullIfEmpty(DeliveryName), |
| | 11 | 239 | | DeliveryCity = NullIfEmpty(DeliveryCity), |
| | 11 | 240 | | OnlyWithTrackingNumber = OnlyWithTrackingNumber, |
| | 11 | 241 | | ShippingDateFrom = ParseDate(ShippingDateFrom), |
| | 11 | 242 | | ShippingDateTo = ParseDate(ShippingDateTo), |
| | 11 | 243 | | ProcessingDateFrom = ParseDate(ProcessingDateFrom), |
| | 11 | 244 | | ProcessingDateTo = ParseDate(ProcessingDateTo), |
| | 11 | 245 | | LastMonths = LastMonths is > 0 ? LastMonths : null, |
| | 11 | 246 | | ChangedFrom = ParseDate(ChangedFrom), |
| | 11 | 247 | | ChangedTo = ParseDate(ChangedTo), |
| | 11 | 248 | | FieldChangedName = NullIfEmpty(FieldChangedName), |
| | 11 | 249 | | FieldChangedToValue = NullIfEmpty(FieldChangedToValue), |
| | 11 | 250 | | }; |
| | | 251 | | |
| | | 252 | | private static string? NullIfEmpty(string? s) => |
| | 176 | 253 | | string.IsNullOrWhiteSpace(s) ? null : s.Trim(); |
| | | 254 | | |
| | | 255 | | private static DateTime? ParseDate(string? s) |
| | | 256 | | { |
| | 66 | 257 | | if (string.IsNullOrWhiteSpace(s)) |
| | 57 | 258 | | return null; |
| | 9 | 259 | | if (DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var dt)) |
| | 6 | 260 | | return dt.Date; |
| | 3 | 261 | | return null; |
| | | 262 | | } |
| | | 263 | | } |
| | | 264 | | } |