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 _logger; public DoubaoService(IHttpClientFactory httpClientFactory, DoubaoSetting doubaoSetting, ILogger logger) { _httpClientFactory = httpClientFactory; _doubaoSetting = doubaoSetting; _logger = logger; } public async Task CompleteChatAsync(List 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 { ["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(responseContent); return doubaoResponse.choices[0].message.content; } } }