DoubaoService.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using Newtonsoft.Json;
  2. using System.Net.Http.Headers;
  3. using System.Text;
  4. namespace OASystem.API.OAMethodLib.DoubaoAPI
  5. {
  6. public class DoubaoService : IDoubaoService
  7. {
  8. private readonly IHttpClientFactory _httpClientFactory;
  9. private readonly DoubaoSetting _doubaoSetting;
  10. private readonly ILogger<DoubaoService> _logger;
  11. public DoubaoService(IHttpClientFactory httpClientFactory, DoubaoSetting doubaoSetting, ILogger<DoubaoService> logger)
  12. {
  13. _httpClientFactory = httpClientFactory;
  14. _doubaoSetting = doubaoSetting;
  15. _logger = logger;
  16. }
  17. public async Task<string> CompleteChatAsync(List<DouBaoChatMessage> messages, CompleteChatOptions? options)
  18. {
  19. if (messages == null || !messages.Any())
  20. {
  21. _logger.LogError("消息不能为空 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  22. return null;
  23. }
  24. if(!messages.Any(x => x.Role == DouBaoRole.system)){
  25. messages.Insert(0,
  26. new DouBaoChatMessage() {
  27. Role = DouBaoRole.system, Content = "你是一个专业的AI助手,请根据用户的问题给出回答"
  28. });
  29. }
  30. options ??= new CompleteChatOptions();
  31. var httpClient = _httpClientFactory.CreateClient("Doubao");
  32. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _doubaoSetting.ApiKey);
  33. var body = new Dictionary<string, object>
  34. {
  35. ["model"] = _doubaoSetting.EndpointId,
  36. ["messages"] = messages.Select(x => new { role = x.Role.ToString(), content = x.Content }).ToArray()
  37. };
  38. if (options.ThinkingOptions.IsThinking)
  39. {
  40. body["reasoning_effort"] = options.ThinkingOptions.ReasoningEffort.ToString().ToLower();
  41. body["thinking"] = new {
  42. type = "enabled",
  43. };
  44. }
  45. var json = JsonConvert.SerializeObject(body);
  46. var response = await httpClient.PostAsync(
  47. _doubaoSetting.BaseAddress,
  48. new StringContent(json, Encoding.UTF8, "application/json")
  49. );
  50. response.EnsureSuccessStatusCode();
  51. var responseContent = await response.Content.ReadAsStringAsync();
  52. var doubaoResponse = JsonConvert.DeserializeObject<DoubaoResponse>(responseContent);
  53. return doubaoResponse.choices[0].message.content;
  54. }
  55. }
  56. }