DeepSeekChatClient.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System.Net.Http.Headers;
  2. using System.Text;
  3. using System.Text.Json;
  4. namespace Admin.NET.Plugin.AiDOP.ChatBI;
  5. public sealed class DeepSeekChatClient : ITransient
  6. {
  7. private readonly IHttpClientFactory _httpClientFactory;
  8. public DeepSeekChatClient(IHttpClientFactory httpClientFactory)
  9. {
  10. _httpClientFactory = httpClientFactory;
  11. }
  12. public async Task<string?> CompleteAsync(string systemPrompt, string userPrompt, CancellationToken cancellationToken = default)
  13. {
  14. var options = App.GetConfig<DeepSeekOptions>("DeepSeekSettings", true);
  15. if (options == null || string.IsNullOrWhiteSpace(options.ApiUrl) || string.IsNullOrWhiteSpace(options.ApiKey))
  16. return null;
  17. var client = _httpClientFactory.CreateClient("AidopChatBI.DeepSeek");
  18. using var request = new HttpRequestMessage(HttpMethod.Post, options.ApiUrl);
  19. request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", options.ApiKey);
  20. var body = new
  21. {
  22. model = "deepseek-chat",
  23. messages = new[]
  24. {
  25. new { role = "system", content = systemPrompt },
  26. new { role = "user", content = userPrompt }
  27. },
  28. temperature = 0.2,
  29. max_tokens = 1200
  30. };
  31. request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json");
  32. using var response = await client.SendAsync(request, cancellationToken);
  33. if (!response.IsSuccessStatusCode)
  34. return null;
  35. var json = await response.Content.ReadAsStringAsync(cancellationToken);
  36. using var doc = JsonDocument.Parse(json);
  37. if (!doc.RootElement.TryGetProperty("choices", out var choices) || choices.GetArrayLength() == 0)
  38. return null;
  39. var message = choices[0].GetProperty("message");
  40. return message.TryGetProperty("content", out var content) ? content.GetString()?.Trim() : null;
  41. }
  42. }