package cn.cslg.pas.service.common; import cn.cslg.pas.common.model.dify.*; import cn.cslg.pas.common.model.dify.GenerateClaimDTO; import cn.cslg.pas.common.model.dify.confessionSession.AddConfessionSessionDTO; import cn.cslg.pas.common.model.dify.confessionSession.UpdateConfessionSessionDTO; import cn.cslg.pas.common.model.dify.generateDiscoveryResult.DiscoryResultVO; import cn.cslg.pas.common.utils.*; import cn.cslg.pas.common.utils.ClaimUtils.ClaimSplitUtils; import cn.cslg.pas.common.vo.PatentRightParams; import cn.cslg.pas.domain.business.ReportTemple; import cn.cslg.pas.domain.business.TechnicalCase; import cn.cslg.pas.domain.dify.AssoConfessionConversation; import cn.cslg.pas.domain.dify.AssoConfessionSessionFile; import cn.cslg.pas.domain.dify.ConfessionSession; import cn.cslg.pas.domain.report.AssoProjectConfession; import cn.cslg.pas.exception.ExceptionEnum; import cn.cslg.pas.exception.XiaoShiException; import cn.cslg.pas.mapper.dify.ConfessionSessionMapper; import cn.cslg.pas.service.business.ReportTempleService; import cn.cslg.pas.service.business.TechnicalCaseService; import cn.cslg.pas.service.dify.*; import cn.cslg.pas.service.report.AssoProjectConfessionService; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.deepoove.poi.XWPFTemplate; import com.deepoove.poi.config.Configure; import com.deepoove.poi.config.ConfigureBuilder; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import okhttp3.Response; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.ddr.poi.html.HtmlRenderPolicy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import org.w3c.dom.DocumentType; import reactor.core.publisher.Flux; import javax.swing.text.Document; import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; /** * Okhttp调用FMS上传文件接口 * * @Author lrj * @Date 2025/4/10 */ @RequiredArgsConstructor @Slf4j @Service public class DifyService { @Value("${DIFY.apiKey}") private String apiKey; @Value("${DIFY.OAApiKey}") private String OAApiKey; @Value("${DIFY.url}") private String url; @Value("${DIFY.checkApiKey}") private String checkApiKey; @Value("${FileDownloadUrl}") private String fileDownloadUrl; @Value("${DIFY.cliamKey}") private String cliamKey; @Value("${DIFY.discoveryResultKey}") private String discoveryResultKey; private final DifySessionService difySessionService; private final TechnicalCaseService technicalCaseService; private final AssoProjectConfessionService assoProjectConfessionService; @Autowired private CacheUtils cacheUtils; @Autowired private LoginUtils loginUtils; private final ConfessionSessionService confessionSessionService; @Autowired private ConfessionSessionMapper confessionSessionMapper; @Autowired private ReportTempleService templeService; @Autowired private FileUtils fileUtils; @Autowired private FileManagerService fileManagerService; @Autowired @Lazy private GenerateInstructionService generateInstructionService; @Autowired private AssoConfessionConversationService assoConfessionConversationService; @Autowired private AssoConfessionSessionFileService assoConfessionSessionFileService; /** * 调用文件系统删除文件接口 */ public String chatMessage(DifyChatMessageDTO difyChatMessageDTO, String key) throws IOException { String param = new Gson().toJson(difyChatMessageDTO); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param); OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(600, TimeUnit.SECONDS) .writeTimeout(600, TimeUnit.SECONDS) .readTimeout(600, TimeUnit.SECONDS) .build(); Request request = new Request.Builder() .url(url + "chat-messages") .post(requestBody) .addHeader("Authorization", "Bearer " + key) .build(); return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string(); } /** * 调用文件系统删除文件接口 */ public String queryHistoryMessage(DifyHistoryMessageDTO difyChatMessageDTO) throws IOException { difyChatMessageDTO.setUser(loginUtils.getId().toString()); OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(600, TimeUnit.SECONDS) .writeTimeout(600, TimeUnit.SECONDS) .readTimeout(600, TimeUnit.SECONDS) .build(); Integer type =difyChatMessageDTO.getType(); String path = "messages?conversation_id=" + difyChatMessageDTO.getConversationId() + "&user=" + difyChatMessageDTO.getUser() + "&limit=" + difyChatMessageDTO.getLimit(); if (difyChatMessageDTO.getFirstId() != null) { path += "&first_id=" + difyChatMessageDTO.getFirstId(); } String key =apiKey; if(type!=null&&type.equals(4)){ key=discoveryResultKey; } Request request = new Request.Builder() .url(url + path) .get() .addHeader("Authorization", "Bearer " + key) .build(); return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string(); } public Flux getOkhttp(ChatMessageDTO chatMessageDTO) { Integer projectId = chatMessageDTO.getProjectId(); Integer confessionSessionId = chatMessageDTO.getConfessionSessionId(); String conversationId = chatMessageDTO.getConversationId(); String userId = loginUtils.getId().toString(); String query = chatMessageDTO.getQuery(); if (conversationId == null) { conversationId = difySessionService.getSessionId(projectId, userId); } String temConversationId = conversationId; OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(600, TimeUnit.SECONDS) .writeTimeout(600, TimeUnit.SECONDS) .readTimeout(600, TimeUnit.SECONDS) .build(); DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO(); Map map = new HashMap<>(); String fileContent = ""; String inventionPoint = ""; if (projectId != null) { fileContent = this.getConfression(projectId); inventionPoint = this.getInventPoint(projectId); } else if (confessionSessionId != null) { ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId); fileContent = fileDownloadUrl + confessionSession.getGuid(); inventionPoint = confessionSession.getInventionPoint(); } map.put("file_path", fileContent); map.put("invention_point", inventionPoint); difyChatMessageDTO.setInputs(map); difyChatMessageDTO.setConversationId(conversationId); difyChatMessageDTO.setResponseMode("streaming"); difyChatMessageDTO.setUser(userId); difyChatMessageDTO.setQuery(query); difyChatMessageDTO.setFiles(new ArrayList<>()); String param = new Gson().toJson(difyChatMessageDTO); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param); Request request = this.getChatMessageRequest(requestBody,apiKey); return Flux.create(emitter -> { client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { emitter.error(e); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { emitter.error(new IOException("Unexpected code: " + response)); return; } try (Reader reader = response.body().charStream()) { BufferedReader bufferedReader = new BufferedReader(reader); String line; String temConversationId2 = temConversationId; String prefixToRemove = "data: "; while ((line = bufferedReader.readLine()) != null) { if (line.isEmpty()) { continue; } if (line.startsWith(prefixToRemove)) { line = line.substring(prefixToRemove.length()); } if (temConversationId2 == null || temConversationId2.isEmpty()) { try { JSONObject jsonObject = JSON.parseObject(line); temConversationId2 = jsonObject.get("conversation_id").toString(); if (projectId != null) { difySessionService.addDifySession(projectId, userId, temConversationId2); } if (confessionSessionId != null) { UpdateConfessionSessionDTO updateConfessionSessionDTO = new UpdateConfessionSessionDTO(); updateConfessionSessionDTO.setConfessionSessionId(confessionSessionId); updateConfessionSessionDTO.setConversationId(temConversationId2); confessionSessionService.updateConfessionSession(updateConfessionSessionDTO); } } catch (Exception e) { } } emitter.next(line); // 将每行数据发送到 Flux } } catch (IOException e) { emitter.error(e); } finally { emitter.complete(); } } }); }); } public String getInventPoint(Integer projectId) { String re = ""; TechnicalCase technicalCase = technicalCaseService.getByProjectId(projectId); if (technicalCase != null) { if (technicalCase.getInventionPoint() != null) { re = technicalCase.getInventionPoint(); } } return re; } public String getConfression(Integer projectId) { String url = ""; AssoProjectConfession assoProjectConfession = assoProjectConfessionService.queryAssoProjectConfession(projectId); if (assoProjectConfession != null) { url = fileDownloadUrl + assoProjectConfession.getFileGuid(); } return url; } public Request getChatMessageRequest(RequestBody requestBody,String key) { Request request = new Request.Builder() .url(url + "chat-messages") .addHeader("Authorization", "Bearer " + key).addHeader(HttpHeaders.CONTENT_TYPE, "application/json") .post(requestBody) .build(); return request; } public JSONObject stopMessage(String taskId,Integer type) throws IOException { OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .build(); DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO(); difyChatMessageDTO.setUser("1"); String param = new Gson().toJson(difyChatMessageDTO); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param); String key =apiKey; if(type!=null&&type.equals(4)){ key=discoveryResultKey; } Request request = new Request.Builder() .url(url + "chat-messages/" + taskId + "/stop") .addHeader("Authorization", "Bearer " + key).addHeader(HttpHeaders.CONTENT_TYPE, "application/json") .post(requestBody) .build(); String json = Objects.requireNonNull(client.newCall(request).execute().body()).string(); JSONObject jsonObject = JSONObject.parseObject(json); return jsonObject; } @Transactional(rollbackFor = Exception.class) public Map generateInventionPoint(ChatMessageDTO chatMessageDTO) throws IOException { Integer projectId = chatMessageDTO.getProjectId(); Integer confessionSessionId = chatMessageDTO.getConfessionSessionId(); String query = "生成发明点"; String userId = loginUtils.getId().toString(); String conversationId = chatMessageDTO.getConversationId(); DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO(); Map map = new HashMap<>(); String fileContent = ""; if (confessionSessionId != null) { ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId); fileContent = fileDownloadUrl + confessionSession.getGuid(); } else if (projectId != null) { fileContent = this.getConfression(projectId); } map.put("file_path", fileContent); difyChatMessageDTO.setInputs(map); difyChatMessageDTO.setConversationId(conversationId); difyChatMessageDTO.setResponseMode("blocking"); difyChatMessageDTO.setUser(userId); difyChatMessageDTO.setQuery(query); difyChatMessageDTO.setFiles(new ArrayList<>()); OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(600, TimeUnit.SECONDS) .writeTimeout(600, TimeUnit.SECONDS) .readTimeout(600, TimeUnit.SECONDS) .build(); String param = new Gson().toJson(difyChatMessageDTO); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param); Request request = this.getChatMessageRequest(requestBody,apiKey); String res = Objects.requireNonNull(client.newCall(request).execute().body()).string(); JSONObject jsonObject = JSONObject.parseObject(res); String inventionPoint = jsonObject.get("answer").toString(); inventionPoint = DataUtils.getMarkDownText(inventionPoint); Map map1 = new HashMap<>(); map1.put("invention_point", inventionPoint); if (projectId != null) { technicalCaseService.updateInventionPoint(projectId, inventionPoint); } if (confessionSessionId != null) { UpdateConfessionSessionDTO updateConfessionSessionDTO = new UpdateConfessionSessionDTO(); updateConfessionSessionDTO.setConfessionSessionId(confessionSessionId); updateConfessionSessionDTO.setInventionPoint(inventionPoint); confessionSessionService.updateConfessionSession(updateConfessionSessionDTO); } map1.put("conversation_id", conversationId); map1.put("projectId", projectId); map1.put("confessionSessionId", confessionSessionId); return map1; } public List generateClaimExplain(GenerateClaimDTO generateClaimDTO) throws Exception { String claim = generateClaimDTO.getClaim(); PatentRightParams params = new PatentRightParams(); params.setCountry("CN"); params.setContent(claim); params.setPatentNo("CN"); ClaimSplitUtils.formatPatentRight(params); DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO(); String userId = loginUtils.getId().toString(); Map map = new HashMap<>(); map.put("claim", claim); difyChatMessageDTO.setInputs(map); difyChatMessageDTO.setResponseMode("blocking"); difyChatMessageDTO.setUser(userId); String param = new Gson().toJson(difyChatMessageDTO); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param); OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(6000, TimeUnit.SECONDS) .writeTimeout(6000, TimeUnit.SECONDS) .readTimeout(6000, TimeUnit.SECONDS) .build(); Request request = new Request.Builder() .url(url + "workflows/run") .post(requestBody) .addHeader("Authorization", "Bearer " + cliamKey) .build(); String res = Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string(); JSONObject jsonObject = JSONObject.parseObject(res); String dataStr = jsonObject.get("data").toString(); JSONObject dataObject = JSONObject.parseObject(dataStr); String outPuts = dataObject.get("outputs").toString(); JSONObject jsonObject1 = JSONObject.parseObject(outPuts); Object retsObj = jsonObject1.get("json"); String rets = retsObj.toString(); List reObject = JSONArray.parseArray(rets, Object.class); Map addMap = new HashMap<>(); Map queryMap = new HashMap<>(); queryMap.put("claim", claim); addMap.put("query", queryMap); addMap.put("answer", retsObj); String addStr = JSONObject.toJSONString(addMap); AddConfessionSessionDTO addConfessionSessionDTO = new AddConfessionSessionDTO(); addConfessionSessionDTO.setConversationId(jsonObject.get("workflow_run_id").toString()); addConfessionSessionDTO.setContent(addStr); String name = DateUtils.dateTimeToStr(new Date()); name = name + "-权利要求解释及有益效果"; addConfessionSessionDTO.setConversationName(name); addConfessionSessionDTO.setType(1); confessionSessionService.addSession(addConfessionSessionDTO); System.out.println(res); return reObject; } public Flux successGetOAHttp(Integer confessionSessionId) { ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId); String fileUrl = fileDownloadUrl + confessionSession.getGuid(); String userId = loginUtils.getId().toString(); OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(600, TimeUnit.SECONDS) .writeTimeout(600, TimeUnit.SECONDS) .readTimeout(600, TimeUnit.SECONDS) .build(); Map map = new HashMap<>(); map.put("fileUrl", fileUrl); OAMessageDTO oaMessageDTO = new OAMessageDTO(); oaMessageDTO.setInputs(map); oaMessageDTO.setResponseMode("streaming"); oaMessageDTO.setUser(userId); oaMessageDTO.setFiles(new ArrayList<>()); String param = new Gson().toJson(oaMessageDTO); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param); Request request = new Request.Builder() .url(url + "workflows/run") .addHeader("Authorization", "Bearer " + OAApiKey) .addHeader(HttpHeaders.CONTENT_TYPE, "application/json") .post(requestBody) .build(); return Flux.create(emitter -> { client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { emitter.error(e); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { emitter.error(new IOException("Unexpected code: " + response)); return; } try (Reader reader = response.body().charStream()) { BufferedReader bufferedReader = new BufferedReader(reader); String line; String prefixToRemove = "data: "; String runId = ""; while ((line = bufferedReader.readLine()) != null) { if (line.isEmpty()) { continue; } if (line.startsWith(prefixToRemove)) { line = line.substring(prefixToRemove.length()); } try { JSONObject jsonObject = JSON.parseObject(line); String workflowRunId = jsonObject.get("workflow_run_id").toString(); String event = jsonObject.get("event").toString(); if (StringUtils.isNotEmpty(workflowRunId)) { if (StringUtils.isEmpty(runId)) { runId = workflowRunId; confessionSessionMapper.updateSingleField(confessionSessionId, "conversation_id", workflowRunId); } } if (event.equals("workflow_finished")) { String data = jsonObject.get("data").toString(); String content = ""; if (StringUtils.isNotEmpty(data)) { JSONObject dataObject = JSON.parseObject(data); String outputs = dataObject.get("outputs").toString(); if (StringUtils.isNotEmpty(outputs)) { JSONObject outputsObject = JSON.parseObject(outputs); String output = outputsObject.get("output").toString(); content = DataUtils.unicodeDecode(output); } } if (StringUtils.isNotEmpty(content)) { JSONObject obj = new JSONObject(); obj.put("answer", content); confessionSessionMapper.updateSingleField(confessionSessionId, "content", obj.toString()); } } } catch (Exception e) { } emitter.next(line); // 将每行数据发送到 Flux } } catch (IOException e) { emitter.error(e); } finally { emitter.complete(); } } }); }); } public Flux successGetOAHttp1(OAParamDTO vo) { Integer confessionSessionId = vo.getConfessionSessionId(); String patentFileUrls = vo.getPatentFileUrls(); String appFileGuid = vo.getAppFileGuid(); String modifyFileGuid = vo.getModifyFileGuid(); ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId); if (ObjectUtils.isEmpty(confessionSession)) { throw new XiaoShiException(ExceptionEnum.BUSINESS_ERROR, "未查询到OA答辩记录"); } String conversationId = confessionSession.getConversationId(); String sessionContent = confessionSession.getContent(); String conversationName = confessionSession.getConversationName(); String fileUrl = fileDownloadUrl + confessionSession.getGuid(); String userId = loginUtils.getId().toString(); OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(600, TimeUnit.SECONDS) .writeTimeout(600, TimeUnit.SECONDS) .readTimeout(600, TimeUnit.SECONDS) .build(); Map map = new HashMap<>(); map.put("fileUrl", fileUrl); map.put("patent_fileUrls", patentFileUrls); map.put("app_file_guid", appFileGuid); map.put("modify_file_guid", modifyFileGuid); map.put("patent_files", new ArrayList<>()); map.put("changeClaim", vo.getChangeClaim()); map.put("claim", vo.getClaim()); map.put("main_claim_reason", vo.getMainClaimReason()); map.put("near_index", vo.getNearIndex()); OAMessageDTO oaMessageDTO = new OAMessageDTO(); oaMessageDTO.setInputs(map); oaMessageDTO.setResponseMode("streaming"); oaMessageDTO.setUser(userId); oaMessageDTO.setQuery("OA答辩"); oaMessageDTO.setConversationId(conversationId); oaMessageDTO.setFiles(new ArrayList<>()); String param = new Gson().toJson(oaMessageDTO); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param); Request request = new Request.Builder() .url(url + "chat-messages") .addHeader("Authorization", "Bearer " + OAApiKey) .addHeader(HttpHeaders.CONTENT_TYPE, "application/json") .post(requestBody) .build(); return Flux.create(emitter -> { client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { emitter.error(e); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { emitter.error(new IOException("Unexpected code: " + response)); return; } try (Reader reader = response.body().charStream()) { BufferedReader bufferedReader = new BufferedReader(reader); String line; String prefixToRemove = "data: "; String runId = conversationId; while ((line = bufferedReader.readLine()) != null) { if (line.isEmpty()) { continue; } if (line.startsWith(prefixToRemove)) { line = line.substring(prefixToRemove.length()); } try { JSONObject jsonObject = JSON.parseObject(line); String sessionConversationId = jsonObject.get("conversation_id").toString(); String event = jsonObject.get("event").toString(); if (StringUtils.isEmpty(runId)) { if (StringUtils.isNotEmpty(sessionConversationId)) { runId = sessionConversationId; confessionSessionMapper.updateSingleField(confessionSessionId, "conversation_id", sessionConversationId); } } if (event.equals("message")) { String data = jsonObject.get("answer").toString(); JSONObject dataObject = null; if (StringUtils.isNotEmpty(data)) { try { dataObject = JSON.parseObject(data); String code = dataObject.get("code").toString(); if (StringUtils.equals(code, "200")) { JSONObject object = dataObject.getJSONObject("data"); generateDoc(conversationName, confessionSessionId, object); } } catch (Exception e) { } } if (ObjectUtils.isNotEmpty(dataObject)) { JSONObject obj; if (StringUtils.isNotEmpty(sessionContent)) { obj = JSON.parseObject(sessionContent); obj.put("data", dataObject); } else { obj = new JSONObject(); obj.put("data", dataObject); } confessionSessionMapper.updateSingleField(confessionSessionId, "content", obj.toString()); } } } catch (Exception e) { } emitter.next(line); // 将每行数据发送到 Flux } } catch (IOException e) { emitter.error(e); } finally { emitter.complete(); } } }); }); } public void generateDoc(String conversationName, Integer confessionSessionId, JSONObject object) { Map map = new HashMap<>(); String reason = object.getString("reason"); String num = object.getString("num"); String claimChange = object.getString("claim_change"); List claimList = new ArrayList<>(); if (StringUtils.isNotEmpty(claimChange)) { claimList = Arrays.asList(claimChange.split("\n")); } JSONArray jsonArray = object.getJSONArray("defense_opinion"); // 创建List集合 List list = new ArrayList<>(); // 遍历JSONArray并添加元素到List if (!CollectionUtils.isEmpty(jsonArray)) { for (Object o : jsonArray) { String str = o.toString(); if (StringUtils.isNotEmpty(str)) { String[] split1 = str.split("\n"); list.addAll(Arrays.asList(split1)); } } } map.put("num", num); map.put("reason", reason); map.put("claim_change", claimList); map.put("defense_opinion", list); ReportTemple reportTemplate = templeService.getById(20); String templateFilePath = fileUtils.getPath(reportTemplate.getTemplatePath()); //更新会话 String name = DateUtils.dateTimeToStr(new Date(), "yyyyMMdd"); String finalName = name + "-" + conversationName + "-陈述意见书"; //生成文档 String fileGuid = null; try { fileGuid = this.generateOADefenseFile(map, templateFilePath, finalName); AssoConfessionSessionFile assoConfessionSessionFile = new AssoConfessionSessionFile(); assoConfessionSessionFile.setGuid(fileGuid); assoConfessionSessionFile.setConfessionSessionId(confessionSessionId); assoConfessionSessionFile.insert(); } catch (Exception e) { throw new XiaoShiException(ExceptionEnum.BUSINESS_ERROR, "加载陈述意见书失败"); } } /** * 生成OA答辩文件 * * @param map * @param templateFilePath * @param name * @return * @throws Exception */ public String generateOADefenseFile(Map map, String templateFilePath, String name) throws Exception { XWPFTemplate xwpfTemplate = this.getHtmlTemplate(map, templateFilePath); String fileName = name + ".docx"; String directoryName = fileUtils.createDirectory(); String outPath = fileUtils.getSavePath(directoryName) + fileName; File file = new File(outPath); // 生成word保存在指定目录 xwpfTemplate.writeToFile(outPath); xwpfTemplate.close(); List ids = fileManagerService.uploadFileGetGuid2(Collections.singletonList(file)); if (CollectionUtils.isEmpty(ids)) { throw new XiaoShiException("保存记录失败"); } return ids.get(0); } private XWPFTemplate getHtmlTemplate(Map map, String filePath) { XWPFTemplate template = null; try { HtmlRenderPolicy htmlRenderPolicy = new HtmlRenderPolicy(); ConfigureBuilder configureBuilder = Configure.builder().useSpringEL(false); configureBuilder.bind("#this", htmlRenderPolicy); Configure configure = configureBuilder.build(); template = XWPFTemplate.compile(filePath, configure).render(map); } catch (Exception e) { e.printStackTrace(); throw new XiaoShiException(ExceptionEnum.BUSINESS_ERROR, "未匹配到模版文件"); } return template; } /** * 调用质检 */ public String WordErrorWorkFlow(DifyChatMessageDTO difyChatMessageDTO) throws IOException { String param = new Gson().toJson(difyChatMessageDTO); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param); OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(600, TimeUnit.SECONDS) .writeTimeout(600, TimeUnit.SECONDS) .readTimeout(600, TimeUnit.SECONDS) .build(); Request request = new Request.Builder() .url(url + "workflows/run") .post(requestBody) .addHeader("Authorization", "Bearer " + checkApiKey) .build(); return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string(); } /** * 获取具体实施方式 */ public String getImplementation(Map map) throws IOException { String param = new Gson().toJson(map); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param); OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .build(); Request request = new Request.Builder() .url(url + "chat-messages") .post(requestBody) .addHeader("Authorization", "Bearer " + checkApiKey) .build(); return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string(); } public String generateClaimExplainRequest(GenerateClaimDTO generateClaimDTO) throws Exception { String claim = generateClaimDTO.getClaim(); String background = generateClaimDTO.getBackground(); DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO(); String userId = "1"; // String userId = loginUtils.getId().toString(); Map map = new HashMap<>(); map.put("claim", claim); map.put("background", background); difyChatMessageDTO.setInputs(map); difyChatMessageDTO.setResponseMode("blocking"); difyChatMessageDTO.setUser(userId); String param = new Gson().toJson(difyChatMessageDTO); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param); OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(6000, TimeUnit.SECONDS) .writeTimeout(6000, TimeUnit.SECONDS) .readTimeout(6000, TimeUnit.SECONDS) .build(); Request request = new Request.Builder() .url(url + "workflows/run") .post(requestBody) .addHeader("Authorization", "Bearer " + cliamKey) .build(); String res = Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string(); return res; } public Flux discoveryResultDialogue(ChatMessageDTO chatMessageDTO) { Integer confessionSessionId = chatMessageDTO.getConfessionSessionId(); String conversationId = chatMessageDTO.getConversationId(); String userId = loginUtils.getId().toString(); String query = chatMessageDTO.getQuery(); Integer type = chatMessageDTO.getType(); if (type == null || query == null || query.trim().equals("")) { throw new XiaoShiException(ExceptionEnum.BUSINESS_CHECK, "请按要求输入参数"); } if (conversationId == null) { conversationId = assoConfessionConversationService.getConversationId(confessionSessionId, type); } String temConversationId = conversationId; String temConversationId3=conversationId; OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(600, TimeUnit.SECONDS) .writeTimeout(600, TimeUnit.SECONDS) .readTimeout(600, TimeUnit.SECONDS) .build(); DifyChatMessageDTO difyChatMessageDTO = new DifyChatMessageDTO(); Map map = new HashMap<>(); String fileContent = ""; ConfessionSession confessionSession = confessionSessionService.getById(confessionSessionId); List guids = assoConfessionSessionFileService.getFileGuid(confessionSessionId, 0); if (guids == null || guids.size() == 0) { throw new XiaoShiException(ExceptionEnum.BUSINESS_ERROR, "数据错误,未检测到交底书"); } fileContent = fileDownloadUrl + guids.get(0); map.put("file_path", fileContent); map.put("data_Result", confessionSession.getResultContent()); map.put("ask_type", type.toString()); difyChatMessageDTO.setInputs(map); difyChatMessageDTO.setConversationId(conversationId); difyChatMessageDTO.setResponseMode("streaming"); difyChatMessageDTO.setUser(userId); difyChatMessageDTO.setQuery(query); difyChatMessageDTO.setFiles(new ArrayList<>()); String param = new Gson().toJson(difyChatMessageDTO); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), param); Request request = this.getChatMessageRequest(requestBody,discoveryResultKey); return Flux.create(emitter -> { client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { emitter.error(e); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { emitter.error(new IOException("Unexpected code: " + response)); return; } try (Reader reader = response.body().charStream()) { BufferedReader bufferedReader = new BufferedReader(reader); String line; String temConversationId2 = temConversationId; String prefixToRemove = "data: "; while ((line = bufferedReader.readLine()) != null) { if (line.isEmpty()) { continue; } if (line.startsWith(prefixToRemove)) { line = line.substring(prefixToRemove.length()); } if (temConversationId2 == null || temConversationId2.isEmpty()) { try { JSONObject jsonObject = JSON.parseObject(line); temConversationId2 = jsonObject.get("conversation_id").toString(); AssoConfessionConversation assoConfessionConversation = new AssoConfessionConversation(); assoConfessionConversation.setConfessionId(confessionSessionId); assoConfessionConversation.setConversationId(temConversationId2); assoConfessionConversation.setType(type); assoConfessionConversation.insert(); } catch (Exception e) { } } emitter.next(line); // 将每行数据发送到 Flux } } catch (IOException e) { emitter.error(e); } finally { emitter.complete(); } } }); }); } }