DifyService.java 41 KB

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