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 com.google.gson.Gson; import okhttp3.*; import org.jetbrains.annotations.NotNull; import org.springframework.stereotype.Service; 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.LLMServiceRequestVO; import qiwu.xfllmdemo.pojo.LLMServiceResponseVO; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; /** * 向模型发起一次请求,返回这次请求对应的回答 */ @Service public class LLMService { /** * 所有用户的对话历史列表, */ static HashMap> chatHistory; // static ArrayList userList; static final String hostUrl = "https://spark-api.xf-yun.com/v1.1/chat"; //ws(s)://spark-api.xf-yun.com/v2.1/chat static final String appid = "76f57fca"; static final String apiSecret = "ZGFiZDAxMWVkM2I5ZDg0YzJhMzVjMjc0"; static final String apiKey = "cbd03b0dc6862d38b24c5c25ba8b0f02"; static String authURL; static { // 生成鉴权authURL - 代码块先于构造方法执行 try { URL url = new URL(hostUrl); // 时间 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 static final Gson gson = new Gson(); /** * 用于拼接整个回答串 */ StringBuffer answerBuffer = new StringBuffer(); public LLMService() { chatHistory = new HashMap<>(); } public LLMServiceResponseVO query(LLMServiceRequestVO inVO) { // TODO 1. 根据入参获得用户id和对话历史 LinkedList thisHistory = chatHistory.get(inVO.userID); if (thisHistory == null) { // outVO = UUID.randomUUID().toString().substring(0, 10); thisHistory = new LinkedList(); chatHistory.put(inVO.userID, thisHistory); } // TODO 2. 构造模型请求JSON,将问题添加到对话历史 LLMRequestVO toReq = new LLMRequestVO(); toReq.header.app_id = appid; toReq.parameter.chat.chat_id = inVO.userID.toString(); // 以UUID区分用户 thisHistory.add(new Message.Text("user", inVO.question)); toReq.payload.message.text = thisHistory; String toReqJSON = JSON.toJSONString(toReq); // TODO Test System.out.println("toReqJSON: \n" + toReqJSON + "\n------"); System.out.println("authURL: \n" + authURL + "\n------"); // TODO 3. 发起请求,获得回复,将回复添加到对话历史,返回 LLMSocket llmSocket = new LLMSocket(authURL, toReqJSON); String thisAnswer = llmSocket.executeQuery().toString(); thisHistory.add(new Message.Text("assistant", thisAnswer)); LLMServiceResponseVO outVO = new LLMServiceResponseVO(inVO.userID, thisAnswer); return outVO; } } 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, ""); } catch (Exception e) { e.printStackTrace(); } } } /** * WebSocket连接建立后,启动线程,托管webSocket(等待关闭时机) * @param webSocket * @param response */ @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执行一次 * @param webSocket * @param text */ @Override public synchronized void onMessage(@NotNull WebSocket webSocket, @NotNull String text) { // System.out.println(userId + "用来区分是哪个用户的结果" + text); // TODO Test System.out.println("onMessage() " + threadNum + ": "); threadNum++; System.out.println("LLMResponseJSON: " + text); // TODO 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; } // TODO Test System.out.println("responseVO: " + responseVO); // TODO 2. 提取其中的回答串 List textList = responseVO.payload.choices.text; // TODO Test System.out.println("textList.size(): " + textList.size()); // TODO 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) { // TODO Auto-generated catch block e.printStackTrace(); } } }