Files
guoxue-java/src/main/java/com/gxwebsoft/law/controller/AiController.java
T
2026-03-25 15:56:42 +08:00

228 lines
12 KiB
Java

package com.gxwebsoft.law.controller;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
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 io.swagger.annotations.Api;
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.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@Api(tags = "AI")
@RestController
@RequestMapping("/api/chat")
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, 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("https://ai-console.gxshucheng.com/ai-console-api/run/v1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setDoOutput(true);
connection.setConnectTimeout(600000);
connection.setReadTimeout(600000);
// 写入请求体
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(LocalDateTimeUtil.format(LocalDateTimeUtil.now(), "yyyy-MM-dd HH:mm:ss") + " Received chunk: " + line); // 打印接收到的每一部分数据
// 这里可以对每一部分数据进行处理,例如解析或发送给前端
if (!line.isEmpty()) {
String[] dataList = line.split("data: ");
if (dataList.length == 2) {
// System.out.println(dataList[1]);
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 (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", conversation_id);
answerData.put("taskIdOrigin", task_id);
webSocketServer.sendMessage(getLoginUserId().toString(), JSONUtil.toJSONString(answerData));
}
System.out.println("answer: " + answer);
responseStr.append(answer);
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", 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));
}
}
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
for (StackTraceElement stackTraceElement : e.getStackTrace()) {
System.out.println(stackTraceElement);
}
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("出错了,请晚点再来提问吧~");
}
// 返回成功响应
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, 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";
}
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))
.execute().body();
System.out.println("stop res:" + res);
return success();
}
}