DeepSeekChatClient.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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(
  13. string systemPrompt,
  14. string userPrompt,
  15. CancellationToken cancellationToken = default,
  16. int? maxTokens = null)
  17. {
  18. var options = App.GetConfig<DeepSeekOptions>("DeepSeekSettings", true);
  19. if (options == null || string.IsNullOrWhiteSpace(options.ApiUrl) || string.IsNullOrWhiteSpace(options.ApiKey))
  20. return null;
  21. var client = _httpClientFactory.CreateClient("AidopChatBI.DeepSeek");
  22. using var request = new HttpRequestMessage(HttpMethod.Post, options.ApiUrl);
  23. request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", options.ApiKey);
  24. var body = new
  25. {
  26. model = "deepseek-chat",
  27. messages = new[]
  28. {
  29. new { role = "system", content = systemPrompt },
  30. new { role = "user", content = userPrompt }
  31. },
  32. temperature = 0.2,
  33. max_tokens = maxTokens ?? 1200
  34. };
  35. request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json");
  36. using var response = await client.SendAsync(request, cancellationToken);
  37. if (!response.IsSuccessStatusCode)
  38. return null;
  39. var json = await response.Content.ReadAsStringAsync(cancellationToken);
  40. using var doc = JsonDocument.Parse(json);
  41. if (!doc.RootElement.TryGetProperty("choices", out var choices) || choices.GetArrayLength() == 0)
  42. return null;
  43. var message = choices[0].GetProperty("message");
  44. return message.TryGetProperty("content", out var content) ? content.GetString()?.Trim() : null;
  45. }
  46. }