DeepSeekService.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. using System.Net.Http;
  2. using System.Net.Http.Headers;
  3. using System.Text.Json;
  4. using System.Text.Json.Serialization;
  5. using JsonSerializer = System.Text.Json.JsonSerializer;
  6. using System.IO;
  7. namespace OASystem.API.OAMethodLib.DeepSeekAPI
  8. {
  9. /// <summary>
  10. /// DeepSeek API 服务实现
  11. /// </summary>
  12. public class DeepSeekService : IDeepSeekService
  13. {
  14. private readonly HttpClient _httpClient;
  15. private readonly ILogger<DeepSeekService> _logger;
  16. private readonly IHostEnvironment _hostEnvironment;
  17. /// <summary>
  18. /// 配置文件
  19. /// </summary>
  20. private DeepSeek DeepSeek { get; set; }
  21. /// <summary>
  22. /// 构造函数
  23. /// </summary>
  24. public DeepSeekService(IHostEnvironment hostEnvironment, ILogger<DeepSeekService> logger, HttpClient httpClient)
  25. {
  26. _hostEnvironment = hostEnvironment;
  27. _httpClient = httpClient;
  28. _logger = logger;
  29. DeepSeek = AutofacIocManager.Instance.GetService<DeepSeek>();
  30. // 设置基础地址和认证头
  31. _httpClient.BaseAddress = new Uri(DeepSeek.BaseAddress ?? "https://api.deepseek.com/v1/");
  32. _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", DeepSeek.ApiKey);
  33. _httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
  34. }
  35. /// <summary>
  36. /// 测试API连通性
  37. /// </summary>
  38. /// <returns></returns>
  39. public async Task<bool> TestApiConnectivityAsync()
  40. {
  41. try
  42. {
  43. var response = await _httpClient.GetAsync("models");
  44. return response.IsSuccessStatusCode;
  45. }
  46. catch
  47. {
  48. return false;
  49. }
  50. }
  51. /// <summary>
  52. /// 检查可用端点
  53. /// </summary>
  54. /// <returns></returns>
  55. public async Task<List<string>> DiscoverAvailableEndpointsAsync()
  56. {
  57. var endpoints = new List<string>
  58. {
  59. "models",
  60. "chat/completions",
  61. "files",
  62. "uploads",
  63. "documents",
  64. "assistants"
  65. };
  66. var availableEndpoints = new List<string>();
  67. foreach (var endpoint in endpoints)
  68. {
  69. try
  70. {
  71. var response = await _httpClient.GetAsync(endpoint);
  72. if (response.IsSuccessStatusCode)
  73. {
  74. availableEndpoints.Add(endpoint);
  75. Console.WriteLine($"✅ 端点可用: {endpoint}");
  76. }
  77. else
  78. {
  79. Console.WriteLine($"❌ 端点不可用: {endpoint} - {response.StatusCode}");
  80. }
  81. }
  82. catch (Exception ex)
  83. {
  84. Console.WriteLine($"⚠️ 端点检查错误: {endpoint} - {ex.Message}");
  85. }
  86. }
  87. return availableEndpoints;
  88. }
  89. /// <summary>
  90. /// 上传文件到DeepSeek API
  91. /// </summary>
  92. public async Task<DeepSeekFileUploadResponse> UploadFileAsync(IFormFile file, string purpose = "assistants")
  93. {
  94. try
  95. {
  96. _logger.LogInformation("开始上传文件: {FileName}, 大小: {Size} bytes", file.FileName, file.Length);
  97. // 检查文件大小
  98. if (file.Length > 512 * 1024 * 1024) // 512MB限制
  99. {
  100. throw new Exception($"文件大小超过限制: {file.Length} bytes");
  101. }
  102. using var content = new MultipartFormDataContent();
  103. using var fileStream = file.OpenReadStream();
  104. var fileContent = new StreamContent(fileStream);
  105. fileContent.Headers.ContentType = new MediaTypeHeaderValue(GetContentType(file.FileName));
  106. content.Add(fileContent, "file", file.FileName);
  107. content.Add(new StringContent(purpose), "purpose");
  108. var response = await _httpClient.PostAsync("files", content);
  109. _logger.LogInformation("文件上传路径:{filePath}", response.RequestMessage.RequestUri);
  110. response.EnsureSuccessStatusCode();
  111. var responseContent = await response.Content.ReadAsStringAsync();
  112. var result = JsonSerializer.Deserialize<DeepSeekFileUploadResponse>(responseContent, new JsonSerializerOptions
  113. {
  114. PropertyNameCaseInsensitive = true
  115. });
  116. _logger.LogInformation("文件上传成功: {FileName}, FileId: {FileId}", file.FileName, result.Id);
  117. return result;
  118. }
  119. catch (Exception ex)
  120. {
  121. _logger.LogError(ex, "文件上传失败: {FileName}", file.FileName);
  122. throw;
  123. }
  124. }
  125. /// <summary>
  126. /// 批量上传文件
  127. /// </summary>
  128. public async Task<List<FileUploadResult>> UploadFilesAsync(List<IFormFile> files, string purpose = "assistants")
  129. {
  130. var results = new List<FileUploadResult>();
  131. foreach (var file in files)
  132. {
  133. var result = new FileUploadResult
  134. {
  135. FileName = file.FileName,
  136. FileSize = file.Length
  137. };
  138. try
  139. {
  140. var uploadResponse = await UploadFileAsync(file, purpose);
  141. result.FileId = uploadResponse.Id;
  142. result.Success = true;
  143. result.Status = uploadResponse.Status;
  144. result.Message = "上传成功";
  145. }
  146. catch (Exception ex)
  147. {
  148. result.Success = false;
  149. result.Message = $"上传失败: {ex.Message}";
  150. result.Status = "error";
  151. }
  152. results.Add(result);
  153. }
  154. return results;
  155. }
  156. /// <summary>
  157. /// 获取文件列表
  158. /// </summary>
  159. public async Task<DeepSeekFileListResponse> ListFilesAsync()
  160. {
  161. try
  162. {
  163. var response = await _httpClient.GetAsync("files");
  164. response.EnsureSuccessStatusCode();
  165. var responseContent = await response.Content.ReadAsStringAsync();
  166. return JsonSerializer.Deserialize<DeepSeekFileListResponse>(responseContent, new JsonSerializerOptions
  167. {
  168. PropertyNameCaseInsensitive = true
  169. });
  170. }
  171. catch (Exception ex)
  172. {
  173. _logger.LogError(ex, "获取文件列表失败");
  174. throw;
  175. }
  176. }
  177. /// <summary>
  178. /// 获取文件信息
  179. /// </summary>
  180. public async Task<DeepSeekFileUploadResponse> GetFileInfoAsync(string fileId)
  181. {
  182. try
  183. {
  184. var response = await _httpClient.GetAsync($"files/{fileId}");
  185. response.EnsureSuccessStatusCode();
  186. var responseContent = await response.Content.ReadAsStringAsync();
  187. return JsonSerializer.Deserialize<DeepSeekFileUploadResponse>(responseContent, new JsonSerializerOptions
  188. {
  189. PropertyNameCaseInsensitive = true
  190. });
  191. }
  192. catch (Exception ex)
  193. {
  194. _logger.LogError(ex, "获取文件信息失败: {FileId}", fileId);
  195. throw;
  196. }
  197. }
  198. /// <summary>
  199. /// 删除文件
  200. /// </summary>
  201. public async Task<bool> DeleteFileAsync(string fileId)
  202. {
  203. try
  204. {
  205. var response = await _httpClient.DeleteAsync($"files/{fileId}");
  206. response.EnsureSuccessStatusCode();
  207. _logger.LogInformation("文件删除成功: {FileId}", fileId);
  208. return true;
  209. }
  210. catch (Exception ex)
  211. {
  212. _logger.LogError(ex, "文件删除失败: {FileId}", fileId);
  213. return false;
  214. }
  215. }
  216. /// <summary>
  217. /// 使用已上传的文件进行聊天
  218. /// </summary>
  219. public async Task<ApiResponse> ChatWithFilesAsync(List<string> fileIds, string question, string model = "deepseek-chat", float temperature = 0.7f, int maxTokens = 4000)
  220. {
  221. try
  222. {
  223. // 等待所有文件处理完成
  224. var processedFiles = new List<DeepSeekFileUploadResponse>();
  225. foreach (var fileId in fileIds)
  226. {
  227. var fileInfo = await WaitForFileProcessingAsync(fileId);
  228. processedFiles.Add(fileInfo);
  229. }
  230. // 构建消息内容
  231. var messageContent = new List<object>
  232. {
  233. new { type = "text", text = question }
  234. };
  235. // 添加文件引用
  236. foreach (var file in processedFiles)
  237. {
  238. messageContent.Add(new
  239. {
  240. type = "file",
  241. file_id = file.Id
  242. });
  243. }
  244. var request = new DeepSeekChatWithFilesRequest
  245. {
  246. Model = model,
  247. Messages = new List<FileMessage>
  248. {
  249. new FileMessage
  250. {
  251. Role = "user",
  252. Content = messageContent
  253. }
  254. },
  255. Temperature = temperature,
  256. MaxTokens = maxTokens
  257. };
  258. var jsonContent = JsonSerializer.Serialize(request, new JsonSerializerOptions
  259. {
  260. PropertyNamingPolicy = JsonNamingPolicy.CamelCase
  261. });
  262. var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
  263. var response = await _httpClient.PostAsync("chat/completions", httpContent);
  264. response.EnsureSuccessStatusCode();
  265. var responseContent = await response.Content.ReadAsStringAsync();
  266. var chatResponse = JsonSerializer.Deserialize<DeepSeekResponse>(responseContent, new JsonSerializerOptions
  267. {
  268. PropertyNameCaseInsensitive = true
  269. });
  270. return new ApiResponse
  271. {
  272. Success = true,
  273. Message = "聊天成功",
  274. Answer = chatResponse.Choices[0].Message.Content,
  275. TokensUsed = chatResponse.Usage.TotalTokens
  276. };
  277. }
  278. catch (Exception ex)
  279. {
  280. _logger.LogError(ex, "使用文件聊天失败");
  281. throw;
  282. }
  283. }
  284. /// <summary>
  285. /// 使用进行聊天
  286. /// </summary>
  287. public async Task<ApiResponse> ChatAsync(string question, string model = "deepseek-chat", float temperature = 0.7f, int maxTokens = 4000)
  288. {
  289. try
  290. {
  291. // 构建消息内容
  292. var messageContent = new List<object>
  293. {
  294. new { type = "text", text = question }
  295. };
  296. var request = new DeepSeekChatWithFilesRequest
  297. {
  298. Model = model,
  299. Messages = new List<FileMessage>
  300. {
  301. new FileMessage
  302. {
  303. Role = "user",
  304. Content = messageContent
  305. }
  306. },
  307. Temperature = temperature,
  308. MaxTokens = maxTokens
  309. };
  310. var jsonContent = JsonSerializer.Serialize(request, new JsonSerializerOptions
  311. {
  312. PropertyNamingPolicy = JsonNamingPolicy.CamelCase
  313. });
  314. var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
  315. var response = await _httpClient.PostAsync("chat/completions", httpContent);
  316. response.EnsureSuccessStatusCode();
  317. var responseContent = await response.Content.ReadAsStringAsync();
  318. var chatResponse = JsonSerializer.Deserialize<DeepSeekResponse>(responseContent, new JsonSerializerOptions
  319. {
  320. PropertyNameCaseInsensitive = true
  321. });
  322. return new ApiResponse
  323. {
  324. Success = true,
  325. Message = "聊天成功",
  326. Answer = chatResponse.Choices[0].Message.Content,
  327. TokensUsed = chatResponse.Usage.TotalTokens
  328. };
  329. }
  330. catch (Exception ex)
  331. {
  332. _logger.LogError(ex, "使用文件聊天失败");
  333. throw;
  334. }
  335. }
  336. /// <summary>
  337. /// 等待文件处理完成
  338. /// </summary>
  339. public async Task<DeepSeekFileUploadResponse> WaitForFileProcessingAsync(string fileId, int timeoutSeconds = 60)
  340. {
  341. var startTime = DateTime.UtcNow;
  342. var timeout = TimeSpan.FromSeconds(timeoutSeconds);
  343. while (DateTime.UtcNow - startTime < timeout)
  344. {
  345. var fileInfo = await GetFileInfoAsync(fileId);
  346. if (fileInfo.Status == "processed")
  347. {
  348. _logger.LogInformation("文件处理完成: {FileId}", fileId);
  349. return fileInfo;
  350. }
  351. else if (fileInfo.Status == "error")
  352. {
  353. throw new Exception($"文件处理失败: {fileId}");
  354. }
  355. // 等待2秒后重试
  356. await Task.Delay(2000);
  357. }
  358. throw new TimeoutException($"文件处理超时: {fileId}");
  359. }
  360. /// <summary>
  361. /// 根据文件名获取Content-Type
  362. /// </summary>
  363. private static string GetContentType(string fileName)
  364. {
  365. var extension = Path.GetExtension(fileName).ToLower();
  366. return extension switch
  367. {
  368. ".txt" => "text/plain",
  369. ".pdf" => "application/pdf",
  370. ".json" => "application/json",
  371. ".csv" => "text/csv",
  372. ".html" => "text/html",
  373. ".htm" => "text/html",
  374. ".md" => "text/markdown",
  375. _ => "application/octet-stream"
  376. };
  377. }
  378. #region 项目相关
  379. /// <summary>
  380. /// 读取项目内的指定文件并转换为IFormFile
  381. /// </summary>
  382. public async Task<ProjectFileReadResponse> ReadProjectFilesAsync(List<string> relativePaths)
  383. {
  384. var response = new ProjectFileReadResponse();
  385. var projectRoot = GetProjectRootPath();
  386. if (projectRoot.Contains("OASystem.Api"))
  387. {
  388. projectRoot = projectRoot.Replace("OASystem.Api", "");
  389. }
  390. _logger.LogInformation("开始读取项目文件,数量: {Count}", relativePaths.Count);
  391. foreach (var relativePath in relativePaths)
  392. {
  393. var fileInfo = new ProjectFileInfo
  394. {
  395. RelativePath = relativePath
  396. };
  397. try
  398. {
  399. var fullPath = Path.Combine(projectRoot, relativePath);
  400. fileInfo.FullPath = fullPath;
  401. if (!System.IO.File.Exists(fullPath))
  402. {
  403. throw new FileNotFoundException($"文件不存在: {relativePath}");
  404. }
  405. var fileInfoObj = new FileInfo(fullPath);
  406. fileInfo.FileSize = fileInfoObj.Length;
  407. fileInfo.LastModified = fileInfoObj.LastWriteTime;
  408. // 转换为IFormFile
  409. fileInfo.FormFile = await ConvertToFormFileAsync(fullPath);
  410. fileInfo.Success = true;
  411. _logger.LogInformation("文件读取成功: {FileName}, 大小: {Size} bytes", relativePath, fileInfo.FileSize);
  412. }
  413. catch (Exception ex)
  414. {
  415. fileInfo.Success = false;
  416. fileInfo.ErrorMessage = ex.Message;
  417. _logger.LogError(ex, "文件读取失败: {FileName}", relativePath);
  418. }
  419. response.FileInfos.Add(fileInfo);
  420. }
  421. response.Success = response.SuccessCount > 0;
  422. response.Message = $"成功读取 {response.SuccessCount} 个文件,失败 {response.FailureCount} 个";
  423. return response;
  424. }
  425. /// <summary>
  426. /// 读取项目内指定目录的文件
  427. /// </summary>
  428. public async Task<ProjectFileReadResponse> ReadProjectDirectoryAsync(string directoryPath, string searchPattern = "*.cs", bool recursive = false)
  429. {
  430. var response = new ProjectFileReadResponse();
  431. var projectRoot = GetProjectRootPath();
  432. var fullDirectoryPath = Path.Combine(projectRoot, directoryPath);
  433. _logger.LogInformation("开始读取目录文件: {Directory}, 模式: {Pattern}", directoryPath, searchPattern);
  434. if (!Directory.Exists(fullDirectoryPath))
  435. {
  436. response.Success = false;
  437. response.Message = $"目录不存在: {directoryPath}";
  438. return response;
  439. }
  440. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  441. var files = Directory.GetFiles(fullDirectoryPath, searchPattern, searchOption);
  442. _logger.LogInformation("找到 {FileCount} 个文件", files.Length);
  443. foreach (var filePath in files)
  444. {
  445. var relativePath = Path.GetRelativePath(projectRoot, filePath);
  446. var fileInfo = new ProjectFileInfo
  447. {
  448. RelativePath = relativePath,
  449. FullPath = filePath
  450. };
  451. try
  452. {
  453. var fileInfoObj = new FileInfo(filePath);
  454. fileInfo.FileSize = fileInfoObj.Length;
  455. fileInfo.LastModified = fileInfoObj.LastWriteTime;
  456. // 转换为IFormFile
  457. fileInfo.FormFile = await ConvertToFormFileAsync(filePath);
  458. fileInfo.Success = true;
  459. _logger.LogDebug("文件读取成功: {FileName}", relativePath);
  460. }
  461. catch (Exception ex)
  462. {
  463. fileInfo.Success = false;
  464. fileInfo.ErrorMessage = ex.Message;
  465. _logger.LogError(ex, "文件读取失败: {FileName}", relativePath);
  466. }
  467. response.FileInfos.Add(fileInfo);
  468. }
  469. response.Success = response.SuccessCount > 0;
  470. response.Message = $"成功读取 {response.SuccessCount} 个文件,失败 {response.FailureCount} 个";
  471. return response;
  472. }
  473. /// <summary>
  474. /// 获取项目根目录路径
  475. /// </summary>
  476. public string GetProjectRootPath()
  477. {
  478. // 在开发环境中使用ContentRootPath,在生产环境中可能需要调整
  479. return _hostEnvironment.ContentRootPath;
  480. }
  481. /// <summary>
  482. /// 检查文件是否存在
  483. /// </summary>
  484. public bool FileExists(string relativePath)
  485. {
  486. var fullPath = Path.Combine(GetProjectRootPath(), relativePath);
  487. return System.IO.File.Exists(fullPath);
  488. }
  489. /// <summary>
  490. /// 将物理文件转换为IFormFile
  491. /// </summary>
  492. public async Task<IFormFile> ConvertToFormFileAsync(string filePath)
  493. {
  494. var fileInfo = new FileInfo(filePath);
  495. var fileName = Path.GetFileName(filePath);
  496. // 读取文件内容
  497. byte[] fileBytes;
  498. using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  499. {
  500. fileBytes = new byte[fileStream.Length];
  501. await fileStream.ReadAsync(fileBytes, 0, (int)fileStream.Length);
  502. }
  503. // 创建IFormFile
  504. return new FormFile(
  505. new MemoryStream(fileBytes),
  506. 0,
  507. fileBytes.Length,
  508. "file",
  509. fileName)
  510. {
  511. Headers = new HeaderDictionary(),
  512. ContentType = GetFileContentType(fileName)
  513. };
  514. }
  515. /// <summary>
  516. /// 根据文件名获取Content-Type
  517. /// </summary>
  518. private string GetFileContentType(string fileName)
  519. {
  520. var extension = Path.GetExtension(fileName).ToLower();
  521. return extension switch
  522. {
  523. ".cs" => "text/plain",
  524. ".txt" => "text/plain",
  525. ".json" => "application/json",
  526. ".xml" => "application/xml",
  527. ".html" => "text/html",
  528. ".htm" => "text/html",
  529. ".css" => "text/css",
  530. ".js" => "application/javascript",
  531. ".ts" => "application/typescript",
  532. ".py" => "text/x-python",
  533. ".java" => "text/x-java",
  534. ".cpp" => "text/x-c++",
  535. ".c" => "text/x-c",
  536. ".h" => "text/x-c",
  537. ".md" => "text/markdown",
  538. _ => "application/octet-stream"
  539. };
  540. }
  541. /// <summary>
  542. /// 读取特定的签证申请表单文件
  543. /// </summary>
  544. /// <param name="fileName"></param>
  545. /// <returns></returns>
  546. public async Task<ProjectFileReadResponse> ReadVisaFormFileAsync(string fileName)
  547. {
  548. var specificPath = $@"OASystem\OASystem.Domain\ViewModels\VisaFormDetails\{fileName}";
  549. return await ReadProjectFilesAsync(new List<string> { specificPath });
  550. }
  551. /// <summary>
  552. /// 读取OASystem项目中的所有CS文件
  553. /// </summary>
  554. public async Task<ProjectFileReadResponse> ReadOASystemFilesAsync(string searchPattern = "*.cs", bool recursive = true)
  555. {
  556. return await ReadProjectDirectoryAsync(@"OASystem", searchPattern, recursive);
  557. }
  558. /// <summary>
  559. /// 读取指定域模型中的CS文件
  560. /// </summary>
  561. public async Task<ProjectFileReadResponse> ReadDomainViewModelsAsync(string searchPattern = "*.cs", bool recursive = true)
  562. {
  563. return await ReadProjectDirectoryAsync(@"OASystem\OASystem.Domain\ViewModels", searchPattern, recursive);
  564. }
  565. /// <summary>
  566. /// 读取签证表单相关的所有CS文件
  567. /// </summary>
  568. public async Task<ProjectFileReadResponse> ReadVisaFormFilesAsync(string searchPattern = "*.cs", bool recursive = true)
  569. {
  570. return await ReadProjectDirectoryAsync(@"OASystem\OASystem.Domain\ViewModels\VisaFormDetails", searchPattern, recursive);
  571. }
  572. #endregion
  573. }
  574. #region 私有实体类
  575. /// <summary>
  576. /// DeepSeek 聊天响应(用于反序列化)
  577. /// </summary>
  578. internal class DeepSeekResponse
  579. {
  580. [JsonPropertyName("choices")]
  581. public List<Choice> Choices { get; set; }
  582. [JsonPropertyName("usage")]
  583. public Usage Usage { get; set; }
  584. }
  585. internal class Choice
  586. {
  587. [JsonPropertyName("message")]
  588. public Message Message { get; set; }
  589. }
  590. internal class Message
  591. {
  592. [JsonPropertyName("content")]
  593. public string Content { get; set; }
  594. }
  595. internal class Usage
  596. {
  597. [JsonPropertyName("total_tokens")]
  598. public int TotalTokens { get; set; }
  599. }
  600. #endregion
  601. }