321 lines
16 KiB
Java
321 lines
16 KiB
Java
package com.peanut.common.utils;
|
||
|
||
import com.alibaba.fastjson.JSONObject;
|
||
import com.peanut.config.WebSocket;
|
||
import com.peanut.modules.common.entity.AiChatContent;
|
||
import com.peanut.modules.common.entity.PrecisionMedicineGene;
|
||
import com.peanut.modules.common.service.AiChatContentService;
|
||
import org.apache.commons.lang.StringUtils;
|
||
import org.apache.http.Consts;
|
||
import org.apache.http.HttpEntity;
|
||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||
import org.apache.http.client.methods.HttpGet;
|
||
import org.apache.http.client.methods.HttpPost;
|
||
import org.apache.http.entity.StringEntity;
|
||
import org.apache.http.impl.client.CloseableHttpClient;
|
||
import org.apache.http.impl.client.HttpClients;
|
||
import org.apache.http.util.EntityUtils;
|
||
import org.springframework.beans.factory.annotation.Autowired;
|
||
import org.springframework.beans.factory.annotation.Value;
|
||
import org.springframework.stereotype.Component;
|
||
import org.springframework.transaction.interceptor.TransactionAspectSupport;
|
||
import org.springframework.web.reactive.function.client.WebClient;
|
||
import java.util.ArrayList;
|
||
import java.util.HashMap;
|
||
import java.util.List;
|
||
import java.util.Map;
|
||
|
||
@Component
|
||
public class RagFlowApiUtil {
|
||
|
||
@Value("${ragflow.url}")
|
||
private String url;
|
||
@Value("${ragflow.authorization}")
|
||
private String authorization;
|
||
@Autowired
|
||
private AiChatContentService aiChatContentService;
|
||
@Autowired
|
||
private WebSocket webSocket;
|
||
|
||
//聊天助手列表
|
||
public List<Map<String,Object>> getChatAssistants(String chatId) throws Exception{
|
||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||
HttpGet get = new HttpGet(url+"/api/v1/chats?id="+chatId);
|
||
get.setHeader("Authorization", authorization);
|
||
get.setHeader("Content-Type", "application/json;chartset=utf-8");
|
||
CloseableHttpResponse response = httpClient.execute(get);
|
||
int statusCode = response.getStatusLine().getStatusCode();
|
||
if (statusCode >= 400) {
|
||
throw new RuntimeException("API调用失败,状态码:" + statusCode);
|
||
}
|
||
HttpEntity responseEntity = response.getEntity();
|
||
String responseString = EntityUtils.toString(responseEntity, Consts.UTF_8);
|
||
JSONObject jsonObject = JSONObject.parseObject(responseString);
|
||
List<Map<String,Object>> list = new ArrayList();
|
||
if ("0".equals(jsonObject.get("code").toString())){
|
||
List l = jsonObject.getJSONArray("data");
|
||
for (Object o : l) {
|
||
Map<String,Object> map = new HashMap<>();
|
||
Map<String,Object> m = (Map<String,Object>)o;
|
||
map.put("id",m.get("id"));
|
||
map.put("name",m.get("name"));
|
||
list.add(map);
|
||
}
|
||
}
|
||
return list;
|
||
}
|
||
|
||
//聊天助手下对话列表
|
||
public List<Map<String,Object>> getChats(Map<String,Object> params) throws Exception{
|
||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||
String chatId = params.get("chatId").toString();
|
||
List<Map<String,Object>> list = new ArrayList();
|
||
String page = params.get("page").toString();
|
||
String pageSize = params.get("pageSize").toString();
|
||
String sessionId = params.get("sessionId").toString();
|
||
HttpGet get = new HttpGet(url+"/api/v1/chats/"+chatId+"/sessions?" +
|
||
"page="+page+"&page_size="+pageSize+"&id="+sessionId+"&user_id="+ShiroUtils.getUId());
|
||
get.setHeader("Authorization", authorization);
|
||
get.setHeader("Content-Type", "application/json;chartset=utf-8");
|
||
CloseableHttpResponse response = httpClient.execute(get);
|
||
int statusCode = response.getStatusLine().getStatusCode();
|
||
if (statusCode >= 400) {
|
||
throw new RuntimeException("API调用失败,状态码:" + statusCode);
|
||
}
|
||
HttpEntity responseEntity = response.getEntity();
|
||
String responseString = EntityUtils.toString(responseEntity, Consts.UTF_8);
|
||
JSONObject jsonObject = JSONObject.parseObject(responseString);
|
||
if ("0".equals(jsonObject.get("code").toString())){
|
||
List l = jsonObject.getJSONArray("data");
|
||
list.addAll(l);
|
||
}
|
||
return list;
|
||
}
|
||
|
||
//创建会话
|
||
public String createChat(Map<String,Object> params) throws Exception{
|
||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||
String chatId = params.get("chatId").toString();
|
||
Map<String, Object> entity = new HashMap<>();
|
||
entity.put("name", params.get("name").toString());
|
||
entity.put("user_id", ShiroUtils.getUId());
|
||
HttpPost post = new HttpPost(url+"/api/v1/chats/"+chatId+"/sessions");
|
||
post.setHeader("Authorization", authorization);
|
||
post.setHeader("Content-Type", "application/json;chartset=utf-8");
|
||
post.setEntity(new StringEntity(JSONObject.toJSONString(entity),"utf-8"));
|
||
CloseableHttpResponse response = httpClient.execute(post);
|
||
int statusCode = response.getStatusLine().getStatusCode();
|
||
if (statusCode >= 400) {
|
||
throw new RuntimeException("API调用失败,状态码:" + statusCode);
|
||
}
|
||
HttpEntity responseEntity = response.getEntity();
|
||
String responseString = EntityUtils.toString(responseEntity, Consts.UTF_8);
|
||
JSONObject jsonObject = JSONObject.parseObject(responseString);
|
||
if ("0".equals(jsonObject.get("code").toString())){
|
||
return ((JSONObject)jsonObject.get("data")).get("id").toString();
|
||
}
|
||
return "";
|
||
}
|
||
|
||
//与助手聊天
|
||
public R chatToAssistant(Map<String,Object> params) throws Exception{
|
||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||
String chatId = params.get("chatId").toString();
|
||
Map<String, Object> entity = new HashMap<>();
|
||
entity.put("question", params.get("question").toString());
|
||
entity.put("session_id", params.get("sessionId").toString());
|
||
entity.put("user_id", ShiroUtils.getUId());
|
||
HttpPost post = new HttpPost(url+"/api/v1/chats/"+chatId+"/completions");
|
||
post.setHeader("Authorization", authorization);
|
||
post.setHeader("Content-Type", "application/json;chartset=utf-8");
|
||
post.setEntity(new StringEntity(JSONObject.toJSONString(entity),"utf-8"));
|
||
CloseableHttpResponse response = httpClient.execute(post);
|
||
int statusCode = response.getStatusLine().getStatusCode();
|
||
if (statusCode >= 400) {
|
||
throw new RuntimeException("API调用失败,状态码:" + statusCode);
|
||
}
|
||
HttpEntity responseEntity = response.getEntity();
|
||
String responseString = EntityUtils.toString(responseEntity, Consts.UTF_8);
|
||
return R.ok().put("res",responseString);
|
||
}
|
||
|
||
//与助手聊天流式
|
||
public void chatToAssistantStream(String chatId,String chatName,String sessionId,String sessionName,String question,String patientName,Map<String,Object> geneInfo) {
|
||
try {
|
||
String allQuestion = question;
|
||
if (geneInfo!=null){
|
||
String geneStr = "";
|
||
String geneInfoStr = "";
|
||
String prescriptionStr = "";
|
||
List<PrecisionMedicineGene> geneList = (List<PrecisionMedicineGene>) geneInfo.get("geneList");
|
||
for (PrecisionMedicineGene gene:geneList){
|
||
// geneStr += gene.getName()+"("+gene.getNamecn()+")基因阳性。";
|
||
if (StringUtils.isEmpty(geneInfoStr)){
|
||
geneInfoStr = "已知"+gene.getDescription()+"匹配药材:"+gene.getTcmName()+"。";
|
||
}else {
|
||
geneInfoStr += gene.getDescription()+"匹配药材:"+gene.getTcmName()+"。";
|
||
}
|
||
}
|
||
allQuestion+=geneStr+geneInfoStr;
|
||
List<Map<String,Object>> prescriptionList = (List<Map<String, Object>>) geneInfo.get("prescriptionList");
|
||
if (prescriptionList.size()>0){
|
||
for (Map<String, Object> prescription:prescriptionList) {
|
||
prescriptionStr+="基因匹配方剂:"+prescription.get("name")+",方剂组成:"+prescription.get("compose")+"出处:"+prescription.get("source");
|
||
}
|
||
allQuestion+=prescriptionStr;
|
||
}
|
||
}
|
||
String userId = ShiroUtils.getUId()+"";
|
||
Map<String, Object> entity = new HashMap<>();
|
||
entity.put("question", question);
|
||
entity.put("stream", true);
|
||
entity.put("session_id", sessionId);
|
||
entity.put("user_id", userId);
|
||
AiChatContent content = new AiChatContent();
|
||
content.setUserId(Integer.parseInt(userId));
|
||
content.setChatAssistantId(chatId);
|
||
content.setChatAssistantName(chatName);
|
||
content.setChatId(sessionId);
|
||
content.setChatName(sessionName);
|
||
content.setPatientName(patientName);
|
||
content.setType(0);
|
||
content.setContent(question);
|
||
aiChatContentService.save(content);
|
||
List<String> list = new ArrayList<>();
|
||
WebClient.create().post()
|
||
.uri(url+"/api/v1/chats/"+chatId+"/completions")
|
||
.header("Authorization", authorization)
|
||
.header("Content-Type", "application/json;chartset=utf-8")
|
||
.bodyValue(JSONObject.toJSONString(entity))
|
||
.retrieve()
|
||
.bodyToFlux(String.class)
|
||
.doOnNext(data -> {
|
||
JSONObject jsonObject = JSONObject.parseObject(data);
|
||
if ("0".equals(jsonObject.get("code").toString())){
|
||
if (!"true".equals(jsonObject.get("data").toString())){
|
||
webSocket.sendMessage(data);
|
||
list.add(((JSONObject)jsonObject.get("data")).get("answer").toString());
|
||
}
|
||
}
|
||
})
|
||
.doFinally(data -> {
|
||
webSocket.sendMessage("{\"code\":0,\"data\":true}");
|
||
AiChatContent answer = new AiChatContent();
|
||
answer.setUserId(Integer.parseInt(userId));
|
||
answer.setChatAssistantId(chatId);
|
||
answer.setChatAssistantName(chatName);
|
||
answer.setChatId(sessionId);
|
||
answer.setChatName(sessionName);
|
||
answer.setPatientName(patientName);
|
||
answer.setType(1);
|
||
answer.setContent(list.get(list.size()-1));
|
||
aiChatContentService.save(answer);
|
||
}).subscribe();
|
||
}catch (Exception e){
|
||
e.printStackTrace();
|
||
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
|
||
}
|
||
}
|
||
|
||
//代理列表
|
||
public List<Map<String,Object>> getChatAgents(String agentId) throws Exception{
|
||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||
HttpGet get = new HttpGet(url+"/api/v1/agents?id="+agentId);
|
||
get.setHeader("Authorization", authorization);
|
||
get.setHeader("Content-Type", "application/json;chartset=utf-8");
|
||
CloseableHttpResponse response = httpClient.execute(get);
|
||
int statusCode = response.getStatusLine().getStatusCode();
|
||
if (statusCode >= 400) {
|
||
throw new RuntimeException("API调用失败,状态码:" + statusCode);
|
||
}
|
||
HttpEntity responseEntity = response.getEntity();
|
||
String responseString = EntityUtils.toString(responseEntity, Consts.UTF_8);
|
||
JSONObject jsonObject = JSONObject.parseObject(responseString);
|
||
List<Map<String,Object>> list = new ArrayList();
|
||
if ("0".equals(jsonObject.get("code").toString())){
|
||
List l = jsonObject.getJSONArray("data");
|
||
for (Object o : l) {
|
||
Map<String,Object> map = new HashMap<>();
|
||
Map<String,Object> m = (Map<String,Object>)o;
|
||
map.put("id",m.get("id"));
|
||
map.put("name",m.get("title"));
|
||
list.add(map);
|
||
}
|
||
}
|
||
return list;
|
||
}
|
||
|
||
//新建代理对话
|
||
public String createAgentChat(Map<String,Object> params) throws Exception{
|
||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||
String agentId = params.get("agentId").toString();
|
||
HttpPost post = new HttpPost(url+"/api/v1/agents/"+agentId+"/sessions?user_id="+ShiroUtils.getUId());
|
||
post.setHeader("Authorization", authorization);
|
||
post.setHeader("Content-Type", "application/json;chartset=utf-8");
|
||
CloseableHttpResponse response = httpClient.execute(post);
|
||
int statusCode = response.getStatusLine().getStatusCode();
|
||
if (statusCode >= 400) {
|
||
throw new RuntimeException("API调用失败,状态码:" + statusCode);
|
||
}
|
||
HttpEntity responseEntity = response.getEntity();
|
||
String responseString = EntityUtils.toString(responseEntity, Consts.UTF_8);
|
||
JSONObject jsonObject = JSONObject.parseObject(responseString);
|
||
if ("0".equals(jsonObject.get("code").toString())){
|
||
return ((JSONObject)jsonObject.get("data")).get("id").toString();
|
||
}else {
|
||
return jsonObject.get("message").toString();
|
||
}
|
||
}
|
||
|
||
//与代理聊天流式
|
||
public void chatToAgentStream(String agentId,String sessionId,String question) {
|
||
try {
|
||
String userId = ShiroUtils.getUId()+"";
|
||
Map<String, Object> entity = new HashMap<>();
|
||
entity.put("question", question);
|
||
entity.put("stream", true);
|
||
entity.put("session_id", sessionId);
|
||
entity.put("user_id", userId);
|
||
AiChatContent content = new AiChatContent();
|
||
content.setUserId(Integer.parseInt(userId));
|
||
content.setChatAssistantId(agentId);
|
||
content.setChatId(sessionId);
|
||
content.setType(0);
|
||
content.setContent(question);
|
||
aiChatContentService.save(content);
|
||
List<String> list = new ArrayList<>();
|
||
WebClient.create().post()
|
||
.uri(url+"/api/v1/agents/"+agentId+"/completions")
|
||
.header("Authorization", authorization)
|
||
.header("Content-Type", "application/json;chartset=utf-8")
|
||
.bodyValue(JSONObject.toJSONString(entity))
|
||
.retrieve()
|
||
.bodyToFlux(String.class)
|
||
.doOnNext(data -> {
|
||
JSONObject jsonObject = JSONObject.parseObject(data);
|
||
if ("0".equals(jsonObject.get("code").toString())){
|
||
if (!"true".equals(jsonObject.get("data").toString())){
|
||
webSocket.sendMessage(data);
|
||
list.add(((JSONObject)jsonObject.get("data")).get("answer").toString());
|
||
}
|
||
}
|
||
})
|
||
.doFinally(data -> {
|
||
webSocket.sendMessage("{\"code\":0,\"data\":true}");
|
||
AiChatContent answer = new AiChatContent();
|
||
answer.setUserId(Integer.parseInt(userId));
|
||
answer.setChatAssistantId(agentId);
|
||
answer.setChatId(sessionId);
|
||
answer.setType(1);
|
||
answer.setContent(list.get(list.size()-1));
|
||
aiChatContentService.save(answer);
|
||
}).subscribe();
|
||
}catch (Exception e){
|
||
e.printStackTrace();
|
||
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
|
||
}
|
||
}
|
||
|
||
|
||
}
|