DifyService.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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.CacheUtils;
  7. import cn.cslg.pas.common.utils.ClaimUtils.ClaimSplitUtils;
  8. import cn.cslg.pas.common.utils.DataUtils;
  9. import cn.cslg.pas.common.utils.DateUtils;
  10. import cn.cslg.pas.common.utils.LoginUtils;
  11. import cn.cslg.pas.common.vo.PatentRightParams;
  12. import cn.cslg.pas.domain.business.TechnicalCase;
  13. import cn.cslg.pas.domain.dify.ConfessionSession;
  14. import cn.cslg.pas.domain.report.AssoProjectConfession;
  15. import cn.cslg.pas.mapper.dify.ConfessionSessionMapper;
  16. import cn.cslg.pas.service.business.TechnicalCaseService;
  17. import cn.cslg.pas.service.dify.ConfessionSessionService;
  18. import cn.cslg.pas.service.dify.DifySessionService;
  19. import cn.cslg.pas.service.report.AssoProjectConfessionService;
  20. import com.alibaba.fastjson.JSON;
  21. import com.alibaba.fastjson.JSONArray;
  22. import com.alibaba.fastjson.JSONObject;
  23. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  24. import com.fasterxml.jackson.databind.JsonNode;
  25. import com.fasterxml.jackson.databind.ObjectMapper;
  26. import com.google.gson.Gson;
  27. import com.google.gson.GsonBuilder;
  28. import lombok.RequiredArgsConstructor;
  29. import lombok.extern.slf4j.Slf4j;
  30. import okhttp3.*;
  31. import org.apache.commons.lang3.ObjectUtils;
  32. import org.apache.commons.lang3.StringUtils;
  33. import org.springframework.beans.factory.annotation.Autowired;
  34. import org.springframework.beans.factory.annotation.Value;
  35. import org.springframework.http.HttpHeaders;
  36. import org.springframework.stereotype.Service;
  37. import org.springframework.transaction.annotation.Transactional;
  38. import org.w3c.dom.DocumentType;
  39. import reactor.core.publisher.Flux;
  40. import javax.swing.text.Document;
  41. import java.io.*;
  42. import java.util.*;
  43. import java.util.concurrent.TimeUnit;
  44. /**
  45. * Okhttp调用FMS上传文件接口
  46. *
  47. * @Author lrj
  48. * @Date 2025/4/10
  49. */
  50. @RequiredArgsConstructor
  51. @Slf4j
  52. @Service
  53. public class DifyService {
  54. @Value("${DIFY.apiKey}")
  55. private String apiKey;
  56. @Value("${DIFY.OAApiKey}")
  57. private String OAApiKey;
  58. @Value("${DIFY.url}")
  59. private String url;
  60. @Value("${DIFY.checkApiKey}")
  61. private String checkApiKey;
  62. @Value("${FileDownloadUrl}")
  63. private String fileDownloadUrl;
  64. @Value("${DIFY.cliamKey}")
  65. private String cliamKey;
  66. private final DifySessionService difySessionService;
  67. private final TechnicalCaseService technicalCaseService;
  68. private final AssoProjectConfessionService assoProjectConfessionService;
  69. @Autowired
  70. private CacheUtils cacheUtils;
  71. @Autowired
  72. private LoginUtils loginUtils;
  73. private final ConfessionSessionService confessionSessionService;
  74. @Autowired
  75. private ConfessionSessionMapper confessionSessionMapper;
  76. /**
  77. * 调用文件系统删除文件接口
  78. */
  79. public String chatMessage(DifyChatMessageDTO difyChatMessageDTO,String key) throws IOException {
  80. String param = new Gson().toJson(difyChatMessageDTO);
  81. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  82. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  83. .connectTimeout(600, TimeUnit.SECONDS)
  84. .writeTimeout(600, TimeUnit.SECONDS)
  85. .readTimeout(600, TimeUnit.SECONDS)
  86. .build();
  87. Request request = new Request.Builder()
  88. .url(url + "chat-messages")
  89. .post(requestBody)
  90. .addHeader("Authorization", "Bearer " + key)
  91. .build();
  92. return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  93. }
  94. /**
  95. * 调用文件系统删除文件接口
  96. */
  97. public String queryHistoryMessage(DifyHistoryMessageDTO difyChatMessageDTO) throws IOException {
  98. difyChatMessageDTO.setUser(loginUtils.getId().toString());
  99. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  100. .connectTimeout(600, TimeUnit.SECONDS)
  101. .writeTimeout(600, TimeUnit.SECONDS)
  102. .readTimeout(600, TimeUnit.SECONDS)
  103. .build();
  104. String path = "messages?conversation_id=" + difyChatMessageDTO.getConversationId() + "&user=" + difyChatMessageDTO.getUser() + "&limit=" + difyChatMessageDTO.getLimit();
  105. if (difyChatMessageDTO.getFirstId() != null) {
  106. path += "&first_id=" + difyChatMessageDTO.getFirstId();
  107. }
  108. Request request = new Request.Builder()
  109. .url(url + path)
  110. .get()
  111. .addHeader("Authorization", "Bearer " + apiKey)
  112. .build();
  113. return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  114. }
  115. public Flux<String> getOkhttp(ChatMessageDTO chatMessageDTO) {
  116. Integer projectId = chatMessageDTO.getProjectId();
  117. Integer confessionSessionId = chatMessageDTO.getConfessionSessionId();
  118. String conversationId = chatMessageDTO.getConversationId();
  119. String userId = loginUtils.getId().toString();
  120. String query = chatMessageDTO.getQuery();
  121. if (conversationId == null) {
  122. conversationId = difySessionService.getSessionId(projectId, userId);
  123. }
  124. String temConversationId = conversationId;
  125. OkHttpClient client = new OkHttpClient.Builder()
  126. .connectTimeout(600, TimeUnit.SECONDS)
  127. .writeTimeout(600, TimeUnit.SECONDS)
  128. .readTimeout(600, TimeUnit.SECONDS)
  129. .build();
  130. DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO();
  131. Map<String, Object> map = new HashMap<>();
  132. String fileContent = "";
  133. String inventionPoint = "";
  134. if (projectId != null) {
  135. fileContent = this.getConfression(projectId);
  136. inventionPoint = this.getInventPoint(projectId);
  137. } else if (confessionSessionId != null) {
  138. ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId);
  139. fileContent = fileDownloadUrl + confessionSession.getGuid();
  140. inventionPoint = confessionSession.getInventionPoint();
  141. }
  142. map.put("file_path", fileContent);
  143. map.put("invention_point", inventionPoint);
  144. difyChatMessageDTO.setInputs(map);
  145. difyChatMessageDTO.setConversationId(conversationId);
  146. difyChatMessageDTO.setResponseMode("streaming");
  147. difyChatMessageDTO.setUser(userId);
  148. difyChatMessageDTO.setQuery(query);
  149. difyChatMessageDTO.setFiles(new ArrayList<>());
  150. String param = new Gson().toJson(difyChatMessageDTO);
  151. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  152. Request request = this.getChatMessageRequest(requestBody);
  153. return Flux.create(emitter -> {
  154. client.newCall(request).enqueue(new Callback() {
  155. @Override
  156. public void onFailure(Call call, IOException e) {
  157. emitter.error(e);
  158. }
  159. @Override
  160. public void onResponse(Call call, Response response) throws IOException {
  161. if (!response.isSuccessful()) {
  162. emitter.error(new IOException("Unexpected code: " + response));
  163. return;
  164. }
  165. try (Reader reader = response.body().charStream()) {
  166. BufferedReader bufferedReader = new BufferedReader(reader);
  167. String line;
  168. String temConversationId2 = temConversationId;
  169. String prefixToRemove = "data: ";
  170. while ((line = bufferedReader.readLine()) != null) {
  171. if (line.isEmpty()) {
  172. continue;
  173. }
  174. if (line.startsWith(prefixToRemove)) {
  175. line = line.substring(prefixToRemove.length());
  176. }
  177. if (temConversationId2 == null || temConversationId2.isEmpty()) {
  178. try {
  179. JSONObject jsonObject = JSON.parseObject(line);
  180. temConversationId2 = jsonObject.get("conversation_id").toString();
  181. if (projectId != null) {
  182. difySessionService.addDifySession(projectId, userId, temConversationId2);
  183. }
  184. if (confessionSessionId != null) {
  185. UpdateConfessionSessionDTO updateConfessionSessionDTO = new UpdateConfessionSessionDTO();
  186. updateConfessionSessionDTO.setConfessionSessionId(confessionSessionId);
  187. updateConfessionSessionDTO.setConversationId(temConversationId2);
  188. confessionSessionService.updateConfessionSession(updateConfessionSessionDTO);
  189. }
  190. } catch (Exception e) {
  191. }
  192. }
  193. emitter.next(line); // 将每行数据发送到 Flux
  194. }
  195. } catch (IOException e) {
  196. emitter.error(e);
  197. } finally {
  198. emitter.complete();
  199. }
  200. }
  201. });
  202. });
  203. }
  204. public String getInventPoint(Integer projectId) {
  205. String re = "";
  206. TechnicalCase technicalCase = technicalCaseService.getByProjectId(projectId);
  207. if (technicalCase != null) {
  208. if (technicalCase.getInventionPoint() != null) {
  209. re = technicalCase.getInventionPoint();
  210. }
  211. }
  212. return re;
  213. }
  214. public String getConfression(Integer projectId) {
  215. String url = "";
  216. AssoProjectConfession assoProjectConfession = assoProjectConfessionService.queryAssoProjectConfession(projectId);
  217. if (assoProjectConfession != null) {
  218. url = fileDownloadUrl + assoProjectConfession.getFileGuid();
  219. }
  220. return url;
  221. }
  222. public Request getChatMessageRequest(RequestBody requestBody) {
  223. Request request = new Request.Builder()
  224. .url(url + "chat-messages")
  225. .addHeader("Authorization", "Bearer " + apiKey).addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  226. .post(requestBody)
  227. .build();
  228. return request;
  229. }
  230. public JSONObject stopMessage(String taskId) throws IOException {
  231. OkHttpClient client = new OkHttpClient.Builder()
  232. .connectTimeout(60, TimeUnit.SECONDS)
  233. .writeTimeout(60, TimeUnit.SECONDS)
  234. .readTimeout(60, TimeUnit.SECONDS)
  235. .build();
  236. DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO();
  237. difyChatMessageDTO.setUser("1");
  238. String param = new Gson().toJson(difyChatMessageDTO);
  239. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  240. Request request = new Request.Builder()
  241. .url(url + "chat-messages/" + taskId + "/stop")
  242. .addHeader("Authorization", "Bearer " + apiKey).addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  243. .post(requestBody)
  244. .build();
  245. String json = Objects.requireNonNull(client.newCall(request).execute().body()).string();
  246. JSONObject jsonObject = JSONObject.parseObject(json);
  247. return jsonObject;
  248. }
  249. @Transactional(rollbackFor = Exception.class)
  250. public Map<String, Object> generateInventionPoint(ChatMessageDTO chatMessageDTO) throws IOException {
  251. Integer projectId = chatMessageDTO.getProjectId();
  252. Integer confessionSessionId = chatMessageDTO.getConfessionSessionId();
  253. String query = "生成发明点";
  254. String userId = loginUtils.getId().toString();
  255. String conversationId = chatMessageDTO.getConversationId();
  256. DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO();
  257. Map<String, Object> map = new HashMap<>();
  258. String fileContent = "";
  259. if (confessionSessionId != null) {
  260. ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId);
  261. fileContent = fileDownloadUrl + confessionSession.getGuid();
  262. } else if (projectId != null) {
  263. fileContent = this.getConfression(projectId);
  264. }
  265. map.put("file_path", fileContent);
  266. difyChatMessageDTO.setInputs(map);
  267. difyChatMessageDTO.setConversationId(conversationId);
  268. difyChatMessageDTO.setResponseMode("blocking");
  269. difyChatMessageDTO.setUser(userId);
  270. difyChatMessageDTO.setQuery(query);
  271. difyChatMessageDTO.setFiles(new ArrayList<>());
  272. OkHttpClient client = new OkHttpClient.Builder()
  273. .connectTimeout(600, TimeUnit.SECONDS)
  274. .writeTimeout(600, TimeUnit.SECONDS)
  275. .readTimeout(600, TimeUnit.SECONDS)
  276. .build();
  277. String param = new Gson().toJson(difyChatMessageDTO);
  278. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  279. Request request = this.getChatMessageRequest(requestBody);
  280. String res = Objects.requireNonNull(client.newCall(request).execute().body()).string();
  281. System.out.println(res);
  282. JSONObject jsonObject = JSONObject.parseObject(res);
  283. String inventionPoint = jsonObject.get("answer").toString();
  284. inventionPoint = DataUtils.getMarkDownText(inventionPoint);
  285. Map<String, Object> map1 = new HashMap<>();
  286. map1.put("invention_point", inventionPoint);
  287. if (projectId != null) {
  288. technicalCaseService.updateInventionPoint(projectId, inventionPoint);
  289. }
  290. if (confessionSessionId != null) {
  291. UpdateConfessionSessionDTO updateConfessionSessionDTO = new UpdateConfessionSessionDTO();
  292. updateConfessionSessionDTO.setConfessionSessionId(confessionSessionId);
  293. updateConfessionSessionDTO.setInventionPoint(inventionPoint);
  294. confessionSessionService.updateConfessionSession(updateConfessionSessionDTO);
  295. }
  296. map1.put("conversation_id", conversationId);
  297. map1.put("projectId", projectId);
  298. map1.put("confessionSessionId", confessionSessionId);
  299. return map1;
  300. }
  301. public List<Object> generateClaimExplain(GenerateClaimDTO generateClaimDTO) throws Exception {
  302. String claim = generateClaimDTO.getClaim();
  303. PatentRightParams params = new PatentRightParams();
  304. params.setCountry("CN");
  305. params.setContent(claim);
  306. params.setPatentNo("CN");
  307. ClaimSplitUtils.formatPatentRight(params);
  308. DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO();
  309. String userId = loginUtils.getId().toString();
  310. Map<String, Object> map = new HashMap<>();
  311. map.put("claim", claim);
  312. difyChatMessageDTO.setInputs(map);
  313. difyChatMessageDTO.setResponseMode("blocking");
  314. difyChatMessageDTO.setUser(userId);
  315. String param = new Gson().toJson(difyChatMessageDTO);
  316. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  317. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  318. .connectTimeout(6000, TimeUnit.SECONDS)
  319. .writeTimeout(6000, TimeUnit.SECONDS)
  320. .readTimeout(6000, TimeUnit.SECONDS)
  321. .build();
  322. Request request = new Request.Builder()
  323. .url(url + "workflows/run")
  324. .post(requestBody)
  325. .addHeader("Authorization", "Bearer " + cliamKey)
  326. .build();
  327. String res = Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  328. JSONObject jsonObject = JSONObject.parseObject(res);
  329. String dataStr = jsonObject.get("data").toString();
  330. JSONObject dataObject = JSONObject.parseObject(dataStr);
  331. String outPuts = dataObject.get("outputs").toString();
  332. JSONObject jsonObject1 = JSONObject.parseObject(outPuts);
  333. Object retsObj = jsonObject1.get("json");
  334. String rets = retsObj.toString();
  335. List<Object> reObject = JSONArray.parseArray(rets, Object.class);
  336. Map<String, Object> addMap = new HashMap<>();
  337. Map<String, Object> queryMap = new HashMap<>();
  338. queryMap.put("claim", claim);
  339. addMap.put("query", queryMap);
  340. addMap.put("answer", retsObj);
  341. String addStr = JSONObject.toJSONString(addMap);
  342. AddConfessionSessionDTO addConfessionSessionDTO = new AddConfessionSessionDTO();
  343. addConfessionSessionDTO.setConversationId(jsonObject.get("workflow_run_id").toString());
  344. addConfessionSessionDTO.setContent(addStr);
  345. String name = DateUtils.dateTimeToStr(new Date());
  346. name = name + "-权利要求解释及有益效果";
  347. addConfessionSessionDTO.setConversationName(name);
  348. addConfessionSessionDTO.setType(1);
  349. confessionSessionService.addSession(addConfessionSessionDTO);
  350. System.out.println(res);
  351. return reObject;
  352. }
  353. public Flux<String> successGetOAHttp(Integer confessionSessionId) {
  354. ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId);
  355. String fileUrl = fileDownloadUrl + confessionSession.getGuid();
  356. String userId = loginUtils.getId().toString();
  357. OkHttpClient client = new OkHttpClient.Builder()
  358. .connectTimeout(600, TimeUnit.SECONDS)
  359. .writeTimeout(600, TimeUnit.SECONDS)
  360. .readTimeout(600, TimeUnit.SECONDS)
  361. .build();
  362. Map<String, Object> map = new HashMap<>();
  363. map.put("fileUrl", fileUrl);
  364. OAMessageDTO oaMessageDTO = new OAMessageDTO();
  365. oaMessageDTO.setInputs(map);
  366. oaMessageDTO.setResponseMode("streaming");
  367. oaMessageDTO.setUser(userId);
  368. oaMessageDTO.setFiles(new ArrayList<>());
  369. String param = new Gson().toJson(oaMessageDTO);
  370. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  371. Request request = new Request.Builder()
  372. .url(url + "workflows/run")
  373. .addHeader("Authorization", "Bearer " + OAApiKey)
  374. .addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  375. .post(requestBody)
  376. .build();
  377. return Flux.create(emitter -> {
  378. client.newCall(request).enqueue(new Callback() {
  379. @Override
  380. public void onFailure(Call call, IOException e) {
  381. emitter.error(e);
  382. }
  383. @Override
  384. public void onResponse(Call call, Response response) throws IOException {
  385. if (!response.isSuccessful()) {
  386. emitter.error(new IOException("Unexpected code: " + response));
  387. return;
  388. }
  389. try (Reader reader = response.body().charStream()) {
  390. BufferedReader bufferedReader = new BufferedReader(reader);
  391. String line;
  392. String prefixToRemove = "data: ";
  393. String runId = "";
  394. while ((line = bufferedReader.readLine()) != null) {
  395. if (line.isEmpty()) {
  396. continue;
  397. }
  398. if (line.startsWith(prefixToRemove)) {
  399. line = line.substring(prefixToRemove.length());
  400. }
  401. try {
  402. JSONObject jsonObject = JSON.parseObject(line);
  403. String workflowRunId = jsonObject.get("workflow_run_id").toString();
  404. String event = jsonObject.get("event").toString();
  405. if (StringUtils.isNotEmpty(workflowRunId)) {
  406. if (StringUtils.isEmpty(runId)) {
  407. runId = workflowRunId;
  408. confessionSessionMapper.updateSingleField(confessionSessionId, "conversation_id", workflowRunId);
  409. }
  410. }
  411. if (event.equals("workflow_finished")) {
  412. String data = jsonObject.get("data").toString();
  413. String content = "";
  414. if (StringUtils.isNotEmpty(data)) {
  415. JSONObject dataObject = JSON.parseObject(data);
  416. String outputs = dataObject.get("outputs").toString();
  417. if (StringUtils.isNotEmpty(outputs)) {
  418. JSONObject outputsObject = JSON.parseObject(outputs);
  419. String output = outputsObject.get("output").toString();
  420. content = DataUtils.unicodeDecode(output);
  421. }
  422. }
  423. if (StringUtils.isNotEmpty(content)) {
  424. JSONObject obj = new JSONObject();
  425. obj.put("answer", content);
  426. confessionSessionMapper.updateSingleField(confessionSessionId, "content", obj.toString());
  427. }
  428. }
  429. } catch (Exception e) {
  430. }
  431. emitter.next(line); // 将每行数据发送到 Flux
  432. }
  433. } catch (IOException e) {
  434. emitter.error(e);
  435. } finally {
  436. emitter.complete();
  437. }
  438. }
  439. });
  440. });
  441. }
  442. /**
  443. * 调用质检
  444. */
  445. public String WordErrorWorkFlow(DifyChatMessageDTO difyChatMessageDTO) throws IOException {
  446. String param = new Gson().toJson(difyChatMessageDTO);
  447. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  448. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  449. .connectTimeout(600, TimeUnit.SECONDS)
  450. .writeTimeout(600, TimeUnit.SECONDS)
  451. .readTimeout(600, TimeUnit.SECONDS)
  452. .build();
  453. Request request = new Request.Builder()
  454. .url(url + "workflows/run")
  455. .post(requestBody)
  456. .addHeader("Authorization", "Bearer " + checkApiKey)
  457. .build();
  458. return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  459. }
  460. /**
  461. * 获取具体实施方式
  462. */
  463. public String getImplementation(Map<String, Object> map) throws IOException {
  464. String param = new Gson().toJson(map);
  465. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  466. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  467. .connectTimeout(60, TimeUnit.SECONDS)
  468. .writeTimeout(60, TimeUnit.SECONDS)
  469. .readTimeout(60, TimeUnit.SECONDS)
  470. .build();
  471. Request request = new Request.Builder()
  472. .url(url + "chat-messages")
  473. .post(requestBody)
  474. .addHeader("Authorization", "Bearer " + checkApiKey)
  475. .build();
  476. return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  477. }
  478. public String generateClaimExplainRequest(GenerateClaimDTO generateClaimDTO) throws Exception {
  479. String claim = generateClaimDTO.getClaim();
  480. String background = generateClaimDTO.getBackground();
  481. DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO();
  482. String userId ="1";
  483. // String userId = loginUtils.getId().toString();
  484. Map<String, Object> map = new HashMap<>();
  485. map.put("claim", claim);
  486. map.put("background", background);
  487. difyChatMessageDTO.setInputs(map);
  488. difyChatMessageDTO.setResponseMode("blocking");
  489. difyChatMessageDTO.setUser(userId);
  490. String param = new Gson().toJson(difyChatMessageDTO);
  491. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param);
  492. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  493. .connectTimeout(6000, TimeUnit.SECONDS)
  494. .writeTimeout(6000, TimeUnit.SECONDS)
  495. .readTimeout(6000, TimeUnit.SECONDS)
  496. .build();
  497. Request request = new Request.Builder()
  498. .url(url + "workflows/run")
  499. .post(requestBody)
  500. .addHeader("Authorization", "Bearer " + cliamKey)
  501. .build();
  502. String res = Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
  503. return res;
  504. }
  505. }