| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- using Newtonsoft.Json;
- using System.Net.Http.Headers;
- using System.Text;
- namespace OASystem.API.OAMethodLib.DoubaoAPI
- {
- public class DoubaoService : IDoubaoService
- {
- private readonly IHttpClientFactory _httpClientFactory;
- private readonly DoubaoSetting _doubaoSetting;
- private readonly ILogger<DoubaoService> _logger;
- public DoubaoService(IHttpClientFactory httpClientFactory, DoubaoSetting doubaoSetting, ILogger<DoubaoService> logger)
- {
- _httpClientFactory = httpClientFactory;
- _doubaoSetting = doubaoSetting;
- _logger = logger;
- }
- public async Task<string> CompleteChatAsync(List<DouBaoChatMessage> messages, CompleteChatOptions? options)
- {
- if (messages == null || !messages.Any())
- {
- _logger.LogError("消息不能为空 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
- return null;
- }
- if(!messages.Any(x => x.Role == DouBaoRole.system)){
- messages.Insert(0,
- new DouBaoChatMessage() {
- Role = DouBaoRole.system, Content = "你是一个专业的AI助手,请根据用户的问题给出回答"
- });
- }
- options ??= new CompleteChatOptions();
- var httpClient = _httpClientFactory.CreateClient("Doubao");
- httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _doubaoSetting.ApiKey);
- var body = new Dictionary<string, object>
- {
- ["model"] = _doubaoSetting.EndpointId,
- ["messages"] = messages.Select(x => new { role = x.Role.ToString(), content = x.Content }).ToArray()
- };
- if (options.ThinkingOptions.IsThinking)
- {
- body["reasoning_effort"] = options.ThinkingOptions.ReasoningEffort.ToString().ToLower();
- body["thinking"] = new {
- type = "enabled",
- };
- }
- var json = JsonConvert.SerializeObject(body);
- var response = await httpClient.PostAsync(
- _doubaoSetting.BaseAddress,
- new StringContent(json, Encoding.UTF8, "application/json")
- );
- response.EnsureSuccessStatusCode();
- var responseContent = await response.Content.ReadAsStringAsync();
- var doubaoResponse = JsonConvert.DeserializeObject<DoubaoResponse>(responseContent);
- return doubaoResponse.choices[0].message.content;
- }
- }
- }
|