123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779 |
- 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.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.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.ConfessionSessionService;
- import cn.cslg.pas.service.dify.DifySessionService;
- import cn.cslg.pas.service.dify.GenerateInstructionService;
- 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;
- 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;
- /**
- * 调用文件系统删除文件接口
- */
- 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();
- String path = "messages?conversation_id=" + difyChatMessageDTO.getConversationId() + "&user=" + difyChatMessageDTO.getUser() + "&limit=" + difyChatMessageDTO.getLimit();
- if (difyChatMessageDTO.getFirstId() != null) {
- path += "&first_id=" + difyChatMessageDTO.getFirstId();
- }
- Request request = new Request.Builder()
- .url(url + path)
- .get()
- .addHeader("Authorization", "Bearer " + apiKey)
- .build();
- return Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string();
- }
- public Flux<String> 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<String, Object> 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);
- 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) {
- Request request = new Request.Builder()
- .url(url + "chat-messages")
- .addHeader("Authorization", "Bearer " + apiKey).addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
- .post(requestBody)
- .build();
- return request;
- }
- public JSONObject stopMessage(String taskId) 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);
- Request request = new Request.Builder()
- .url(url + "chat-messages/" + taskId + "/stop")
- .addHeader("Authorization", "Bearer " + apiKey).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<String, Object> 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<String, Object> 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);
- 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<String, Object> 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<Object> 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<String, Object> 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<Object> reObject = JSONArray.parseArray(rets, Object.class);
- Map<String, Object> addMap = new HashMap<>();
- Map<String, Object> 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<String> 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<String, Object> 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<String> successGetOAHttp1(OAParamDTO vo) {
- Integer confessionSessionId = vo.getConfessionSessionId();
- String patentFileUrls = vo.getPatentFileUrls();
- 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<String, Object> map = new HashMap<>();
- map.put("fileUrl", fileUrl);
- map.put("patent_fileUrls",patentFileUrls);
- 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<String, Object> map = new HashMap<>();
- String reason = object.getString("reason");
- String num = object.getString("num");
- String claimChange = object.getString("claim_change");
- List<String> claimList = new ArrayList<>();
- if (StringUtils.isNotEmpty(claimChange)) {
- claimList = Arrays.asList(claimChange.split("\n"));
- }
- JSONArray jsonArray = object.getJSONArray("defense_opinion");
- // 创建List集合
- List<String> 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<String, Object> 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<String> ids = fileManagerService.uploadFileGetGuid2(Collections.singletonList(file));
- if (CollectionUtils.isEmpty(ids)) {
- throw new XiaoShiException("保存记录失败");
- }
- return ids.get(0);
- }
- private XWPFTemplate getHtmlTemplate(Map<String, Object> map, String filePath) {
- XWPFTemplate template = null;
- try {
- HtmlRenderPolicy htmlRenderPolicy = new HtmlRenderPolicy();
- ConfigureBuilder configureBuilder = Configure.builder();
- 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<String, Object> 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<String, Object> 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;
- }
- }
|