using System.Net.Http.Headers; using System.Text; using System.Text.Json; namespace Admin.NET.Plugin.AiDOP.ChatBI; public sealed class DeepSeekChatClient : ITransient { private readonly IHttpClientFactory _httpClientFactory; public DeepSeekChatClient(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } public async Task CompleteAsync(string systemPrompt, string userPrompt, CancellationToken cancellationToken = default) { var options = App.GetConfig("DeepSeekSettings", true); if (options == null || string.IsNullOrWhiteSpace(options.ApiUrl) || string.IsNullOrWhiteSpace(options.ApiKey)) return null; var client = _httpClientFactory.CreateClient("AidopChatBI.DeepSeek"); using var request = new HttpRequestMessage(HttpMethod.Post, options.ApiUrl); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", options.ApiKey); var body = new { model = "deepseek-chat", messages = new[] { new { role = "system", content = systemPrompt }, new { role = "user", content = userPrompt } }, temperature = 0.2, max_tokens = 1200 }; request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"); using var response = await client.SendAsync(request, cancellationToken); if (!response.IsSuccessStatusCode) return null; var json = await response.Content.ReadAsStringAsync(cancellationToken); using var doc = JsonDocument.Parse(json); if (!doc.RootElement.TryGetProperty("choices", out var choices) || choices.GetArrayLength() == 0) return null; var message = choices[0].GetProperty("message"); return message.TryGetProperty("content", out var content) ? content.GetString()?.Trim() : null; } }