DeepSeekService.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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. /// <param name="question"></param>
  288. /// <param name="model"></param>
  289. /// <param name="stream"></param>
  290. /// <param name="temperature"></param>
  291. /// <param name="maxTokens"></param>
  292. /// <returns></returns>
  293. public async Task<ApiResponse> ChatAsync(string question, bool stream = false, string model = "deepseek-chat", float temperature = 0.7f, int maxTokens = 4000)
  294. {
  295. try
  296. {
  297. // 构建消息内容
  298. var messageContent = new List<object>
  299. {
  300. new { type = "text", text = question }
  301. };
  302. var request = new DeepSeekChatWithFilesRequest
  303. {
  304. Model = model,
  305. Messages = new List<FileMessage>
  306. {
  307. new FileMessage
  308. {
  309. Role = "user",
  310. Content = messageContent
  311. }
  312. },
  313. Stream = stream,
  314. Temperature = temperature,
  315. MaxTokens = maxTokens,
  316. TopP = 0.9M,
  317. FrequencyPenalty = 0.2M,
  318. PresencePenalty = 0.1M,
  319. };
  320. var jsonContent = JsonSerializer.Serialize(request, new JsonSerializerOptions
  321. {
  322. PropertyNamingPolicy = JsonNamingPolicy.CamelCase
  323. });
  324. _httpClient.Timeout = TimeSpan.FromMinutes(10);
  325. var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
  326. var response = await _httpClient.PostAsync("chat/completions", httpContent);
  327. response.EnsureSuccessStatusCode();
  328. var responseContent = await response.Content.ReadAsStringAsync();
  329. var chatResponse = JsonSerializer.Deserialize<DeepSeekResponse>(responseContent, new JsonSerializerOptions
  330. {
  331. PropertyNameCaseInsensitive = true
  332. });
  333. return new ApiResponse
  334. {
  335. Success = true,
  336. Message = "聊天成功",
  337. Answer = chatResponse.Choices[0].Message.Content,
  338. TokensUsed = chatResponse.Usage.TotalTokens
  339. };
  340. }
  341. catch (Exception ex)
  342. {
  343. _logger.LogError(ex, "使用文件聊天失败");
  344. throw;
  345. }
  346. }
  347. /// <summary>
  348. /// 流式 chat
  349. /// </summary>
  350. /// <param name="question">问题</param>
  351. /// <param name="model">模型名称</param>
  352. /// <param name="temperature">温度参数</param>
  353. /// <param name="maxTokens">最大token数</param>
  354. /// <returns>聊天响应</returns>
  355. public async IAsyncEnumerable<string> ChatStreamAsync(string question, string model = "deepseek-chat", float temperature = 0.7f, int maxTokens = 4000)
  356. {
  357. var messageContent = new List<object>
  358. {
  359. new { type = "text", text = question }
  360. };
  361. var request = new DeepSeekChatWithFilesRequest
  362. {
  363. Model = model,
  364. Messages = new List<FileMessage>
  365. {
  366. new FileMessage
  367. {
  368. Role = "user",
  369. Content = messageContent
  370. }
  371. },
  372. Stream = true,
  373. Temperature = temperature,
  374. MaxTokens = maxTokens,
  375. TopP = 0.9M,
  376. FrequencyPenalty = 0.2M,
  377. PresencePenalty = 0.1M,
  378. };
  379. var jsonContent = JsonSerializer.Serialize(request, new JsonSerializerOptions
  380. {
  381. PropertyNamingPolicy = JsonNamingPolicy.CamelCase
  382. });
  383. _httpClient.Timeout = TimeSpan.FromMinutes(10);
  384. using var requestMsg = new HttpRequestMessage(HttpMethod.Post, "chat/completions")
  385. {
  386. Content = new StringContent(jsonContent, Encoding.UTF8, "application/json")
  387. };
  388. using var response = await _httpClient.SendAsync(requestMsg, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
  389. response.EnsureSuccessStatusCode();
  390. using var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  391. using var reader = new StreamReader(responseStream, Encoding.UTF8);
  392. string? line;
  393. while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
  394. {
  395. if (string.IsNullOrWhiteSpace(line))
  396. continue;
  397. if (!line.StartsWith("data: ", StringComparison.Ordinal))
  398. continue;
  399. var data = line["data: ".Length..];
  400. if (data == "[DONE]")
  401. yield break;
  402. string? deltaText = null;
  403. try
  404. {
  405. using var jsonDoc = JsonDocument.Parse(data);
  406. if (!jsonDoc.RootElement.TryGetProperty("choices", out var choices) || choices.GetArrayLength() == 0)
  407. continue;
  408. if (!choices[0].TryGetProperty("delta", out var delta))
  409. continue;
  410. if (delta.TryGetProperty("content", out var contentVal))
  411. {
  412. var text = contentVal.GetString();
  413. if (!string.IsNullOrEmpty(text))
  414. deltaText = text;
  415. }
  416. }
  417. catch (System.Text.Json.JsonException)
  418. {
  419. }
  420. if (deltaText != null)
  421. yield return deltaText;
  422. }
  423. }
  424. /// <summary>
  425. /// 等待文件处理完成
  426. /// </summary>
  427. public async Task<DeepSeekFileUploadResponse> WaitForFileProcessingAsync(string fileId, int timeoutSeconds = 60)
  428. {
  429. var startTime = DateTime.UtcNow;
  430. var timeout = TimeSpan.FromSeconds(timeoutSeconds);
  431. while (DateTime.UtcNow - startTime < timeout)
  432. {
  433. var fileInfo = await GetFileInfoAsync(fileId);
  434. if (fileInfo.Status == "processed")
  435. {
  436. _logger.LogInformation("文件处理完成: {FileId}", fileId);
  437. return fileInfo;
  438. }
  439. else if (fileInfo.Status == "error")
  440. {
  441. throw new Exception($"文件处理失败: {fileId}");
  442. }
  443. // 等待2秒后重试
  444. await Task.Delay(2000);
  445. }
  446. throw new TimeoutException($"文件处理超时: {fileId}");
  447. }
  448. /// <summary>
  449. /// 根据文件名获取Content-Type
  450. /// </summary>
  451. private static string GetContentType(string fileName)
  452. {
  453. var extension = Path.GetExtension(fileName).ToLower();
  454. return extension switch
  455. {
  456. ".txt" => "text/plain",
  457. ".pdf" => "application/pdf",
  458. ".json" => "application/json",
  459. ".csv" => "text/csv",
  460. ".html" => "text/html",
  461. ".htm" => "text/html",
  462. ".md" => "text/markdown",
  463. _ => "application/octet-stream"
  464. };
  465. }
  466. #region 项目相关
  467. /// <summary>
  468. /// 读取项目内的指定文件并转换为IFormFile
  469. /// </summary>
  470. public async Task<ProjectFileReadResponse> ReadProjectFilesAsync(List<string> relativePaths)
  471. {
  472. var response = new ProjectFileReadResponse();
  473. var projectRoot = GetProjectRootPath();
  474. if (projectRoot.Contains("OASystem.Api"))
  475. {
  476. projectRoot = projectRoot.Replace("OASystem.Api", "");
  477. }
  478. _logger.LogInformation("开始读取项目文件,数量: {Count}", relativePaths.Count);
  479. foreach (var relativePath in relativePaths)
  480. {
  481. var fileInfo = new ProjectFileInfo
  482. {
  483. RelativePath = relativePath
  484. };
  485. try
  486. {
  487. var fullPath = Path.Combine(projectRoot, relativePath);
  488. fileInfo.FullPath = fullPath;
  489. if (!System.IO.File.Exists(fullPath))
  490. {
  491. throw new FileNotFoundException($"文件不存在: {relativePath}");
  492. }
  493. var fileInfoObj = new FileInfo(fullPath);
  494. fileInfo.FileSize = fileInfoObj.Length;
  495. fileInfo.LastModified = fileInfoObj.LastWriteTime;
  496. // 转换为IFormFile
  497. fileInfo.FormFile = await ConvertToFormFileAsync(fullPath);
  498. fileInfo.Success = true;
  499. _logger.LogInformation("文件读取成功: {FileName}, 大小: {Size} bytes", relativePath, fileInfo.FileSize);
  500. }
  501. catch (Exception ex)
  502. {
  503. fileInfo.Success = false;
  504. fileInfo.ErrorMessage = ex.Message;
  505. _logger.LogError(ex, "文件读取失败: {FileName}", relativePath);
  506. }
  507. response.FileInfos.Add(fileInfo);
  508. }
  509. response.Success = response.SuccessCount > 0;
  510. response.Message = $"成功读取 {response.SuccessCount} 个文件,失败 {response.FailureCount} 个";
  511. return response;
  512. }
  513. /// <summary>
  514. /// 读取项目内指定目录的文件
  515. /// </summary>
  516. public async Task<ProjectFileReadResponse> ReadProjectDirectoryAsync(string directoryPath, string searchPattern = "*.cs", bool recursive = false)
  517. {
  518. var response = new ProjectFileReadResponse();
  519. var projectRoot = GetProjectRootPath();
  520. var fullDirectoryPath = Path.Combine(projectRoot, directoryPath);
  521. _logger.LogInformation("开始读取目录文件: {Directory}, 模式: {Pattern}", directoryPath, searchPattern);
  522. if (!Directory.Exists(fullDirectoryPath))
  523. {
  524. response.Success = false;
  525. response.Message = $"目录不存在: {directoryPath}";
  526. return response;
  527. }
  528. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  529. var files = Directory.GetFiles(fullDirectoryPath, searchPattern, searchOption);
  530. _logger.LogInformation("找到 {FileCount} 个文件", files.Length);
  531. foreach (var filePath in files)
  532. {
  533. var relativePath = Path.GetRelativePath(projectRoot, filePath);
  534. var fileInfo = new ProjectFileInfo
  535. {
  536. RelativePath = relativePath,
  537. FullPath = filePath
  538. };
  539. try
  540. {
  541. var fileInfoObj = new FileInfo(filePath);
  542. fileInfo.FileSize = fileInfoObj.Length;
  543. fileInfo.LastModified = fileInfoObj.LastWriteTime;
  544. // 转换为IFormFile
  545. fileInfo.FormFile = await ConvertToFormFileAsync(filePath);
  546. fileInfo.Success = true;
  547. _logger.LogDebug("文件读取成功: {FileName}", relativePath);
  548. }
  549. catch (Exception ex)
  550. {
  551. fileInfo.Success = false;
  552. fileInfo.ErrorMessage = ex.Message;
  553. _logger.LogError(ex, "文件读取失败: {FileName}", relativePath);
  554. }
  555. response.FileInfos.Add(fileInfo);
  556. }
  557. response.Success = response.SuccessCount > 0;
  558. response.Message = $"成功读取 {response.SuccessCount} 个文件,失败 {response.FailureCount} 个";
  559. return response;
  560. }
  561. /// <summary>
  562. /// 获取项目根目录路径
  563. /// </summary>
  564. public string GetProjectRootPath()
  565. {
  566. // 在开发环境中使用ContentRootPath,在生产环境中可能需要调整
  567. return _hostEnvironment.ContentRootPath;
  568. }
  569. /// <summary>
  570. /// 检查文件是否存在
  571. /// </summary>
  572. public bool FileExists(string relativePath)
  573. {
  574. var fullPath = Path.Combine(GetProjectRootPath(), relativePath);
  575. return System.IO.File.Exists(fullPath);
  576. }
  577. /// <summary>
  578. /// 将物理文件转换为IFormFile
  579. /// </summary>
  580. public async Task<IFormFile> ConvertToFormFileAsync(string filePath)
  581. {
  582. var fileInfo = new FileInfo(filePath);
  583. var fileName = Path.GetFileName(filePath);
  584. // 读取文件内容
  585. byte[] fileBytes;
  586. using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  587. {
  588. fileBytes = new byte[fileStream.Length];
  589. await fileStream.ReadAsync(fileBytes, 0, (int)fileStream.Length);
  590. }
  591. // 创建IFormFile
  592. return new FormFile(
  593. new MemoryStream(fileBytes),
  594. 0,
  595. fileBytes.Length,
  596. "file",
  597. fileName)
  598. {
  599. Headers = new HeaderDictionary(),
  600. ContentType = GetFileContentType(fileName)
  601. };
  602. }
  603. /// <summary>
  604. /// 根据文件名获取Content-Type
  605. /// </summary>
  606. private string GetFileContentType(string fileName)
  607. {
  608. var extension = Path.GetExtension(fileName).ToLower();
  609. return extension switch
  610. {
  611. ".cs" => "text/plain",
  612. ".txt" => "text/plain",
  613. ".json" => "application/json",
  614. ".xml" => "application/xml",
  615. ".html" => "text/html",
  616. ".htm" => "text/html",
  617. ".css" => "text/css",
  618. ".js" => "application/javascript",
  619. ".ts" => "application/typescript",
  620. ".py" => "text/x-python",
  621. ".java" => "text/x-java",
  622. ".cpp" => "text/x-c++",
  623. ".c" => "text/x-c",
  624. ".h" => "text/x-c",
  625. ".md" => "text/markdown",
  626. _ => "application/octet-stream"
  627. };
  628. }
  629. /// <summary>
  630. /// 读取特定的签证申请表单文件
  631. /// </summary>
  632. /// <param name="fileName"></param>
  633. /// <returns></returns>
  634. public async Task<ProjectFileReadResponse> ReadVisaFormFileAsync(string fileName)
  635. {
  636. var specificPath = $@"OASystem\OASystem.Domain\ViewModels\VisaFormDetails\{fileName}";
  637. return await ReadProjectFilesAsync(new List<string> { specificPath });
  638. }
  639. /// <summary>
  640. /// 读取OASystem项目中的所有CS文件
  641. /// </summary>
  642. public async Task<ProjectFileReadResponse> ReadOASystemFilesAsync(string searchPattern = "*.cs", bool recursive = true)
  643. {
  644. return await ReadProjectDirectoryAsync(@"OASystem", searchPattern, recursive);
  645. }
  646. /// <summary>
  647. /// 读取指定域模型中的CS文件
  648. /// </summary>
  649. public async Task<ProjectFileReadResponse> ReadDomainViewModelsAsync(string searchPattern = "*.cs", bool recursive = true)
  650. {
  651. return await ReadProjectDirectoryAsync(@"OASystem\OASystem.Domain\ViewModels", searchPattern, recursive);
  652. }
  653. /// <summary>
  654. /// 读取签证表单相关的所有CS文件
  655. /// </summary>
  656. public async Task<ProjectFileReadResponse> ReadVisaFormFilesAsync(string searchPattern = "*.cs", bool recursive = true)
  657. {
  658. return await ReadProjectDirectoryAsync(@"OASystem\OASystem.Domain\ViewModels\VisaFormDetails", searchPattern, recursive);
  659. }
  660. #endregion
  661. }
  662. #region 私有实体类
  663. /// <summary>
  664. /// DeepSeek 聊天响应(用于反序列化)
  665. /// </summary>
  666. internal class DeepSeekResponse
  667. {
  668. [JsonPropertyName("choices")]
  669. public List<Choice> Choices { get; set; }
  670. [JsonPropertyName("usage")]
  671. public Usage Usage { get; set; }
  672. }
  673. internal class Choice
  674. {
  675. [JsonPropertyName("message")]
  676. public Message Message { get; set; }
  677. }
  678. internal class Message
  679. {
  680. [JsonPropertyName("content")]
  681. public string Content { get; set; }
  682. }
  683. internal class Usage
  684. {
  685. [JsonPropertyName("total_tokens")]
  686. public int TotalTokens { get; set; }
  687. }
  688. #endregion
  689. }