DifyService.java 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. package cn.cslg.pas.service.common;
  2. import cn.cslg.pas.common.model.dify.*;
  3. import cn.cslg.pas.common.model.dify.GenerateClaimDTO;
  4. import cn.cslg.pas.common.model.dify.confessionSession.AddConfessionSessionDTO;
  5. import cn.cslg.pas.common.model.dify.confessionSession.UpdateConfessionSessionDTO;
  6. import cn.cslg.pas.common.utils.*;
  7. import cn.cslg.pas.common.utils.ClaimUtils.ClaimSplitUtils;
  8. import cn.cslg.pas.common.vo.PatentRightParams;
  9. import cn.cslg.pas.domain.business.ReportTemple;
  10. import cn.cslg.pas.domain.business.TechnicalCase;
  11. import cn.cslg.pas.domain.dify.AssoConfessionSessionFile;
  12. import cn.cslg.pas.domain.dify.ConfessionSession;
  13. import cn.cslg.pas.domain.report.AssoProjectConfession;
  14. import cn.cslg.pas.exception.ExceptionEnum;
  15. import cn.cslg.pas.exception.XiaoShiException;
  16. import cn.cslg.pas.mapper.dify.ConfessionSessionMapper;
  17. import cn.cslg.pas.service.business.ReportTempleService;
  18. import cn.cslg.pas.service.business.TechnicalCaseService;
  19. import cn.cslg.pas.service.dify.ConfessionSessionService;
  20. import cn.cslg.pas.service.dify.DifySessionService;
  21. import cn.cslg.pas.service.dify.GenerateInstructionService;
  22. import cn.cslg.pas.service.report.AssoProjectConfessionService;
  23. import com.alibaba.fastjson.JSON;
  24. import com.alibaba.fastjson.JSONArray;
  25. import com.alibaba.fastjson.JSONObject;
  26. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  27. import com.deepoove.poi.XWPFTemplate;
  28. import com.deepoove.poi.config.Configure;
  29. import com.deepoove.poi.config.ConfigureBuilder;
  30. import com.fasterxml.jackson.databind.JsonNode;
  31. import com.fasterxml.jackson.databind.ObjectMapper;
  32. import com.google.gson.Gson;
  33. import com.google.gson.GsonBuilder;
  34. import lombok.RequiredArgsConstructor;
  35. import lombok.extern.slf4j.Slf4j;
  36. import okhttp3.*;
  37. import okhttp3.Response;
  38. import org.apache.commons.lang3.ObjectUtils;
  39. import org.apache.commons.lang3.StringUtils;
  40. import org.ddr.poi.html.HtmlRenderPolicy;
  41. import org.springframework.beans.factory.annotation.Autowired;
  42. import org.springframework.beans.factory.annotation.Value;
  43. import org.springframework.context.annotation.Lazy;
  44. import org.springframework.http.HttpHeaders;
  45. import org.springframework.stereotype.Service;
  46. import org.springframework.transaction.annotation.Transactional;
  47. import org.springframework.util.CollectionUtils;
  48. import org.w3c.dom.DocumentType;
  49. import reactor.core.publisher.Flux;
  50. import javax.swing.text.Document;
  51. import java.io.*;
  52. import java.util.*;
  53. import java.util.concurrent.TimeUnit;
  54. /**
  55. * Okhttp调用FMS上传文件接口
  56. *
  57. * @Author lrj
  58. * @Date 2025/4/10
  59. */
  60. @RequiredArgsConstructor
  61. @Slf4j
  62. @Service
  63. public class DifyService {
  64. @Value("${DIFY.apiKey}")
  65. private String apiKey;
  66. @Value("${DIFY.OAApiKey}")
  67. private String OAApiKey;
  68. @Value("${DIFY.url}")
  69. private String url;
  70. @Value("${DIFY.checkApiKey}")
  71. private String checkApiKey;
  72. @Value("${FileDownloadUrl}")
  73. private String fileDownloadUrl;
  74. @Value("${DIFY.cliamKey}")
  75. private String cliamKey;
  76. private final DifySessionService difySessionService;
  77. private final TechnicalCaseService technicalCaseService;
  78. private final AssoProjectConfessionService assoProjectConfessionService;
  79. @Autowired
  80. private CacheUtils cacheUtils;
  81. @Autowired
  82. private LoginUtils loginUtils;
  83. private final ConfessionSessionService confessionSessionService;
  84. @Autowired
  85. private ConfessionSessionMapper confessionSessionMapper;
  86. @Autowired
  87. private ReportTempleService templeService;
  88. @Autowired
  89. private FileUtils fileUtils;
  90. @Autowired
  91. private FileManagerService fileManagerService;
  92. @Autowired
  93. @Lazy
  94. private GenerateInstructionService generateInstructionService;
  95. /**
  96. * 调用文件系统删除文件接口
  97. */
  98. public String chatMessage(DifyChatMessageDTO difyChatMessageDTO,String key) throws IOException {
  99. String param = new Gson().toJson(difyChatMessageDTO);
  100. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  101. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  102. .connectTimeout(600, TimeUnit.SECONDS)
  103. .writeTimeout(600, TimeUnit.SECONDS)
  104. .readTimeout(600, TimeUnit.SECONDS)
  105. .build();
  106. Request request = new Request.Builder()
  107. .url(url + "chat-messages")
  108. .post(requestBody)
  109. .addHeader("Authorization", "Bearer " + key)
  110. .build();
  111. return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  112. }
  113. /**
  114. * 调用文件系统删除文件接口
  115. */
  116. public String queryHistoryMessage(DifyHistoryMessageDTO difyChatMessageDTO) throws IOException {
  117. difyChatMessageDTO.setUser(loginUtils.getId().toString());
  118. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  119. .connectTimeout(600, TimeUnit.SECONDS)
  120. .writeTimeout(600, TimeUnit.SECONDS)
  121. .readTimeout(600, TimeUnit.SECONDS)
  122. .build();
  123. String path = "messages?conversation_id=" + difyChatMessageDTO.getConversationId() + "&user=" + difyChatMessageDTO.getUser() + "&limit=" + difyChatMessageDTO.getLimit();
  124. if (difyChatMessageDTO.getFirstId() != null) {
  125. path += "&first_id=" + difyChatMessageDTO.getFirstId();
  126. }
  127. Request request = new Request.Builder()
  128. .url(url + path)
  129. .get()
  130. .addHeader("Authorization", "Bearer " + apiKey)
  131. .build();
  132. return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  133. }
  134. public Flux<String> getOkhttp(ChatMessageDTO chatMessageDTO) {
  135. Integer projectId = chatMessageDTO.getProjectId();
  136. Integer confessionSessionId = chatMessageDTO.getConfessionSessionId();
  137. String conversationId = chatMessageDTO.getConversationId();
  138. String userId = loginUtils.getId().toString();
  139. String query = chatMessageDTO.getQuery();
  140. if (conversationId == null) {
  141. conversationId = difySessionService.getSessionId(projectId, userId);
  142. }
  143. String temConversationId = conversationId;
  144. OkHttpClient client = new OkHttpClient.Builder()
  145. .connectTimeout(600, TimeUnit.SECONDS)
  146. .writeTimeout(600, TimeUnit.SECONDS)
  147. .readTimeout(600, TimeUnit.SECONDS)
  148. .build();
  149. DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO();
  150. Map<String, Object> map = new HashMap<>();
  151. String fileContent = "";
  152. String inventionPoint = "";
  153. if (projectId != null) {
  154. fileContent = this.getConfression(projectId);
  155. inventionPoint = this.getInventPoint(projectId);
  156. } else if (confessionSessionId != null) {
  157. ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId);
  158. fileContent = fileDownloadUrl + confessionSession.getGuid();
  159. inventionPoint = confessionSession.getInventionPoint();
  160. }
  161. map.put("file_path", fileContent);
  162. map.put("invention_point", inventionPoint);
  163. difyChatMessageDTO.setInputs(map);
  164. difyChatMessageDTO.setConversationId(conversationId);
  165. difyChatMessageDTO.setResponseMode("streaming");
  166. difyChatMessageDTO.setUser(userId);
  167. difyChatMessageDTO.setQuery(query);
  168. difyChatMessageDTO.setFiles(new ArrayList<>());
  169. String param = new Gson().toJson(difyChatMessageDTO);
  170. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  171. Request request = this.getChatMessageRequest(requestBody);
  172. return Flux.create(emitter -> {
  173. client.newCall(request).enqueue(new Callback() {
  174. @Override
  175. public void onFailure(Call call, IOException e) {
  176. emitter.error(e);
  177. }
  178. @Override
  179. public void onResponse(Call call, Response response) throws IOException {
  180. if (!response.isSuccessful()) {
  181. emitter.error(new IOException("Unexpected code: " + response));
  182. return;
  183. }
  184. try (Reader reader = response.body().charStream()) {
  185. BufferedReader bufferedReader = new BufferedReader(reader);
  186. String line;
  187. String temConversationId2 = temConversationId;
  188. String prefixToRemove = "data: ";
  189. while ((line = bufferedReader.readLine()) != null) {
  190. if (line.isEmpty()) {
  191. continue;
  192. }
  193. if (line.startsWith(prefixToRemove)) {
  194. line = line.substring(prefixToRemove.length());
  195. }
  196. if (temConversationId2 == null || temConversationId2.isEmpty()) {
  197. try {
  198. JSONObject jsonObject = JSON.parseObject(line);
  199. temConversationId2 = jsonObject.get("conversation_id").toString();
  200. if (projectId != null) {
  201. difySessionService.addDifySession(projectId, userId, temConversationId2);
  202. }
  203. if (confessionSessionId != null) {
  204. UpdateConfessionSessionDTO updateConfessionSessionDTO = new UpdateConfessionSessionDTO();
  205. updateConfessionSessionDTO.setConfessionSessionId(confessionSessionId);
  206. updateConfessionSessionDTO.setConversationId(temConversationId2);
  207. confessionSessionService.updateConfessionSession(updateConfessionSessionDTO);
  208. }
  209. } catch (Exception e) {
  210. }
  211. }
  212. emitter.next(line); // 将每行数据发送到 Flux
  213. }
  214. } catch (IOException e) {
  215. emitter.error(e);
  216. } finally {
  217. emitter.complete();
  218. }
  219. }
  220. });
  221. });
  222. }
  223. public String getInventPoint(Integer projectId) {
  224. String re = "";
  225. TechnicalCase technicalCase = technicalCaseService.getByProjectId(projectId);
  226. if (technicalCase != null) {
  227. if (technicalCase.getInventionPoint() != null) {
  228. re = technicalCase.getInventionPoint();
  229. }
  230. }
  231. return re;
  232. }
  233. public String getConfression(Integer projectId) {
  234. String url = "";
  235. AssoProjectConfession assoProjectConfession = assoProjectConfessionService.queryAssoProjectConfession(projectId);
  236. if (assoProjectConfession != null) {
  237. url = fileDownloadUrl + assoProjectConfession.getFileGuid();
  238. }
  239. return url;
  240. }
  241. public Request getChatMessageRequest(RequestBody requestBody) {
  242. Request request = new Request.Builder()
  243. .url(url + "chat-messages")
  244. .addHeader("Authorization", "Bearer " + apiKey).addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  245. .post(requestBody)
  246. .build();
  247. return request;
  248. }
  249. public JSONObject stopMessage(String taskId) throws IOException {
  250. OkHttpClient client = new OkHttpClient.Builder()
  251. .connectTimeout(60, TimeUnit.SECONDS)
  252. .writeTimeout(60, TimeUnit.SECONDS)
  253. .readTimeout(60, TimeUnit.SECONDS)
  254. .build();
  255. DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO();
  256. difyChatMessageDTO.setUser("1");
  257. String param = new Gson().toJson(difyChatMessageDTO);
  258. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  259. Request request = new Request.Builder()
  260. .url(url + "chat-messages/" + taskId + "/stop")
  261. .addHeader("Authorization", "Bearer " + apiKey).addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  262. .post(requestBody)
  263. .build();
  264. String json = Objects.requireNonNull(client.newCall(request).execute().body()).string();
  265. JSONObject jsonObject = JSONObject.parseObject(json);
  266. return jsonObject;
  267. }
  268. @Transactional(rollbackFor = Exception.class)
  269. public Map<String, Object> generateInventionPoint(ChatMessageDTO chatMessageDTO) throws IOException {
  270. Integer projectId = chatMessageDTO.getProjectId();
  271. Integer confessionSessionId = chatMessageDTO.getConfessionSessionId();
  272. String query = "生成发明点";
  273. String userId = loginUtils.getId().toString();
  274. String conversationId = chatMessageDTO.getConversationId();
  275. DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO();
  276. Map<String, Object> map = new HashMap<>();
  277. String fileContent = "";
  278. if (confessionSessionId != null) {
  279. ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId);
  280. fileContent = fileDownloadUrl + confessionSession.getGuid();
  281. } else if (projectId != null) {
  282. fileContent = this.getConfression(projectId);
  283. }
  284. map.put("file_path", fileContent);
  285. difyChatMessageDTO.setInputs(map);
  286. difyChatMessageDTO.setConversationId(conversationId);
  287. difyChatMessageDTO.setResponseMode("blocking");
  288. difyChatMessageDTO.setUser(userId);
  289. difyChatMessageDTO.setQuery(query);
  290. difyChatMessageDTO.setFiles(new ArrayList<>());
  291. OkHttpClient client = new OkHttpClient.Builder()
  292. .connectTimeout(600, TimeUnit.SECONDS)
  293. .writeTimeout(600, TimeUnit.SECONDS)
  294. .readTimeout(600, TimeUnit.SECONDS)
  295. .build();
  296. String param = new Gson().toJson(difyChatMessageDTO);
  297. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  298. Request request = this.getChatMessageRequest(requestBody);
  299. String res = Objects.requireNonNull(client.newCall(request).execute().body()).string();
  300. JSONObject jsonObject = JSONObject.parseObject(res);
  301. String inventionPoint = jsonObject.get("answer").toString();
  302. inventionPoint = DataUtils.getMarkDownText(inventionPoint);
  303. Map<String, Object> map1 = new HashMap<>();
  304. map1.put("invention_point", inventionPoint);
  305. if (projectId != null) {
  306. technicalCaseService.updateInventionPoint(projectId, inventionPoint);
  307. }
  308. if (confessionSessionId != null) {
  309. UpdateConfessionSessionDTO updateConfessionSessionDTO = new UpdateConfessionSessionDTO();
  310. updateConfessionSessionDTO.setConfessionSessionId(confessionSessionId);
  311. updateConfessionSessionDTO.setInventionPoint(inventionPoint);
  312. confessionSessionService.updateConfessionSession(updateConfessionSessionDTO);
  313. }
  314. map1.put("conversation_id", conversationId);
  315. map1.put("projectId", projectId);
  316. map1.put("confessionSessionId", confessionSessionId);
  317. return map1;
  318. }
  319. public List<Object> generateClaimExplain(GenerateClaimDTO generateClaimDTO) throws Exception {
  320. String claim = generateClaimDTO.getClaim();
  321. PatentRightParams params = new PatentRightParams();
  322. params.setCountry("CN");
  323. params.setContent(claim);
  324. params.setPatentNo("CN");
  325. ClaimSplitUtils.formatPatentRight(params);
  326. DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO();
  327. String userId = loginUtils.getId().toString();
  328. Map<String, Object> map = new HashMap<>();
  329. map.put("claim", claim);
  330. difyChatMessageDTO.setInputs(map);
  331. difyChatMessageDTO.setResponseMode("blocking");
  332. difyChatMessageDTO.setUser(userId);
  333. String param = new Gson().toJson(difyChatMessageDTO);
  334. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  335. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  336. .connectTimeout(6000, TimeUnit.SECONDS)
  337. .writeTimeout(6000, TimeUnit.SECONDS)
  338. .readTimeout(6000, TimeUnit.SECONDS)
  339. .build();
  340. Request request = new Request.Builder()
  341. .url(url + "workflows/run")
  342. .post(requestBody)
  343. .addHeader("Authorization", "Bearer " + cliamKey)
  344. .build();
  345. String res = Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  346. JSONObject jsonObject = JSONObject.parseObject(res);
  347. String dataStr = jsonObject.get("data").toString();
  348. JSONObject dataObject = JSONObject.parseObject(dataStr);
  349. String outPuts = dataObject.get("outputs").toString();
  350. JSONObject jsonObject1 = JSONObject.parseObject(outPuts);
  351. Object retsObj = jsonObject1.get("json");
  352. String rets = retsObj.toString();
  353. List<Object> reObject = JSONArray.parseArray(rets, Object.class);
  354. Map<String, Object> addMap = new HashMap<>();
  355. Map<String, Object> queryMap = new HashMap<>();
  356. queryMap.put("claim", claim);
  357. addMap.put("query", queryMap);
  358. addMap.put("answer", retsObj);
  359. String addStr = JSONObject.toJSONString(addMap);
  360. AddConfessionSessionDTO addConfessionSessionDTO = new AddConfessionSessionDTO();
  361. addConfessionSessionDTO.setConversationId(jsonObject.get("workflow_run_id").toString());
  362. addConfessionSessionDTO.setContent(addStr);
  363. String name = DateUtils.dateTimeToStr(new Date());
  364. name = name + "-权利要求解释及有益效果";
  365. addConfessionSessionDTO.setConversationName(name);
  366. addConfessionSessionDTO.setType(1);
  367. confessionSessionService.addSession(addConfessionSessionDTO);
  368. System.out.println(res);
  369. return reObject;
  370. }
  371. public Flux<String> successGetOAHttp(Integer confessionSessionId) {
  372. ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId);
  373. String fileUrl = fileDownloadUrl + confessionSession.getGuid();
  374. String userId = loginUtils.getId().toString();
  375. OkHttpClient client = new OkHttpClient.Builder()
  376. .connectTimeout(600, TimeUnit.SECONDS)
  377. .writeTimeout(600, TimeUnit.SECONDS)
  378. .readTimeout(600, TimeUnit.SECONDS)
  379. .build();
  380. Map<String, Object> map = new HashMap<>();
  381. map.put("fileUrl", fileUrl);
  382. OAMessageDTO oaMessageDTO = new OAMessageDTO();
  383. oaMessageDTO.setInputs(map);
  384. oaMessageDTO.setResponseMode("streaming");
  385. oaMessageDTO.setUser(userId);
  386. oaMessageDTO.setFiles(new ArrayList<>());
  387. String param = new Gson().toJson(oaMessageDTO);
  388. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  389. Request request = new Request.Builder()
  390. .url(url + "workflows/run")
  391. .addHeader("Authorization", "Bearer " + OAApiKey)
  392. .addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  393. .post(requestBody)
  394. .build();
  395. return Flux.create(emitter -> {
  396. client.newCall(request).enqueue(new Callback() {
  397. @Override
  398. public void onFailure(Call call, IOException e) {
  399. emitter.error(e);
  400. }
  401. @Override
  402. public void onResponse(Call call, Response response) throws IOException {
  403. if (!response.isSuccessful()) {
  404. emitter.error(new IOException("Unexpected code: " + response));
  405. return;
  406. }
  407. try (Reader reader = response.body().charStream()) {
  408. BufferedReader bufferedReader = new BufferedReader(reader);
  409. String line;
  410. String prefixToRemove = "data: ";
  411. String runId = "";
  412. while ((line = bufferedReader.readLine()) != null) {
  413. if (line.isEmpty()) {
  414. continue;
  415. }
  416. if (line.startsWith(prefixToRemove)) {
  417. line = line.substring(prefixToRemove.length());
  418. }
  419. try {
  420. JSONObject jsonObject = JSON.parseObject(line);
  421. String workflowRunId = jsonObject.get("workflow_run_id").toString();
  422. String event = jsonObject.get("event").toString();
  423. if (StringUtils.isNotEmpty(workflowRunId)) {
  424. if (StringUtils.isEmpty(runId)) {
  425. runId = workflowRunId;
  426. confessionSessionMapper.updateSingleField(confessionSessionId, "conversation_id", workflowRunId);
  427. }
  428. }
  429. if (event.equals("workflow_finished")) {
  430. String data = jsonObject.get("data").toString();
  431. String content = "";
  432. if (StringUtils.isNotEmpty(data)) {
  433. JSONObject dataObject = JSON.parseObject(data);
  434. String outputs = dataObject.get("outputs").toString();
  435. if (StringUtils.isNotEmpty(outputs)) {
  436. JSONObject outputsObject = JSON.parseObject(outputs);
  437. String output = outputsObject.get("output").toString();
  438. content = DataUtils.unicodeDecode(output);
  439. }
  440. }
  441. if (StringUtils.isNotEmpty(content)) {
  442. JSONObject obj = new JSONObject();
  443. obj.put("answer", content);
  444. confessionSessionMapper.updateSingleField(confessionSessionId, "content", obj.toString());
  445. }
  446. }
  447. } catch (Exception e) {
  448. }
  449. emitter.next(line); // 将每行数据发送到 Flux
  450. }
  451. } catch (IOException e) {
  452. emitter.error(e);
  453. } finally {
  454. emitter.complete();
  455. }
  456. }
  457. });
  458. });
  459. }
  460. public Flux<String> successGetOAHttp1(OAParamDTO vo) {
  461. Integer confessionSessionId = vo.getConfessionSessionId();
  462. String patentFileUrls = vo.getPatentFileUrls();
  463. ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId);
  464. if (ObjectUtils.isEmpty(confessionSession)) {
  465. throw new XiaoShiException(ExceptionEnum.BUSINESS_ERROR, "未查询到OA答辩记录");
  466. }
  467. String conversationId = confessionSession.getConversationId();
  468. String sessionContent = confessionSession.getContent();
  469. String conversationName = confessionSession.getConversationName();
  470. String fileUrl = fileDownloadUrl + confessionSession.getGuid();
  471. String userId = loginUtils.getId().toString();
  472. OkHttpClient client = new OkHttpClient.Builder()
  473. .connectTimeout(600, TimeUnit.SECONDS)
  474. .writeTimeout(600, TimeUnit.SECONDS)
  475. .readTimeout(600, TimeUnit.SECONDS)
  476. .build();
  477. Map<String, Object> map = new HashMap<>();
  478. map.put("fileUrl", fileUrl);
  479. map.put("patent_fileUrls",patentFileUrls);
  480. OAMessageDTO oaMessageDTO = new OAMessageDTO();
  481. oaMessageDTO.setInputs(map);
  482. oaMessageDTO.setResponseMode("streaming");
  483. oaMessageDTO.setUser(userId);
  484. oaMessageDTO.setQuery("OA答辩");
  485. oaMessageDTO.setConversationId(conversationId);
  486. oaMessageDTO.setFiles(new ArrayList<>());
  487. String param = new Gson().toJson(oaMessageDTO);
  488. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  489. Request request = new Request.Builder()
  490. .url(url + "chat-messages")
  491. .addHeader("Authorization", "Bearer " + OAApiKey)
  492. .addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  493. .post(requestBody)
  494. .build();
  495. return Flux.create(emitter -> {
  496. client.newCall(request).enqueue(new Callback() {
  497. @Override
  498. public void onFailure(Call call, IOException e) {
  499. emitter.error(e);
  500. }
  501. @Override
  502. public void onResponse(Call call, Response response) throws IOException {
  503. if (!response.isSuccessful()) {
  504. emitter.error(new IOException("Unexpected code: " + response));
  505. return;
  506. }
  507. try (Reader reader = response.body().charStream()) {
  508. BufferedReader bufferedReader = new BufferedReader(reader);
  509. String line;
  510. String prefixToRemove = "data: ";
  511. String runId = conversationId;
  512. while ((line = bufferedReader.readLine()) != null) {
  513. if (line.isEmpty()) {
  514. continue;
  515. }
  516. if (line.startsWith(prefixToRemove)) {
  517. line = line.substring(prefixToRemove.length());
  518. }
  519. try {
  520. JSONObject jsonObject = JSON.parseObject(line);
  521. String sessionConversationId = jsonObject.get("conversation_id").toString();
  522. String event = jsonObject.get("event").toString();
  523. if (StringUtils.isEmpty(runId)) {
  524. if (StringUtils.isNotEmpty(sessionConversationId)) {
  525. runId = sessionConversationId;
  526. confessionSessionMapper.updateSingleField(confessionSessionId, "conversation_id", sessionConversationId);
  527. }
  528. }
  529. if (event.equals("message")) {
  530. String data = jsonObject.get("answer").toString();
  531. JSONObject dataObject = null;
  532. if (StringUtils.isNotEmpty(data)) {
  533. try {
  534. dataObject = JSON.parseObject(data);
  535. String code = dataObject.get("code").toString();
  536. if (StringUtils.equals(code, "200")) {
  537. JSONObject object = dataObject.getJSONObject("data");
  538. generateDoc(conversationName, confessionSessionId, object);
  539. }
  540. } catch (Exception e) {
  541. }
  542. }
  543. if (ObjectUtils.isNotEmpty(dataObject)) {
  544. JSONObject obj;
  545. if (StringUtils.isNotEmpty(sessionContent)) {
  546. obj = JSON.parseObject(sessionContent);
  547. obj.put("data", dataObject);
  548. } else {
  549. obj = new JSONObject();
  550. obj.put("data", dataObject);
  551. }
  552. confessionSessionMapper.updateSingleField(confessionSessionId, "content", obj.toString());
  553. }
  554. }
  555. } catch (Exception e) {
  556. }
  557. emitter.next(line); // 将每行数据发送到 Flux
  558. }
  559. } catch (IOException e) {
  560. emitter.error(e);
  561. } finally {
  562. emitter.complete();
  563. }
  564. }
  565. });
  566. });
  567. }
  568. public void generateDoc(String conversationName,Integer confessionSessionId,JSONObject object) {
  569. Map<String, Object> map = new HashMap<>();
  570. String reason = object.getString("reason");
  571. String num = object.getString("num");
  572. String claimChange = object.getString("claim_change");
  573. List<String> claimList = new ArrayList<>();
  574. if (StringUtils.isNotEmpty(claimChange)) {
  575. claimList = Arrays.asList(claimChange.split("\n"));
  576. }
  577. JSONArray jsonArray = object.getJSONArray("defense_opinion");
  578. // 创建List集合
  579. List<String> list = new ArrayList<>();
  580. // 遍历JSONArray并添加元素到List
  581. if (!CollectionUtils.isEmpty(jsonArray)) {
  582. for (Object o : jsonArray) {
  583. String str = o.toString();
  584. if (StringUtils.isNotEmpty(str)) {
  585. String[] split1 = str.split("\n");
  586. list.addAll(Arrays.asList(split1));
  587. }
  588. }
  589. }
  590. map.put("num", num);
  591. map.put("reason", reason);
  592. map.put("claim_change", claimList);
  593. map.put("defense_opinion", list);
  594. ReportTemple reportTemplate = templeService.getById(20);
  595. String templateFilePath = fileUtils.getPath(reportTemplate.getTemplatePath());
  596. //更新会话
  597. String name = DateUtils.dateTimeToStr(new Date(), "yyyyMMdd");
  598. String finalName = name + "-" + conversationName + "-陈述意见书";
  599. //生成文档
  600. String fileGuid = null;
  601. try {
  602. fileGuid = this.generateOADefenseFile(map, templateFilePath, finalName);
  603. AssoConfessionSessionFile assoConfessionSessionFile = new AssoConfessionSessionFile();
  604. assoConfessionSessionFile.setGuid(fileGuid);
  605. assoConfessionSessionFile.setConfessionSessionId(confessionSessionId);
  606. assoConfessionSessionFile.insert();
  607. } catch (Exception e) {
  608. throw new XiaoShiException(ExceptionEnum.BUSINESS_ERROR, "加载陈述意见书失败");
  609. }
  610. }
  611. /**
  612. * 生成OA答辩文件
  613. *
  614. * @param map
  615. * @param templateFilePath
  616. * @param name
  617. * @return
  618. * @throws Exception
  619. */
  620. public String generateOADefenseFile(Map<String, Object> map, String templateFilePath, String name) throws Exception {
  621. XWPFTemplate xwpfTemplate = this.getHtmlTemplate(map, templateFilePath);
  622. String fileName = name + ".docx";
  623. String directoryName = fileUtils.createDirectory();
  624. String outPath = fileUtils.getSavePath(directoryName) + fileName;
  625. File file = new File(outPath);
  626. // 生成word保存在指定目录
  627. xwpfTemplate.writeToFile(outPath);
  628. xwpfTemplate.close();
  629. List<String> ids = fileManagerService.uploadFileGetGuid2(Collections.singletonList(file));
  630. if (CollectionUtils.isEmpty(ids)) {
  631. throw new XiaoShiException("保存记录失败");
  632. }
  633. return ids.get(0);
  634. }
  635. private XWPFTemplate getHtmlTemplate(Map<String, Object> map, String filePath) {
  636. XWPFTemplate template = null;
  637. try {
  638. HtmlRenderPolicy htmlRenderPolicy = new HtmlRenderPolicy();
  639. ConfigureBuilder configureBuilder = Configure.builder();
  640. configureBuilder.bind("#this", htmlRenderPolicy);
  641. Configure configure = configureBuilder.build();
  642. template = XWPFTemplate.compile(filePath, configure).render(map);
  643. } catch (Exception e) {
  644. e.printStackTrace();
  645. throw new XiaoShiException(ExceptionEnum.BUSINESS_ERROR, "未匹配到模版文件");
  646. }
  647. return template;
  648. }
  649. /**
  650. * 调用质检
  651. */
  652. public String WordErrorWorkFlow(DifyChatMessageDTO difyChatMessageDTO) throws IOException {
  653. String param = new Gson().toJson(difyChatMessageDTO);
  654. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  655. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  656. .connectTimeout(600, TimeUnit.SECONDS)
  657. .writeTimeout(600, TimeUnit.SECONDS)
  658. .readTimeout(600, TimeUnit.SECONDS)
  659. .build();
  660. Request request = new Request.Builder()
  661. .url(url + "workflows/run")
  662. .post(requestBody)
  663. .addHeader("Authorization", "Bearer " + checkApiKey)
  664. .build();
  665. return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  666. }
  667. /**
  668. * 获取具体实施方式
  669. */
  670. public String getImplementation(Map<String, Object> map) throws IOException {
  671. String param = new Gson().toJson(map);
  672. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  673. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  674. .connectTimeout(60, TimeUnit.SECONDS)
  675. .writeTimeout(60, TimeUnit.SECONDS)
  676. .readTimeout(60, TimeUnit.SECONDS)
  677. .build();
  678. Request request = new Request.Builder()
  679. .url(url + "chat-messages")
  680. .post(requestBody)
  681. .addHeader("Authorization", "Bearer " + checkApiKey)
  682. .build();
  683. return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  684. }
  685. public String generateClaimExplainRequest(GenerateClaimDTO generateClaimDTO) throws Exception {
  686. String claim = generateClaimDTO.getClaim();
  687. String background = generateClaimDTO.getBackground();
  688. DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO();
  689. String userId ="1";
  690. // String userId = loginUtils.getId().toString();
  691. Map<String, Object> map = new HashMap<>();
  692. map.put("claim", claim);
  693. map.put("background", background);
  694. difyChatMessageDTO.setInputs(map);
  695. difyChatMessageDTO.setResponseMode("blocking");
  696. difyChatMessageDTO.setUser(userId);
  697. String param = new Gson().toJson(difyChatMessageDTO);
  698. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  699. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  700. .connectTimeout(6000, TimeUnit.SECONDS)
  701. .writeTimeout(6000, TimeUnit.SECONDS)
  702. .readTimeout(6000, TimeUnit.SECONDS)
  703. .build();
  704. Request request = new Request.Builder()
  705. .url(url + "workflows/run")
  706. .post(requestBody)
  707. .addHeader("Authorization", "Bearer " + cliamKey)
  708. .build();
  709. String res = Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  710. return res;
  711. }
  712. }