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.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(); } } /** * 用于拼接整个回答串 */ StringBuffer answerBuffer = new StringBuffer(); public LLMService() { } public LLMServiceResponseVO query(LLMServiceRequestVO inVO) { LLMServiceResponseVO outVO = new LLMServiceResponseVO(); // 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.uid = null; 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); System.out.println(toReqJSON); // TODO 3. 发起请求,获得回复,将回复添加到对话历史,返回 LLMSocket llmSocket = new LLMSocket(authURL, toReqJSON); StringBuffer ans = llmSocket.executeQuery(); } } class LLMSocket extends WebSocketListener { /** * 请求参数JSON */ String requestJSON; /** * 与模型接口服务器建立WebSocket连接用 */ OkHttpClient client; Request request; WebSocket webSocket; /** * 关闭WebSocket线程标志 */ boolean wsCloseFlag = false; StringBuffer output = new StringBuffer(); /** * 建立连接,执行对模型的请求,并同步等待 * @return 含有完整回答串的StringBuffer */ StringBuffer executeQuery() { webSocket = client.newWebSocket(request, this); // 用指定的请求URL建立连接 try { do { Thread.sleep(200); } while (!wsCloseFlag); } catch (InterruptedException e) { e.printStackTrace(); } return output; } 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(); } /** * 收到一个Response执行一次 * @param webSocket * @param text */ @Override public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) { // System.out.println(userId + "用来区分那个用户的结果" + text); 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, ""); } // TODO 每个Response里面只有一个text? List textList = responseVO.payload.choices.text; System.out.println(textList.size()); for (Choices.Text temp : textList) { System.out.print(temp.content); output } 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(); } } }