AITestController.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. using Flurl.Http.Configuration;
  2. using OASystem.API.OAMethodLib.DoubaoAPI;
  3. using OASystem.API.OAMethodLib.Hotmail;
  4. using OASystem.API.OAMethodLib.HunYuanAPI;
  5. using OASystem.API.OAMethodLib.QiYeWeChatAPI;
  6. using OASystem.Domain.ViewModels.QiYeWeChat;
  7. using System.IdentityModel.Tokens.Jwt;
  8. using System.Text.Json;
  9. using static OASystem.API.OAMethodLib.Hotmail.HotmailService;
  10. namespace OASystem.API.Controllers
  11. {
  12. /// <summary>
  13. /// AI测试控制器
  14. /// </summary>
  15. [Route("api/[controller]")]
  16. public class AITestController : ControllerBase
  17. {
  18. private readonly IHunyuanService _hunyuanService;
  19. private readonly IDoubaoService _doubaoService;
  20. private readonly ILogger<AITestController> _logger;
  21. private readonly IConfiguration _config;
  22. private readonly IQiYeWeChatApiService _qiYeWeChatApiService;
  23. private readonly System.Net.Http.IHttpClientFactory _httpClientFactory;
  24. private readonly HotmailService _hotmailService;
  25. public AITestController(IHunyuanService hunyuanService, IDoubaoService doubaoService, ILogger<AITestController> logger, IQiYeWeChatApiService qiYeWeChatApiService, HotmailService hotmailService, System.Net.Http.IHttpClientFactory httpClientFactory, IConfiguration config)
  26. {
  27. _hunyuanService = hunyuanService;
  28. _doubaoService = doubaoService;
  29. _logger = logger;
  30. _qiYeWeChatApiService = qiYeWeChatApiService;
  31. _hotmailService = hotmailService;
  32. _httpClientFactory = httpClientFactory;
  33. _config = config;
  34. }
  35. #region 企业微信发送邮件测试
  36. /// <summary>
  37. /// 企业微信发送邮件测试
  38. /// </summary>
  39. [HttpPost("sendEmail")]
  40. public async Task<ActionResult<string>> SendEmail([FromForm] IFormFile[] feils)
  41. {
  42. try
  43. {
  44. var req = new EmailRequestDto()
  45. {
  46. ToEmails = new List<string> { "johnny.yang@pan-american-intl.com" },
  47. CcEmails = new List<string> { "Roy.lei@pan-american-intl.com" },
  48. BccEmails = new List<string> { "Roy.lei@pan-american-intl.com" },
  49. Subject = "测试邮件 - 来自企业微信API",
  50. Body = "这是一封通过企业微信API发送的测试邮件,包含附件。",
  51. Files = feils
  52. };
  53. var response = await _qiYeWeChatApiService.EmailSendAsync(req);
  54. return Ok(response);
  55. }
  56. catch (Exception ex)
  57. {
  58. _logger.LogError(ex, "调用企业微信邮件API失败。");
  59. return StatusCode(500, new { Message = "调用企业微信邮件API失败,请检查配置或网络。", Detail = ex.Message });
  60. }
  61. }
  62. #endregion
  63. #region 豆包 AI
  64. /// <summary>
  65. /// 豆包基础对话
  66. /// </summary>
  67. [HttpPost("doubao-chat")]
  68. public async Task<ActionResult<string>> DoubaoChat(string question, bool isThinking = false)
  69. {
  70. try
  71. {
  72. var messages = new List<DouBaoChatMessage>
  73. {
  74. new DouBaoChatMessage { Role = DouBaoRole.user, Content = question }
  75. };
  76. var options = new CompleteChatOptions
  77. {
  78. ThinkingOptions = new thinkingOptions { IsThinking = isThinking }
  79. };
  80. var response = await _doubaoService.CompleteChatAsync(messages, options);
  81. return Ok(response);
  82. }
  83. catch (Exception ex)
  84. {
  85. _logger.LogError(ex, "调用豆包API失败。");
  86. return StatusCode(500, new { Message = "调用豆包API失败", Detail = ex.Message });
  87. }
  88. }
  89. /// <summary>
  90. /// 豆包上传文件
  91. /// </summary>
  92. [HttpPost("doubao-upload")]
  93. public async Task<ActionResult<DoubaoFileResponse>> DoubaoUpload(IFormFile file, string purpose = "user_data")
  94. {
  95. if (file == null || file.Length == 0)
  96. return BadRequest("请选择要上传的文件");
  97. try
  98. {
  99. var stream = file.OpenReadStream();
  100. var existsFileExpand = new List<string> { "pdf", "docx" };
  101. if (!existsFileExpand.Contains(file.FileName.Split('.').Last().ToLower()))
  102. {
  103. return BadRequest("请上传pdf、docx文件!不支持其他文件");
  104. }
  105. if (file.FileName.Split('.').Last().ToLower() == "docx")
  106. {
  107. using var docxStream = file.OpenReadStream();
  108. var pdfStream = DoubaoService.ConvertDocxStreamToPdfStream(docxStream);
  109. stream = pdfStream;
  110. }
  111. var response = await _doubaoService.UploadFileAsync(stream, file.FileName, purpose);
  112. stream.Dispose();
  113. return Ok(response);
  114. }
  115. catch (Exception ex)
  116. {
  117. _logger.LogError(ex, "豆包上传文件失败");
  118. return StatusCode(500, new { Message = "上传失败", Detail = ex.Message });
  119. }
  120. }
  121. /// <summary>
  122. /// 豆包获取文件列表
  123. /// </summary>
  124. [HttpGet("doubao-files")]
  125. public async Task<ActionResult<DoubaoFileListResponse>> DoubaoListFiles()
  126. {
  127. try
  128. {
  129. var response = await _doubaoService.ListFilesAsync();
  130. return Ok(response);
  131. }
  132. catch (Exception ex)
  133. {
  134. _logger.LogError(ex, "获取豆包文件列表失败");
  135. return StatusCode(500, new { Message = "获取失败", Detail = ex.Message });
  136. }
  137. }
  138. /// <summary>
  139. /// 豆包删除文件
  140. /// </summary>
  141. [HttpDelete("doubao-file/{fileId}")]
  142. public async Task<ActionResult<bool>> DoubaoDeleteFile(string fileId)
  143. {
  144. try
  145. {
  146. var response = await _doubaoService.DeleteFileAsync(fileId);
  147. return Ok(response);
  148. }
  149. catch (Exception ex)
  150. {
  151. _logger.LogError(ex, "删除豆包文件失败");
  152. return StatusCode(500, new { Message = "删除失败", Detail = ex.Message });
  153. }
  154. }
  155. /// <summary>
  156. /// 豆包多模态对话(支持文本+图片)
  157. /// </summary>
  158. /// <param name="request">表单请求参数</param>
  159. [HttpPost("doubao-multimodal-chat")]
  160. public async Task<ActionResult<string>> DoubaoMultimodalChat([FromForm] DoubaoMultimodalChatRequest request)
  161. {
  162. if (string.IsNullOrWhiteSpace(request.Question))
  163. return BadRequest("问题不能为空");
  164. try
  165. {
  166. var contentItems = new List<DoubaoMultimodalContentItem>
  167. {
  168. new DoubaoMultimodalContentItem { Type = "text", Text = request.Question.Trim() }
  169. };
  170. if (!string.IsNullOrWhiteSpace(request.FileId))
  171. {
  172. contentItems.Add(new DoubaoMultimodalContentItem
  173. {
  174. Type = "file",
  175. FileId = request.FileId.Trim(),
  176. });
  177. }
  178. if (request.Image != null && request.Image.Length > 0)
  179. {
  180. using var ms = new MemoryStream();
  181. await request.Image.CopyToAsync(ms);
  182. var base64 = Convert.ToBase64String(ms.ToArray());
  183. var mimeType = request.Image.ContentType ?? "image/jpeg";
  184. var dataUrl = $"data:{mimeType};base64,{base64}";
  185. contentItems.Add(new DoubaoMultimodalContentItem
  186. {
  187. Type = "image_url",
  188. ImageUrl = new DoubaoMultimodalImageUrl { Url = dataUrl }
  189. });
  190. }
  191. var messages = new List<DoubaoMultimodalChatMessage>
  192. {
  193. new DoubaoMultimodalChatMessage
  194. {
  195. Role = "user",
  196. Content = contentItems
  197. }
  198. };
  199. var options = new CompleteMultimodalChatOptions
  200. {
  201. ThinkingOptions = new DoubaoMultimodalThinkingOptions
  202. {
  203. IsThinking = request.IsThinking,
  204. ReasoningEffort = "medium"
  205. }
  206. };
  207. var response = await _doubaoService.CompleteMultimodalChatAsync(messages, options);
  208. return Ok(response ?? string.Empty);
  209. }
  210. catch (Exception ex)
  211. {
  212. _logger.LogError(ex, "调用豆包多模态API失败。");
  213. return StatusCode(500, new { Message = "调用豆包多模态API失败", Detail = ex.Message });
  214. }
  215. }
  216. #endregion
  217. #region 混元 AI
  218. /// <summary>
  219. /// 基础对话示例
  220. /// </summary>
  221. [HttpPost("chat")]
  222. public async Task<ActionResult<string>> BasicChat(string question)
  223. {
  224. try
  225. {
  226. var response = await _hunyuanService.ChatCompletionsHunyuan_t1_latestAsync(question);
  227. return Ok(response);
  228. }
  229. catch (Exception ex)
  230. {
  231. _logger.LogError(ex, "调用腾讯云混元API失败。");
  232. return StatusCode(500, new { Message = "调用腾讯云API失败,请检查配置或网络。", Detail = ex.Message });
  233. }
  234. }
  235. /// <summary>
  236. /// 模拟“根据文件提问”的API端点
  237. /// 注意:此示例中,文件内容通过请求体传入。
  238. /// 实际场景中,文件内容可能来自用户上传并解析(如PDF、TXT解析为文本)后的结果。
  239. /// </summary>
  240. [HttpPost("ask-with-file")]
  241. public async Task<ActionResult<string>> AskBasedOnFile([FromBody] AskWithFileRequest request)
  242. {
  243. if (string.IsNullOrEmpty(request.FileContent) || string.IsNullOrEmpty(request.Question))
  244. {
  245. return BadRequest(new { Message = "FileContent和Question字段不能为空。" });
  246. }
  247. try
  248. {
  249. var answer = await _hunyuanService.AskWithFileContextAsync(request.FileContent, request.Question, request.Model);
  250. return Ok(answer);
  251. }
  252. catch (Exception ex)
  253. {
  254. _logger.LogError(ex, "处理基于文件的提问失败。");
  255. return StatusCode(500, new { Message = "处理请求失败。", Detail = ex.Message });
  256. }
  257. }
  258. /// <summary>
  259. /// 用于测试的GET端点,快速验证服务可用性(使用示例数据)
  260. /// </summary>
  261. [HttpGet("test-file-query")]
  262. public async Task<ActionResult<string>> TestFileQuery()
  263. {
  264. // 示例文件内容和问题
  265. var sampleFileContent = "在软件开发中,依赖注入(Dependency Injection)是一种设计模式,用于实现控制反转(Inversion of Control, IoC)。它允许在类外部创建依赖对象,并通过构造函数、属性或方法将其‘注入’到类中,从而降低类之间的耦合度。";
  266. var sampleQuestion = "依赖注入的主要目的是什么?";
  267. var model = "hunyuan-lite"; // 可使用 "hunyuan-pro" 等
  268. try
  269. {
  270. var answer = await _hunyuanService.AskWithFileContextAsync(sampleFileContent, sampleQuestion, model);
  271. return Ok($"测试成功。问题:'{sampleQuestion}'\n回答:{answer}");
  272. }
  273. catch (Exception ex)
  274. {
  275. _logger.LogError(ex, "测试文件提问失败。");
  276. return StatusCode(500, new { Message = "测试失败。", Detail = ex.Message });
  277. }
  278. }
  279. /// <summary>
  280. /// 用于“根据文件提问”的请求体
  281. /// </summary>
  282. public class AskWithFileRequest
  283. {
  284. public string FileContent { get; set; } = string.Empty;
  285. public string Question { get; set; } = string.Empty;
  286. public string Model { get; set; } = "hunyuan-lite";
  287. }
  288. /// <summary>
  289. /// 豆包多模态对话请求体(form-data)
  290. /// </summary>
  291. public class DoubaoMultimodalChatRequest
  292. {
  293. public string Question { get; set; } = string.Empty;
  294. public IFormFile? Image { get; set; }
  295. public bool IsThinking { get; set; } = false;
  296. public string FileId { get; set; } = string.Empty;
  297. }
  298. #endregion
  299. /// <summary>
  300. /// hotmail 发送邮件
  301. /// </summary>
  302. [HttpPost("hotmailSeed")]
  303. public async Task<ActionResult<string>> HotmailSeed()
  304. {
  305. await _hotmailService.SendMailAsync(
  306. //"Roy.Lei.Atom@hotmail.com",
  307. "925554512@qq.com",
  308. //"johnny.yang@pan-american-intl.com",
  309. new HotmailService.MailDto() {
  310. Subject = "系统提醒",
  311. Content = "<p>这是一封Homail 发送的测试邮件</p>",
  312. //To = "Roy.lei@pan-american-intl.com"
  313. To = "johnny.yang@pan-american-intl.com"
  314. });
  315. return StatusCode(200, new { Message = "操作成功。" });
  316. }
  317. /// <summary>
  318. /// hotmail 发送邮件
  319. /// </summary>
  320. [HttpPost("HotmailMerged")]
  321. public async Task<ActionResult<string>> HotmailMerged()
  322. {
  323. // 1. 获取当前北京时间 (CST)
  324. var cstZone = CommonFun.GetCstZone();
  325. var nowInCst = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cstZone);
  326. // 2. 构造昨天的北京时间范围:00:00:00 到 23:59:59
  327. var yesterdayStart = nowInCst.Date.AddDays(-1); // 昨天的 00:00:00
  328. var yesterdayEnd = yesterdayStart.AddDays(1).AddTicks(-1); // 昨天的 23:59:59
  329. var res = await _hotmailService.GetMergedMessagesAsync(
  330. new List<string>() { "925554512@qq.com" },
  331. yesterdayStart,
  332. yesterdayEnd
  333. );
  334. return StatusCode(200, res);
  335. }
  336. #region 微软 auth
  337. [HttpGet("auth/url")]
  338. public IActionResult GetAuthUrl()
  339. {
  340. var clientId = _config["AzureHotmail:ClientId"];
  341. var redirectUri = _config["AzureHotmail:RedirectUri"]; // 需在 Azure Portal 注册
  342. var scope = Uri.EscapeDataString("offline_access Mail.Read Mail.Send User.Read");
  343. var url = $"https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={clientId}&response_type=code&redirect_uri={redirectUri}&response_mode=query&scope={scope}&state=alchemist";
  344. return Ok(new { authUrl = url });
  345. }
  346. [HttpGet("auth/callback")]
  347. public async Task<IActionResult> HandleCallback([FromQuery] string code)
  348. {
  349. if (string.IsNullOrEmpty(code)) return BadRequest("授权码无效");
  350. // 1. 换取令牌
  351. var httpClient = _httpClientFactory.CreateClient();
  352. var tokenRequest = new FormUrlEncodedContent(new Dictionary<string, string>
  353. {
  354. { "client_id", _config["AzureHotmail:ClientId"] },
  355. { "client_secret", _config["AzureHotmail:ClientSecret"] },
  356. { "code", code },
  357. { "redirect_uri", _config["AzureHotmail:RedirectUri"] },
  358. { "grant_type", "authorization_code" }
  359. });
  360. var response = await httpClient.PostAsync("https://login.microsoftonline.com/common/oauth2/v2.0/token", tokenRequest);
  361. var json = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
  362. if (!response.IsSuccessStatusCode) return BadRequest(json.RootElement.ToString());
  363. var root = json.RootElement;
  364. var accessToken = root.GetProperty("access_token").GetString()!;
  365. var refreshToken = root.GetProperty("refresh_token").GetString()!;
  366. var expiresIn = root.GetProperty("expires_in").GetInt32();
  367. // 2. 自动识别账户身份 【核心重构】:不再手动解析 JWT,而是请求 Graph 的 /me 接口
  368. string userEmail = await GetEmailFromGraphApiAsync(accessToken);
  369. // 3. 炼金产物:构造并存入 Redis
  370. var userToken = new UserToken
  371. {
  372. Email = userEmail,
  373. AccessToken = accessToken,
  374. RefreshToken = refreshToken,
  375. ExpiresAt = DateTime.UtcNow.AddSeconds(expiresIn)
  376. };
  377. // 存入 Redis (使用我们之前的 RedisKeyPrefix: "MailAlchemy:Token:")
  378. var redisKey = $"MailAlchemy:Token:{userEmail}";
  379. await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync<string>(redisKey, System.Text.Json.JsonSerializer.Serialize(userToken), TimeSpan.FromDays(90));
  380. return Ok(new
  381. {
  382. status = "Success",
  383. account = userEmail,
  384. message = "该个人账户已成功集成并启用分布式存储"
  385. });
  386. }
  387. private async Task<string> GetEmailFromGraphApiAsync(string accessToken)
  388. {
  389. var httpClient = _httpClientFactory.CreateClient();
  390. // 使用 AccessToken 调用 Graph API 的个人信息接口
  391. httpClient.DefaultRequestHeaders.Authorization =
  392. new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
  393. var response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me");
  394. if (!response.IsSuccessStatusCode)
  395. throw new Exception("无法通过 Graph API 获取用户信息");
  396. using var doc = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
  397. var root = doc.RootElement;
  398. // 个人账户优先取 mail,如果没有则取 userPrincipalName
  399. return root.GetProperty("mail").GetString()
  400. ?? root.GetProperty("userPrincipalName").GetString()
  401. ?? throw new Exception("未能获取有效的 Email 地址");
  402. }
  403. #endregion
  404. }
  405. }