DifyService.java 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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. System.out.println(res);
  316. JSONObject jsonObject = JSONObject.parseObject(res);
  317. String inventionPoint = jsonObject.get("answer").toString();
  318. inventionPoint = DataUtils.getMarkDownText(inventionPoint);
  319. Map<String, Object> map1 = new HashMap<>();
  320. map1.put("invention_point", inventionPoint);
  321. if (projectId != null) {
  322. technicalCaseService.updateInventionPoint(projectId, inventionPoint);
  323. }
  324. if (confessionSessionId != null) {
  325. UpdateConfessionSessionDTO updateConfessionSessionDTO = new UpdateConfessionSessionDTO();
  326. updateConfessionSessionDTO.setConfessionSessionId(confessionSessionId);
  327. updateConfessionSessionDTO.setInventionPoint(inventionPoint);
  328. confessionSessionService.updateConfessionSession(updateConfessionSessionDTO);
  329. }
  330. map1.put("conversation_id", conversationId);
  331. map1.put("projectId", projectId);
  332. map1.put("confessionSessionId", confessionSessionId);
  333. return map1;
  334. }
  335. public List<Object> generateClaimExplain(GenerateClaimDTO generateClaimDTO) throws Exception {
  336. String claim = generateClaimDTO.getClaim();
  337. PatentRightParams params = new PatentRightParams();
  338. params.setCountry("CN");
  339. params.setContent(claim);
  340. params.setPatentNo("CN");
  341. ClaimSplitUtils.formatPatentRight(params);
  342. DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO();
  343. String userId = loginUtils.getId().toString();
  344. Map<String, Object> map = new HashMap<>();
  345. map.put("claim", claim);
  346. difyChatMessageDTO.setInputs(map);
  347. difyChatMessageDTO.setResponseMode("blocking");
  348. difyChatMessageDTO.setUser(userId);
  349. String param = new Gson().toJson(difyChatMessageDTO);
  350. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  351. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  352. .connectTimeout(6000, TimeUnit.SECONDS)
  353. .writeTimeout(6000, TimeUnit.SECONDS)
  354. .readTimeout(6000, TimeUnit.SECONDS)
  355. .build();
  356. Request request = new Request.Builder()
  357. .url(url + "workflows/run")
  358. .post(requestBody)
  359. .addHeader("Authorization", "Bearer " + cliamKey)
  360. .build();
  361. String res = Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  362. JSONObject jsonObject = JSONObject.parseObject(res);
  363. String dataStr = jsonObject.get("data").toString();
  364. JSONObject dataObject = JSONObject.parseObject(dataStr);
  365. String outPuts = dataObject.get("outputs").toString();
  366. JSONObject jsonObject1 = JSONObject.parseObject(outPuts);
  367. Object retsObj = jsonObject1.get("json");
  368. String rets = retsObj.toString();
  369. List<Object> reObject = JSONArray.parseArray(rets, Object.class);
  370. Map<String, Object> addMap = new HashMap<>();
  371. Map<String, Object> queryMap = new HashMap<>();
  372. queryMap.put("claim", claim);
  373. addMap.put("query", queryMap);
  374. addMap.put("answer", retsObj);
  375. String addStr = JSONObject.toJSONString(addMap);
  376. AddConfessionSessionDTO addConfessionSessionDTO = new AddConfessionSessionDTO();
  377. addConfessionSessionDTO.setConversationId(jsonObject.get("workflow_run_id").toString());
  378. addConfessionSessionDTO.setContent(addStr);
  379. String name = DateUtils.dateTimeToStr(new Date());
  380. name = name + "-权利要求解释及有益效果";
  381. addConfessionSessionDTO.setConversationName(name);
  382. addConfessionSessionDTO.setType(1);
  383. confessionSessionService.addSession(addConfessionSessionDTO);
  384. System.out.println(res);
  385. return reObject;
  386. }
  387. public Flux<String> successGetOAHttp(Integer confessionSessionId) {
  388. ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId);
  389. String fileUrl = fileDownloadUrl + confessionSession.getGuid();
  390. String userId = loginUtils.getId().toString();
  391. OkHttpClient client = new OkHttpClient.Builder()
  392. .connectTimeout(600, TimeUnit.SECONDS)
  393. .writeTimeout(600, TimeUnit.SECONDS)
  394. .readTimeout(600, TimeUnit.SECONDS)
  395. .build();
  396. Map<String, Object> map = new HashMap<>();
  397. map.put("fileUrl", fileUrl);
  398. OAMessageDTO oaMessageDTO = new OAMessageDTO();
  399. oaMessageDTO.setInputs(map);
  400. oaMessageDTO.setResponseMode("streaming");
  401. oaMessageDTO.setUser(userId);
  402. oaMessageDTO.setFiles(new ArrayList<>());
  403. String param = new Gson().toJson(oaMessageDTO);
  404. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  405. Request request = new Request.Builder()
  406. .url(url + "workflows/run")
  407. .addHeader("Authorization", "Bearer " + OAApiKey)
  408. .addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  409. .post(requestBody)
  410. .build();
  411. return Flux.create(emitter -> {
  412. client.newCall(request).enqueue(new Callback() {
  413. @Override
  414. public void onFailure(Call call, IOException e) {
  415. emitter.error(e);
  416. }
  417. @Override
  418. public void onResponse(Call call, Response response) throws IOException {
  419. if (!response.isSuccessful()) {
  420. emitter.error(new IOException("Unexpected code: " + response));
  421. return;
  422. }
  423. try (Reader reader = response.body().charStream()) {
  424. BufferedReader bufferedReader = new BufferedReader(reader);
  425. String line;
  426. String prefixToRemove = "data: ";
  427. String runId = "";
  428. while ((line = bufferedReader.readLine()) != null) {
  429. if (line.isEmpty()) {
  430. continue;
  431. }
  432. if (line.startsWith(prefixToRemove)) {
  433. line = line.substring(prefixToRemove.length());
  434. }
  435. try {
  436. JSONObject jsonObject = JSON.parseObject(line);
  437. String workflowRunId = jsonObject.get("workflow_run_id").toString();
  438. String event = jsonObject.get("event").toString();
  439. if (StringUtils.isNotEmpty(workflowRunId)) {
  440. if (StringUtils.isEmpty(runId)) {
  441. runId = workflowRunId;
  442. confessionSessionMapper.updateSingleField(confessionSessionId, "conversation_id", workflowRunId);
  443. }
  444. }
  445. if (event.equals("workflow_finished")) {
  446. String data = jsonObject.get("data").toString();
  447. String content = "";
  448. if (StringUtils.isNotEmpty(data)) {
  449. JSONObject dataObject = JSON.parseObject(data);
  450. String outputs = dataObject.get("outputs").toString();
  451. if (StringUtils.isNotEmpty(outputs)) {
  452. JSONObject outputsObject = JSON.parseObject(outputs);
  453. String output = outputsObject.get("output").toString();
  454. content = DataUtils.unicodeDecode(output);
  455. }
  456. }
  457. if (StringUtils.isNotEmpty(content)) {
  458. JSONObject obj = new JSONObject();
  459. obj.put("answer", content);
  460. confessionSessionMapper.updateSingleField(confessionSessionId, "content", obj.toString());
  461. }
  462. }
  463. } catch (Exception e) {
  464. }
  465. emitter.next(line); // 将每行数据发送到 Flux
  466. }
  467. } catch (IOException e) {
  468. emitter.error(e);
  469. } finally {
  470. emitter.complete();
  471. }
  472. }
  473. });
  474. });
  475. }
  476. public Flux<String> successGetOAHttp1(OAParamDTO vo) {
  477. Integer confessionSessionId = vo.getConfessionSessionId();
  478. String patentFileUrls = vo.getPatentFileUrls();
  479. String appFileGuid = vo.getAppFileGuid();
  480. String modifyFileGuid = vo.getModifyFileGuid();
  481. ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId);
  482. if (ObjectUtils.isEmpty(confessionSession)) {
  483. throw new XiaoShiException(ExceptionEnum.BUSINESS_ERROR, "未查询到OA答辩记录");
  484. }
  485. String conversationId = confessionSession.getConversationId();
  486. String sessionContent = confessionSession.getContent();
  487. String conversationName = confessionSession.getConversationName();
  488. String fileUrl = fileDownloadUrl + confessionSession.getGuid();
  489. String userId = loginUtils.getId().toString();
  490. OkHttpClient client = new OkHttpClient.Builder()
  491. .connectTimeout(600, TimeUnit.SECONDS)
  492. .writeTimeout(600, TimeUnit.SECONDS)
  493. .readTimeout(600, TimeUnit.SECONDS)
  494. .build();
  495. Map<String, Object> map = new HashMap<>();
  496. map.put("fileUrl", fileUrl);
  497. map.put("patent_fileUrls", patentFileUrls);
  498. map.put("app_file_guid", appFileGuid);
  499. map.put("modify_file_guid", modifyFileGuid);
  500. map.put("patent_files", new ArrayList<>());
  501. map.put("changeClaim", vo.getChangeClaim());
  502. map.put("claim", vo.getClaim());
  503. map.put("main_claim_reason", vo.getMainClaimReason());
  504. map.put("near_index", vo.getNearIndex());
  505. OAMessageDTO oaMessageDTO = new OAMessageDTO();
  506. oaMessageDTO.setInputs(map);
  507. oaMessageDTO.setResponseMode("streaming");
  508. oaMessageDTO.setUser(userId);
  509. oaMessageDTO.setQuery("OA答辩");
  510. oaMessageDTO.setConversationId(conversationId);
  511. oaMessageDTO.setFiles(new ArrayList<>());
  512. String param = new Gson().toJson(oaMessageDTO);
  513. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  514. Request request = new Request.Builder()
  515. .url(url + "chat-messages")
  516. .addHeader("Authorization", "Bearer " + OAApiKey)
  517. .addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  518. .post(requestBody)
  519. .build();
  520. return Flux.create(emitter -> {
  521. client.newCall(request).enqueue(new Callback() {
  522. @Override
  523. public void onFailure(Call call, IOException e) {
  524. emitter.error(e);
  525. }
  526. @Override
  527. public void onResponse(Call call, Response response) throws IOException {
  528. if (!response.isSuccessful()) {
  529. emitter.error(new IOException("Unexpected code: " + response));
  530. return;
  531. }
  532. try (Reader reader = response.body().charStream()) {
  533. BufferedReader bufferedReader = new BufferedReader(reader);
  534. String line;
  535. String prefixToRemove = "data: ";
  536. String runId = conversationId;
  537. while ((line = bufferedReader.readLine()) != null) {
  538. if (line.isEmpty()) {
  539. continue;
  540. }
  541. if (line.startsWith(prefixToRemove)) {
  542. line = line.substring(prefixToRemove.length());
  543. }
  544. try {
  545. JSONObject jsonObject = JSON.parseObject(line);
  546. String sessionConversationId = jsonObject.get("conversation_id").toString();
  547. String event = jsonObject.get("event").toString();
  548. if (StringUtils.isEmpty(runId)) {
  549. if (StringUtils.isNotEmpty(sessionConversationId)) {
  550. runId = sessionConversationId;
  551. confessionSessionMapper.updateSingleField(confessionSessionId, "conversation_id", sessionConversationId);
  552. }
  553. }
  554. if (event.equals("message")) {
  555. String data = jsonObject.get("answer").toString();
  556. JSONObject dataObject = null;
  557. if (StringUtils.isNotEmpty(data)) {
  558. try {
  559. dataObject = JSON.parseObject(data);
  560. String code = dataObject.get("code").toString();
  561. if (StringUtils.equals(code, "200")) {
  562. JSONObject object = dataObject.getJSONObject("data");
  563. generateDoc(conversationName, confessionSessionId, object);
  564. }
  565. } catch (Exception e) {
  566. }
  567. }
  568. if (ObjectUtils.isNotEmpty(dataObject)) {
  569. JSONObject obj;
  570. if (StringUtils.isNotEmpty(sessionContent)) {
  571. obj = JSON.parseObject(sessionContent);
  572. obj.put("data", dataObject);
  573. } else {
  574. obj = new JSONObject();
  575. obj.put("data", dataObject);
  576. }
  577. confessionSessionMapper.updateSingleField(confessionSessionId, "content", obj.toString());
  578. }
  579. }
  580. } catch (Exception e) {
  581. }
  582. emitter.next(line); // 将每行数据发送到 Flux
  583. }
  584. } catch (IOException e) {
  585. emitter.error(e);
  586. } finally {
  587. emitter.complete();
  588. }
  589. }
  590. });
  591. });
  592. }
  593. public void generateDoc(String conversationName, Integer confessionSessionId, JSONObject object) {
  594. Map<String, Object> map = new HashMap<>();
  595. String reason = object.getString("reason");
  596. String num = object.getString("num");
  597. String claimChange = object.getString("claim_change");
  598. List<String> claimList = new ArrayList<>();
  599. if (StringUtils.isNotEmpty(claimChange)) {
  600. claimList = Arrays.asList(claimChange.split("\n"));
  601. }
  602. JSONArray jsonArray = object.getJSONArray("defense_opinion");
  603. // 创建List集合
  604. List<String> list = new ArrayList<>();
  605. // 遍历JSONArray并添加元素到List
  606. if (!CollectionUtils.isEmpty(jsonArray)) {
  607. for (Object o : jsonArray) {
  608. String str = o.toString();
  609. if (StringUtils.isNotEmpty(str)) {
  610. String[] split1 = str.split("\n");
  611. list.addAll(Arrays.asList(split1));
  612. }
  613. }
  614. }
  615. map.put("num", num);
  616. map.put("reason", reason);
  617. map.put("claim_change", claimList);
  618. map.put("defense_opinion", list);
  619. ReportTemple reportTemplate = templeService.getById(20);
  620. String templateFilePath = fileUtils.getPath(reportTemplate.getTemplatePath());
  621. //更新会话
  622. String name = DateUtils.dateTimeToStr(new Date(), "yyyyMMdd");
  623. String finalName = name + "-" + conversationName + "-陈述意见书";
  624. //生成文档
  625. String fileGuid = null;
  626. try {
  627. fileGuid = this.generateOADefenseFile(map, templateFilePath, finalName);
  628. AssoConfessionSessionFile assoConfessionSessionFile = new AssoConfessionSessionFile();
  629. assoConfessionSessionFile.setGuid(fileGuid);
  630. assoConfessionSessionFile.setConfessionSessionId(confessionSessionId);
  631. assoConfessionSessionFile.insert();
  632. } catch (Exception e) {
  633. throw new XiaoShiException(ExceptionEnum.BUSINESS_ERROR, "加载陈述意见书失败");
  634. }
  635. }
  636. /**
  637. * 生成OA答辩文件
  638. *
  639. * @param map
  640. * @param templateFilePath
  641. * @param name
  642. * @return
  643. * @throws Exception
  644. */
  645. public String generateOADefenseFile(Map<String, Object> map, String templateFilePath, String name) throws Exception {
  646. XWPFTemplate xwpfTemplate = this.getHtmlTemplate(map, templateFilePath);
  647. String fileName = name + ".docx";
  648. String directoryName = fileUtils.createDirectory();
  649. String outPath = fileUtils.getSavePath(directoryName) + fileName;
  650. File file = new File(outPath);
  651. // 生成word保存在指定目录
  652. xwpfTemplate.writeToFile(outPath);
  653. xwpfTemplate.close();
  654. List<String> ids = fileManagerService.uploadFileGetGuid2(Collections.singletonList(file));
  655. if (CollectionUtils.isEmpty(ids)) {
  656. throw new XiaoShiException("保存记录失败");
  657. }
  658. return ids.get(0);
  659. }
  660. private XWPFTemplate getHtmlTemplate(Map<String, Object> map, String filePath) {
  661. XWPFTemplate template = null;
  662. try {
  663. HtmlRenderPolicy htmlRenderPolicy = new HtmlRenderPolicy();
  664. ConfigureBuilder configureBuilder = Configure.builder().useSpringEL(false);
  665. configureBuilder.bind("#this", htmlRenderPolicy);
  666. Configure configure = configureBuilder.build();
  667. template = XWPFTemplate.compile(filePath, configure).render(map);
  668. } catch (Exception e) {
  669. e.printStackTrace();
  670. throw new XiaoShiException(ExceptionEnum.BUSINESS_ERROR, "未匹配到模版文件");
  671. }
  672. return template;
  673. }
  674. /**
  675. * 调用质检
  676. */
  677. public String WordErrorWorkFlow(DifyChatMessageDTO difyChatMessageDTO) throws IOException {
  678. String param = new Gson().toJson(difyChatMessageDTO);
  679. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  680. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  681. .connectTimeout(600, TimeUnit.SECONDS)
  682. .writeTimeout(600, TimeUnit.SECONDS)
  683. .readTimeout(600, TimeUnit.SECONDS)
  684. .build();
  685. Request request = new Request.Builder()
  686. .url(url + "workflows/run")
  687. .post(requestBody)
  688. .addHeader("Authorization", "Bearer " + checkApiKey)
  689. .build();
  690. return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  691. }
  692. /**
  693. * 获取具体实施方式
  694. */
  695. public String getImplementation(Map<String, Object> map) throws IOException {
  696. String param = new Gson().toJson(map);
  697. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  698. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  699. .connectTimeout(60, TimeUnit.SECONDS)
  700. .writeTimeout(60, TimeUnit.SECONDS)
  701. .readTimeout(60, TimeUnit.SECONDS)
  702. .build();
  703. Request request = new Request.Builder()
  704. .url(url + "chat-messages")
  705. .post(requestBody)
  706. .addHeader("Authorization", "Bearer " + checkApiKey)
  707. .build();
  708. return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  709. }
  710. public String generateClaimExplainRequest(GenerateClaimDTO generateClaimDTO) throws Exception {
  711. String claim = generateClaimDTO.getClaim();
  712. String background = generateClaimDTO.getBackground();
  713. DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO();
  714. String userId = "1";
  715. // String userId = loginUtils.getId().toString();
  716. Map<String, Object> map = new HashMap<>();
  717. map.put("claim", claim);
  718. map.put("background", background);
  719. difyChatMessageDTO.setInputs(map);
  720. difyChatMessageDTO.setResponseMode("blocking");
  721. difyChatMessageDTO.setUser(userId);
  722. String param = new Gson().toJson(difyChatMessageDTO);
  723. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  724. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  725. .connectTimeout(6000, TimeUnit.SECONDS)
  726. .writeTimeout(6000, TimeUnit.SECONDS)
  727. .readTimeout(6000, TimeUnit.SECONDS)
  728. .build();
  729. Request request = new Request.Builder()
  730. .url(url + "workflows/run")
  731. .post(requestBody)
  732. .addHeader("Authorization", "Bearer " + cliamKey)
  733. .build();
  734. String res = Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  735. return res;
  736. }
  737. public Flux<String> discoveryResultDialogue(ChatMessageDTO chatMessageDTO) {
  738. Integer confessionSessionId = chatMessageDTO.getConfessionSessionId();
  739. String conversationId = chatMessageDTO.getConversationId();
  740. String userId = loginUtils.getId().toString();
  741. String query = chatMessageDTO.getQuery();
  742. Integer type = chatMessageDTO.getType();
  743. if (type == null || query == null || query.trim().equals("")) {
  744. throw new XiaoShiException(ExceptionEnum.BUSINESS_CHECK, "请按要求输入参数");
  745. }
  746. if (conversationId == null) {
  747. conversationId = assoConfessionConversationService.getConversationId(confessionSessionId, type);
  748. }
  749. String temConversationId = conversationId;
  750. String temConversationId3=conversationId;
  751. OkHttpClient client = new OkHttpClient.Builder()
  752. .connectTimeout(600, TimeUnit.SECONDS)
  753. .writeTimeout(600, TimeUnit.SECONDS)
  754. .readTimeout(600, TimeUnit.SECONDS)
  755. .build();
  756. DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO();
  757. Map<String, Object> map = new HashMap<>();
  758. String fileContent = "";
  759. ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId);
  760. List<String> guids = assoConfessionSessionFileService.getFileGuid(confessionSessionId, 0);
  761. if (guids == null || guids.size() == 0) {
  762. throw new XiaoShiException(ExceptionEnum.BUSINESS_ERROR, "数据错误,未检测到交底书");
  763. }
  764. fileContent = fileDownloadUrl + guids.get(0);
  765. map.put("file_path", fileContent);
  766. map.put("data_Result", confessionSession.getResultContent());
  767. map.put("ask_type", "type.toString()");
  768. difyChatMessageDTO.setInputs(map);
  769. difyChatMessageDTO.setConversationId(conversationId);
  770. difyChatMessageDTO.setResponseMode("streaming");
  771. difyChatMessageDTO.setUser(userId);
  772. difyChatMessageDTO.setQuery(query);
  773. difyChatMessageDTO.setFiles(new ArrayList<>());
  774. String param = new Gson().toJson(difyChatMessageDTO);
  775. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  776. Request request = this.getChatMessageRequest(requestBody,discoveryResultKey);
  777. return Flux.create(emitter -> {
  778. client.newCall(request).enqueue(new Callback() {
  779. @Override
  780. public void onFailure(Call call, IOException e) {
  781. emitter.error(e);
  782. }
  783. @Override
  784. public void onResponse(Call call, Response response) throws IOException {
  785. if (!response.isSuccessful()) {
  786. emitter.error(new IOException("Unexpected code: " + response));
  787. return;
  788. }
  789. try (Reader reader = response.body().charStream()) {
  790. BufferedReader bufferedReader = new BufferedReader(reader);
  791. String line;
  792. String temConversationId2 = temConversationId;
  793. String prefixToRemove = "data: ";
  794. while ((line = bufferedReader.readLine()) != null) {
  795. if (line.isEmpty()) {
  796. continue;
  797. }
  798. if (line.startsWith(prefixToRemove)) {
  799. line = line.substring(prefixToRemove.length());
  800. }
  801. if (temConversationId2 == null || temConversationId2.isEmpty()) {
  802. try {
  803. JSONObject jsonObject = JSON.parseObject(line);
  804. temConversationId2 = jsonObject.get("conversation_id").toString();
  805. AssoConfessionConversation assoConfessionConversation = new AssoConfessionConversation();
  806. assoConfessionConversation.setConfessionId(confessionSessionId);
  807. assoConfessionConversation.setConversationId(temConversationId2);
  808. assoConfessionConversation.setType(type);
  809. assoConfessionConversation.insert();
  810. } catch (Exception e) {
  811. }
  812. }
  813. emitter.next(line); // 将每行数据发送到 Flux
  814. }
  815. } catch (IOException e) {
  816. emitter.error(e);
  817. } finally {
  818. emitter.complete();
  819. }
  820. }
  821. });
  822. });
  823. }
  824. public Request getGeneratePatentResultResultRequest(Integer confessionSessionId,DifyChatMessageDTO difyChatMessageDTO,String aiKey){
  825. String param = new Gson().toJson(difyChatMessageDTO);
  826. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  827. Request request = this.getChatMessageRequest(requestBody,aiKey);
  828. return request;
  829. }
  830. }