20260325稳定版
This commit is contained in:
@@ -1,31 +1,32 @@
|
||||
package com.gxwebsoft.law.controller;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.date.LocalDateTimeUtil;
|
||||
import cn.hutool.http.HttpRequest;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.baomidou.mybatisplus.core.toolkit.sql.StringEscape;
|
||||
import com.gxwebsoft.common.core.utils.JSONUtil;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.gx.entity.GxChatHistory;
|
||||
import com.gxwebsoft.gx.entity.GxChatList;
|
||||
import com.gxwebsoft.gx.entity.GxRole;
|
||||
import com.gxwebsoft.gx.service.GxChatHistoryService;
|
||||
import com.gxwebsoft.gx.service.GxChatListService;
|
||||
import com.gxwebsoft.gx.service.GxRoleService;
|
||||
import com.gxwebsoft.law.config.WebSocketServer;
|
||||
import com.gxwebsoft.law.entity.ChatMessage;
|
||||
import com.gxwebsoft.law.entity.ChatResponse;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -35,47 +36,87 @@ import java.util.Map;
|
||||
public class AiController extends BaseController {
|
||||
@Resource
|
||||
private WebSocketServer webSocketServer;
|
||||
@Resource
|
||||
private GxChatHistoryService gxChatHistoryService;
|
||||
@Resource
|
||||
private GxChatListService gxChatListService;
|
||||
@Resource
|
||||
private GxRoleService gxRoleService;
|
||||
|
||||
@PostMapping("/message")
|
||||
public ApiResult<?> message(@RequestBody ChatMessage message) throws IOException {
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("query", message.getQuery());
|
||||
params.put("user", getLoginUserId());
|
||||
params.put("response_mode", "streaming");
|
||||
String token = "Bearer app-UxV82WXIRrScpf53exkJ7dIw";
|
||||
if (message.getType() != null) {
|
||||
token = "Bearer app-7AFseF5UTEJpZGkW93S0wybh";
|
||||
}
|
||||
if (message.getInputs() != null) {
|
||||
Map<String, Object> inputs = new HashMap<>();
|
||||
inputs.put("request_type", message.getRequestType());
|
||||
inputs.put("request_json", message.getInputs());
|
||||
params.put("inputs", inputs);
|
||||
} else {
|
||||
params.put("inputs", new HashMap<>());
|
||||
}
|
||||
Map<String, String> paramsJsonStr = new HashMap<>();
|
||||
GxRole gxRole = gxRoleService.getByRoleName(message.getRoleName());
|
||||
// Map<String, String> inputs = new HashMap<>();
|
||||
paramsJsonStr.put("query", message.getQuery());
|
||||
paramsJsonStr.put("role_name", message.getRoleName());
|
||||
paramsJsonStr.put("role_desc", gxRole.getPrompt() != null ? gxRole.getPrompt() : gxRole.getRoleDesc());
|
||||
String userInfo = "";
|
||||
User user = getLoginUser();
|
||||
if (user.getRealName() != null && !user.getRealName().isEmpty())
|
||||
userInfo = "姓名:" + user.getRealName();
|
||||
if (user.getSex() != null && !user.getSex().isEmpty())
|
||||
userInfo += ",性别:" + (user.getSex().equals("0") ? "男" : "女");
|
||||
if (user.getBirthday() != null)
|
||||
userInfo += ",出生日期:" + user.getBirthday();
|
||||
if (user.getBirthTime() != null)
|
||||
userInfo += ",生辰:" + user.getBirthTime();
|
||||
if (user.getBirthAddress() != null && !user.getBirthAddress().isEmpty())
|
||||
userInfo += ",出生地:" + user.getBirthAddress();
|
||||
paramsJsonStr.put("user_info", userInfo);
|
||||
|
||||
Map<String, String> formData = new HashMap<>();
|
||||
formData.put("user", getLoginUserId().toString());
|
||||
if (message.getConversationId() != null) paramsJsonStr.put("conversation_id", message.getConversationId());
|
||||
// formData.put("inputs", JSONUtil.toJSONString(inputs));
|
||||
formData.put("responseMode", "streaming");
|
||||
formData.put("paramsJsonStr", JSONUtil.toJSONString(paramsJsonStr));
|
||||
formData.put("authCode", "0e3909ca-b9b0-4c61-b555-a98523b68d51");
|
||||
// 使用 Java 自带的 HttpURLConnection 发送流式请求
|
||||
System.out.println("paramsJsonStr: " + JSONUtil.toJSONString(formData));
|
||||
try {
|
||||
URL url = new URL("http://workflow.gxshucheng.com:8010/v1/chat-messages");
|
||||
URL url = new URL("https://ai-console.gxshucheng.com/ai-console-api/run/v1");
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("Authorization", token);
|
||||
connection.setRequestProperty("Content-Type", "application/json");
|
||||
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
|
||||
connection.setDoOutput(true);
|
||||
connection.setConnectTimeout(600000);
|
||||
connection.setReadTimeout(600000);
|
||||
|
||||
// 写入请求体
|
||||
try (OutputStream os = connection.getOutputStream()) {
|
||||
os.write(JSONUtil.toJSONString(params).getBytes(StandardCharsets.UTF_8));
|
||||
try (OutputStream os = connection.getOutputStream();
|
||||
PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
|
||||
for (Map.Entry<String, String> entry : formData.entrySet()) {
|
||||
writeFormField(writer, entry.getKey(), entry.getValue());
|
||||
}
|
||||
// 添加文件上传部分(可选)
|
||||
// writeFilePart(writer, "file", "test.txt", "text/plain", "This is the file content.");
|
||||
writer.append("--").append(boundary).append("--").append("\r\n");
|
||||
writer.flush();
|
||||
}
|
||||
|
||||
StringBuilder responseStr = new StringBuilder();
|
||||
// 读取响应流
|
||||
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
Integer chatId = message.getChatId();
|
||||
if (chatId == null || chatId == 0) {
|
||||
GxChatList gxChatList = new GxChatList();
|
||||
gxChatList.setUserId(getLoginUserId());
|
||||
gxChatListService.save(gxChatList);
|
||||
chatId = gxChatList.getId();
|
||||
}
|
||||
|
||||
GxChatHistory gxChatHistory = new GxChatHistory();
|
||||
gxChatHistory.setUserId(getLoginUserId());
|
||||
gxChatHistory.setContent(message.getQuery());
|
||||
gxChatHistory.setChatId(chatId);
|
||||
|
||||
StringBuilder reply = new StringBuilder();
|
||||
int flag = 0;
|
||||
int saveFlag = 0;
|
||||
while ((line = br.readLine()) != null) {
|
||||
System.out.println("Received chunk: " + line); // 打印接收到的每一部分数据
|
||||
System.out.println(LocalDateTimeUtil.format(LocalDateTimeUtil.now(), "yyyy-MM-dd HH:mm:ss") + " Received chunk: " + line); // 打印接收到的每一部分数据
|
||||
// 这里可以对每一部分数据进行处理,例如解析或发送给前端
|
||||
if (!line.isEmpty()) {
|
||||
String[] dataList = line.split("data: ");
|
||||
@@ -84,21 +125,54 @@ public class AiController extends BaseController {
|
||||
Map data = JSONUtil.parseObject(dataList[1], Map.class);
|
||||
if (data.get("event") != null && data.get("event").equals("message")) {
|
||||
String answer = (String) data.get("answer");
|
||||
String conversation_id = (String) data.get("conversation_id");
|
||||
String task_id = (String) data.get("task_id");
|
||||
if (answer != null && !answer.isEmpty()) {
|
||||
if (flag == 0) {
|
||||
flag = 1;
|
||||
gxChatListService.updateConversationId(chatId, conversation_id);
|
||||
}
|
||||
if (answer != null && !answer.isEmpty() && !answer.contains("搜索中")) {
|
||||
HashMap<String, String> answerData = new HashMap<>();
|
||||
answerData.put("answer", answer);
|
||||
answerData.put("taskId", task_id);
|
||||
webSocketServer.sendMessage(message.getUser(), JSONUtil.toJSONString(answerData));
|
||||
answerData.put("taskId", conversation_id);
|
||||
answerData.put("taskIdOrigin", task_id);
|
||||
webSocketServer.sendMessage(getLoginUserId().toString(), JSONUtil.toJSONString(answerData));
|
||||
}
|
||||
System.out.println(answer);
|
||||
System.out.println("answer: " + answer);
|
||||
responseStr.append(answer);
|
||||
}else if (data.get("event") != null && data.get("event").equals("message_end")) {
|
||||
reply.append(answer);
|
||||
} else if (data.get("event") != null && data.get("event").equals("agent_log")) {
|
||||
String answer = (String) data.get("answer");
|
||||
String conversation_id = (String) data.get("conversation_id");
|
||||
String task_id = (String) data.get("task_id");
|
||||
HashMap<String, String> answerData = new HashMap<>();
|
||||
answerData.put("answer", answer);
|
||||
answerData.put("loading", "true");
|
||||
answerData.put("taskId", conversation_id);
|
||||
answerData.put("taskIdOrigin", task_id);
|
||||
webSocketServer.sendMessage(getLoginUserId().toString(), JSONUtil.toJSONString(answerData));
|
||||
} else if (data.get("event") != null && data.get("event").equals("workflow_finished")) {
|
||||
String conversation_id = (String) data.get("conversation_id");
|
||||
String task_id = (String) data.get("task_id");
|
||||
|
||||
HashMap<String, String> answerData = new HashMap<>();
|
||||
answerData.put("answer", "__END__");
|
||||
answerData.put("taskId", task_id);
|
||||
webSocketServer.sendMessage(message.getUser(), JSONUtil.toJSONString(answerData));
|
||||
answerData.put("taskId", conversation_id);
|
||||
answerData.put("taskIdOrigin", task_id);
|
||||
if (saveFlag == 0) {
|
||||
saveFlag = 1;
|
||||
// gxChatHistory.setReply(reply.toString());
|
||||
// gxChatHistoryService.save(gxChatHistory);
|
||||
webSocketServer.sendMessage(getLoginUserId().toString(), JSONUtil.toJSONString(answerData));
|
||||
}
|
||||
}
|
||||
}else {
|
||||
Map data = JSONUtil.parseObject(dataList[0], Map.class);
|
||||
if (data.get("status") != null && data.get("status").equals(500)) {
|
||||
HashMap<String, String> answerData = new HashMap<>();
|
||||
answerData.put("answer", "出错了,请晚点再来提问吧~");
|
||||
answerData.put("taskId", "0");
|
||||
webSocketServer.sendMessage(getLoginUserId().toString(), JSONUtil.toJSONString(answerData));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -109,7 +183,11 @@ public class AiController extends BaseController {
|
||||
for (StackTraceElement stackTraceElement : e.getStackTrace()) {
|
||||
System.out.println(stackTraceElement);
|
||||
}
|
||||
webSocketServer.sendMessage(message.getUser(), "出错了,请晚点再来提问吧~");
|
||||
HashMap<String, String> answerData = new HashMap<>();
|
||||
answerData.put("answer", "出错了,请晚点再来提问吧~");
|
||||
answerData.put("taskId", "0");
|
||||
webSocketServer.sendMessage(getLoginUserId().toString(), JSONUtil.toJSONString(answerData));
|
||||
// webSocketServer.sendMessage(getLoginUserId().toString(), "出错了,请晚点再来提问吧~");
|
||||
return fail("出错了,请晚点再来提问吧~");
|
||||
}
|
||||
|
||||
@@ -117,17 +195,29 @@ public class AiController extends BaseController {
|
||||
return success("Stream processing completed");
|
||||
}
|
||||
|
||||
private static final String boundary = "---" + System.currentTimeMillis() + "---";
|
||||
|
||||
private static void writeFormField(PrintWriter writer, String fieldName, String value) {
|
||||
writer.append("--").append(boundary).append("\r\n");
|
||||
writer.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"\r\n");
|
||||
writer.append("\r\n");
|
||||
writer.append(value).append("\r\n");
|
||||
}
|
||||
|
||||
@PostMapping("/messageStop")
|
||||
public ApiResult<?> stop(@RequestBody Map<String, Object> data) {
|
||||
if (data.get("taskId") == null) return success();
|
||||
String taskId = data.get("taskId").toString();
|
||||
Map<String, Integer> postData = new HashMap<>();
|
||||
Map<String, Object> postData = new HashMap<>();
|
||||
postData.put("user", getLoginUserId());
|
||||
postData.put("taskId", taskId);
|
||||
postData.put("authCode", "0e3909ca-b9b0-4c61-b555-a98523b68d51");
|
||||
String token = "Bearer app-UxV82WXIRrScpf53exkJ7dIw";
|
||||
if (data.get("type") != null) {
|
||||
token = "Bearer app-7AFseF5UTEJpZGkW93S0wybh";
|
||||
}
|
||||
String res = HttpRequest.post("http://workflow.gxshucheng.com:8010/v1/chat-messages/" + taskId + "/stop")
|
||||
System.out.println("stop payload:" + postData);
|
||||
String res = HttpRequest.post("https://ai-console.gxshucheng.com/ai-console-api/stop/v1")
|
||||
.header("Authorization", token)
|
||||
.header("Content-Type", "application/json")
|
||||
.body(JSONObject.toJSONString(postData))
|
||||
|
||||
Reference in New Issue
Block a user