1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
|
package com.wsl.model.llm.api.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.wsl.model.llm.api.convert.ChatRequestConvert;
import com.wsl.model.llm.api.dto.ChatRequestDTO;
import com.wsl.model.llm.api.dto.SparkDeskDTO;
import com.wsl.model.llm.api.dto.SparkDeskHeaderDTO;
import com.wsl.model.llm.api.service.ModelService;
import com.wsl.model.llm.api.vo.ChatResponseVO;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
@Service("SparkDeskService")
@Slf4j
public class SparkDeskServiceImpl implements ModelService {
private String appId = "?";
private String appSecret = "?";
private String appKey = "?";
public static final String HOST_URL = "https://spark-api.xf-yun.com/v3.5/chat";
@Override
public ChatResponseVO chatMessage(ChatRequestDTO dto) throws Exception {
ChatResponseVO vo = new ChatResponseVO();
SparkDeskDTO sparkDeskDTO = ChatRequestConvert.INSTANCE.convertSparkDesk(dto);
sparkDeskDTO.setHeader(new SparkDeskHeaderDTO(appId));
String authUrl = getAuthUrl(HOST_URL, appKey, appSecret).replace("http://", "ws://").replace("https://", "wss://");
Request request = new Request.Builder().url(authUrl).build();
OkHttpClient client = new OkHttpClient.Builder().build();
StringBuilder sb = new StringBuilder();
CompletableFuture<String> messageReceived = new CompletableFuture<>();
String body = JSON.toJSONString(sparkDeskDTO);
WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket, Response response) {
log.info("讯飞星火请求参数 sparkDesk request:{}", body);
webSocket.send(body);
}
@Override
public void onMessage(WebSocket webSocket, String text) {
try {
JSONObject obj = JSON.parseObject(text);
Optional<String> contentOptional = Optional.ofNullable(obj)
.map(jsonObject -> jsonObject.getJSONObject("payload"))
.map(payload -> payload.getJSONObject("choices"))
.map(choices -> choices.getJSONArray("text"))
.map(jsonArray -> jsonArray.getJSONObject(0))
.map(jsonObject -> jsonObject.getString("content"));
String str = contentOptional.orElseThrow(() -> new RuntimeException(JSONObject.toJSONString(obj)));
sb.append(str);
Optional<Long> statusOptional = Optional.ofNullable(obj)
.map(jsonObject -> jsonObject.getJSONObject("header"))
.map(header -> header.getLong("status"));
if (statusOptional.isPresent() && statusOptional.get() == 2) {
webSocket.close(1000, "Closing WebSocket connection");
messageReceived.complete(text);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
});
messageReceived.get(60, TimeUnit.SECONDS);
webSocket.close(1000, "Closing WebSocket connection");
log.info("讯飞星火返回结果 sparkDesk response:{}", sb);
vo.setResult(sb.toString());
return vo;
}
public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
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";
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));
String sha = Base64.getEncoder().encodeToString(hexDigits);
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();
return httpUrl.toString();
}
}
|