package qiwu.xfllmdemo.service; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.*; import com.alibaba.fastjson2.JSON; import okhttp3.*; import org.jetbrains.annotations.NotNull; import org.springframework.stereotype.Service; import qiwu.xfllmdemo.pojo.LLMAnswerVO; import qiwu.xfllmdemo.pojo.LLMRequestVO; import qiwu.xfllmdemo.pojo.LLMRequestVO.Payload.Message; import qiwu.xfllmdemo.pojo.LLMResponseVO; import qiwu.xfllmdemo.pojo.LLMResponseVO.Payload.Choices; import qiwu.xfllmdemo.pojo.LLMQueryVO; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; @Service public class LLMService { /** * 所有用户的对话历史列表, */ // TODO 前端 清空历史对话按钮? // static ArrayList userList; static final String appid = "76f57fca"; static final String apiSecret = "ZGFiZDAxMWVkM2I5ZDg0YzJhMzVjMjc0"; static final String apiKey = "cbd03b0dc6862d38b24c5c25ba8b0f02"; static String authURL; /** * 生成鉴权authURL - 时间戳偏差需控制在300s范围内,故每次请求都需要调用 */ static void genAuthURL(int modelVersion) { try { URL url; if (modelVersion == 1) { url = new URL("https://spark-api.xf-yun.com/v1.1/chat"); } else { // modelVersion == 2 url = new URL("https://spark-api.xf-yun.com/v2.1/chat"); } // 时间 SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); format.setTimeZone(TimeZone.getTimeZone("GMT")); String date = format.format(new Date()); // 拼接 String preStr = "host: " + url.getHost() + "\n" + "date: " + date + "\n" + "GET " + url.getPath() + " HTTP/1.1"; // System.err.println(preStr); // SHA256加密 Mac mac = Mac.getInstance("hmacsha256"); SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256"); mac.init(spec); byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8)); // Base64加密 String sha = Base64.getEncoder().encodeToString(hexDigits); // System.err.println(sha); // 拼接 String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha); // 拼接地址 HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().// addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).// addQueryParameter("date", date).// addQueryParameter("host", url.getHost()).// build(); // System.err.println(httpUrl.toString()); authURL = httpUrl.toString().replace("http://", "ws://").replace("https://", "wss://"); } catch (Exception e) { e.printStackTrace(); } } public LLMService() {} /** * 根据对话ID(用户ID)和用户话语发起一次请求 * @param chatHistory 本次请求的对话历史 * @param inVO 本次请求的对话ID(用户ID)和用户话语 * @param modelVersion 要请求的模型版本 1:v1.5,2:v2 * @param addToHistory 请求时是否将本次的用户话语加入到历史对话 * @return 本次请求的对话ID(用户ID)和模型的回复 */ public LLMAnswerVO query(HashMap> chatHistory, LLMQueryVO inVO, int modelVersion, boolean addToHistory) throws Exception { // 1. 根据入参获得本次请求的用户id和对话历史 List thisHistory = chatHistory.get(inVO.userID); if (thisHistory == null) { // outVO = UUID.randomUUID().toString().substring(0, 10); thisHistory = new LinkedList(); chatHistory.put(inVO.userID, thisHistory); } // 2. 构造模型请求JSON,将问题添加到对话历史 LLMRequestVO toReq = new LLMRequestVO(); toReq.header.app_id = appid; toReq.header.uid = inVO.userID.toString().substring(0, 20); if (modelVersion == 1) { toReq.parameter.chat.domain = "general"; } else if (modelVersion == 2) { toReq.parameter.chat.domain = "generalv2"; } else { throw new Exception("modelVersion Error, provided value: " + modelVersion); } toReq.parameter.chat.chat_id = inVO.userID.toString(); // 以UUID区分用户 Message.Text thisTimeWords = new Message.Text("user", inVO.question); // on addToHistory if (addToHistory) { thisHistory.add(thisTimeWords); toReq.payload.message.text = thisHistory; } else { List thisTimeList = new LinkedList<>(thisHistory); thisTimeList.add(thisTimeWords); toReq.payload.message.text = thisTimeList; } String toReqJSON = JSON.toJSONString(toReq); // Test // System.out.println("------\n" + "toReqJSON: \n" + toReqJSON); // System.out.println("authURL: \n" + authURL + "\n------"); // 3. 发起请求,获得回复,将回复添加到对话历史,返回 genAuthURL(modelVersion); // 时间戳偏差需控制在300s范围内,故每次请求都需要调用 LLMSocket llmSocket = new LLMSocket(authURL, toReqJSON); String thisAnswer = llmSocket.executeQuery().toString(); // on addToHistory if (addToHistory) { thisHistory.add(new Message.Text("assistant", thisAnswer)); } return new LLMAnswerVO(inVO.userID, thisAnswer); } } /** * 向模型发起一次请求,返回这次请求对应的回答 */ class LLMSocket extends WebSocketListener { /** * 请求参数JSON */ String requestJSON; /** * 与模型接口服务器建立WebSocket连接用 */ OkHttpClient client; Request request; WebSocket webSocket; /** * 关闭WebSocket线程标志 */ boolean wsCloseFlag = false; /** * 用于拼接一次请求的整个回答串 */ StringBuffer outBuffer = new StringBuffer(); static int threadNum = 0; /** * 建立连接,执行对模型的请求,并同步等待 * @return 含有完整回答串的StringBuffer */ StringBuffer executeQuery() { webSocket = client.newWebSocket(request, this); // 用指定的请求URL建立连接 try { do { Thread.sleep(200); } while (!wsCloseFlag); } catch (InterruptedException e) { e.printStackTrace(); } return outBuffer; } public LLMSocket(String authURL, String requestJSON) { this.requestJSON = requestJSON; this.client = new OkHttpClient.Builder().build(); this.request = new Request.Builder().url(authURL).build(); } /** * 托管WebSocket的线程 */ class MonitorThread extends Thread { @Override public void run() { try { webSocket.send(requestJSON); // System.err.println(requestJson); do { //等待服务端返回完毕后关闭webSocket // System.err.println(wsCloseFlag + "---"); Thread.sleep(200); } while (!wsCloseFlag); webSocket.close(1000, ""); // Test System.out.println("webSocket.close() onMessage() " + threadNum); } catch (Exception e) { e.printStackTrace(); } } } /** * WebSocket连接建立后,启动线程,托管webSocket(等待关闭时机) */ @Override public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) { super.onOpen(webSocket, response); MonitorThread monitorThread = new MonitorThread(); monitorThread.start(); System.out.println("onOpen()"); } /** * 收到一个Response执行一次 */ @Override public synchronized void onMessage(@NotNull WebSocket webSocket, @NotNull String text) { // System.out.println(userId + "用来区分是哪个用户的结果" + text); // Test // System.out.println("onMessage() " + threadNum + ": "); threadNum++; // Test // System.out.println("LLMResponseJSON: " + text); // 1. 解析返回的JSON,若出错处理 // 使用JSON.parseObject()时注意,传入的class中每个属性的类型必须与JSON字符串中严格相同,否则方法会阻塞且不会有任何异常抛出 LLMResponseVO responseVO = JSON.parseObject(text, LLMResponseVO.class); if (responseVO.header.code != 0) { System.out.println("发生错误,错误码为:" + responseVO.header.code); System.out.println("本次请求的sid为:" + responseVO.header.sid); webSocket.close(1000, ""); return; } // Test // System.out.println("responseVO: " + responseVO); // 2. 提取其中的回答串 List textList = responseVO.payload.choices.text; // Test // System.out.println("textList.size(): " + textList.size()); // 3. 拼接形成完整回答串 每个Response的test里面只有一个元素 for (Choices.Text temp : textList) { // System.out.println("temp.content: " + temp.content); outBuffer.append(temp.content); } if (responseVO.header.status == 2) { // 输出已结束,可以关闭连接,释放资源 wsCloseFlag = true; } } @Override public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, Response response) { super.onFailure(webSocket, t, response); try { if (null != response) { int code = response.code(); System.out.println("onFailure code:" + code); System.out.println("onFailure body:" + response.body().string()); if (101 != code) { System.out.println("connection failed"); System.exit(0); } } } catch (IOException e) { e.printStackTrace(); } } }