|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+package com.huimv.employment.integration.kb;
|
|
|
2
|
+
|
|
|
3
|
+import com.fasterxml.jackson.databind.JsonNode;
|
|
|
4
|
+import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
5
|
+import com.huimv.employment.common.exception.BizException;
|
|
|
6
|
+import com.huimv.employment.common.exception.ErrorCode;
|
|
|
7
|
+import org.slf4j.Logger;
|
|
|
8
|
+import org.slf4j.LoggerFactory;
|
|
|
9
|
+import org.springframework.beans.factory.annotation.Qualifier;
|
|
|
10
|
+import org.springframework.core.io.FileSystemResource;
|
|
|
11
|
+import org.springframework.http.HttpEntity;
|
|
|
12
|
+import org.springframework.http.HttpHeaders;
|
|
|
13
|
+import org.springframework.http.HttpMethod;
|
|
|
14
|
+import org.springframework.http.ResponseEntity;
|
|
|
15
|
+import org.springframework.stereotype.Service;
|
|
|
16
|
+import org.springframework.util.LinkedMultiValueMap;
|
|
|
17
|
+import org.springframework.util.MultiValueMap;
|
|
|
18
|
+import org.springframework.util.StringUtils;
|
|
|
19
|
+import org.springframework.web.client.HttpStatusCodeException;
|
|
|
20
|
+import org.springframework.web.client.ResourceAccessException;
|
|
|
21
|
+import org.springframework.web.client.RestTemplate;
|
|
|
22
|
+
|
|
|
23
|
+import java.io.File;
|
|
|
24
|
+import java.io.UnsupportedEncodingException;
|
|
|
25
|
+import java.net.URI;
|
|
|
26
|
+import java.net.URLEncoder;
|
|
|
27
|
+import java.nio.charset.StandardCharsets;
|
|
|
28
|
+import java.util.function.Supplier;
|
|
|
29
|
+
|
|
|
30
|
+/**
|
|
|
31
|
+ * 调用大模型知识库开放 API(multipart 上传 / 删除文件等)。
|
|
|
32
|
+ */
|
|
|
33
|
+@Service
|
|
|
34
|
+public class KnowledgeBaseClientImpl implements KnowledgeBaseClient {
|
|
|
35
|
+
|
|
|
36
|
+ private static final Logger log = LoggerFactory.getLogger(KnowledgeBaseClientImpl.class);
|
|
|
37
|
+
|
|
|
38
|
+ private static final String[] FILE_ID_KEYS = { "file_id", "fileId", "kbDocId", "kb_doc_id", "docId", "id" };
|
|
|
39
|
+
|
|
|
40
|
+ private final KbApiProperties properties;
|
|
|
41
|
+ private final RestTemplate restTemplate;
|
|
|
42
|
+ private final ObjectMapper objectMapper;
|
|
|
43
|
+
|
|
|
44
|
+ public KnowledgeBaseClientImpl(KbApiProperties properties,
|
|
|
45
|
+ @Qualifier("kbRestTemplate") RestTemplate restTemplate,
|
|
|
46
|
+ ObjectMapper objectMapper) {
|
|
|
47
|
+ this.properties = properties;
|
|
|
48
|
+ this.restTemplate = restTemplate;
|
|
|
49
|
+ this.objectMapper = objectMapper;
|
|
|
50
|
+ }
|
|
|
51
|
+
|
|
|
52
|
+ @Override
|
|
|
53
|
+ public String uploadFile(File file, String uploadFilename, String knowledgeBase, String category) {
|
|
|
54
|
+ ensureReady();
|
|
|
55
|
+ if (file == null || !file.isFile()) {
|
|
|
56
|
+ throw new BizException(ErrorCode.BAD_REQUEST, "上传文件无效或不存在");
|
|
|
57
|
+ }
|
|
|
58
|
+ String kb = StringUtils.hasText(knowledgeBase) ? knowledgeBase.trim() : properties.getDefaultKnowledgeBase();
|
|
|
59
|
+ if (!StringUtils.hasText(kb)) {
|
|
|
60
|
+ kb = "default";
|
|
|
61
|
+ }
|
|
|
62
|
+ String name = StringUtils.hasText(uploadFilename) ? uploadFilename.trim() : file.getName();
|
|
|
63
|
+
|
|
|
64
|
+ MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
|
|
|
65
|
+ body.add("knowledge_base", kb);
|
|
|
66
|
+ body.add("category", category);
|
|
|
67
|
+ body.add("file", multipartFileResource(file, name));
|
|
|
68
|
+
|
|
|
69
|
+ return postMultipart(body);
|
|
|
70
|
+ }
|
|
|
71
|
+
|
|
|
72
|
+ @Override
|
|
|
73
|
+ public String uploadFileByUrl(String fileUrl, String category, String description) {
|
|
|
74
|
+ ensureReady();
|
|
|
75
|
+ MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
|
|
|
76
|
+ body.add("url", fileUrl);
|
|
|
77
|
+ body.add("category", category);
|
|
|
78
|
+ body.add("description", description);
|
|
|
79
|
+ return postMultipart(body);
|
|
|
80
|
+ }
|
|
|
81
|
+
|
|
|
82
|
+ private String postMultipart(MultiValueMap<String, Object> body) {
|
|
|
83
|
+ String url = properties.baseUrl() + "/api/v1/kb/files";
|
|
|
84
|
+ HttpHeaders headers = new HttpHeaders();
|
|
|
85
|
+ headers.add(properties.getAuthHeaderName(), properties.authHeaderValue());
|
|
|
86
|
+ HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
|
|
|
87
|
+ String raw = executeWithRetry("知识库上传", () -> {
|
|
|
88
|
+ try {
|
|
|
89
|
+ ResponseEntity<String> resp = restTemplate.exchange(URI.create(url), HttpMethod.POST, entity, String.class);
|
|
|
90
|
+ return resp.getBody();
|
|
|
91
|
+ } catch (HttpStatusCodeException e) {
|
|
|
92
|
+ String b = e.getResponseBodyAsString(StandardCharsets.UTF_8);
|
|
|
93
|
+ throw new BizException(ErrorCode.KB_SERVICE_FAILED,
|
|
|
94
|
+ "知识库上传失败 HTTP " + e.getRawStatusCode() + ":" + abbreviate(b));
|
|
|
95
|
+ }
|
|
|
96
|
+ });
|
|
|
97
|
+ return parseUploadResponse(raw);
|
|
|
98
|
+ }
|
|
|
99
|
+
|
|
|
100
|
+ private static FileSystemResource multipartFileResource(File file, String uploadName) {
|
|
|
101
|
+ return new FileSystemResource(file) {
|
|
|
102
|
+ @Override
|
|
|
103
|
+ public String getFilename() {
|
|
|
104
|
+ return uploadName;
|
|
|
105
|
+ }
|
|
|
106
|
+ };
|
|
|
107
|
+ }
|
|
|
108
|
+
|
|
|
109
|
+ @Override
|
|
|
110
|
+ public void deleteFile(String kbDocId) {
|
|
|
111
|
+ ensureReady();
|
|
|
112
|
+ if (!StringUtils.hasText(kbDocId)) {
|
|
|
113
|
+ throw new BizException(ErrorCode.BAD_REQUEST, "知识库文档 id 为空");
|
|
|
114
|
+ }
|
|
|
115
|
+ String url = properties.baseUrl() + "/api/v1/kb/files/" + encodePathSegment(kbDocId);
|
|
|
116
|
+ HttpHeaders headers = new HttpHeaders();
|
|
|
117
|
+ headers.add(properties.getAuthHeaderName(), properties.authHeaderValue());
|
|
|
118
|
+ HttpEntity<Void> entity = new HttpEntity<>(headers);
|
|
|
119
|
+ executeWithRetry("知识库删除", () -> {
|
|
|
120
|
+ try {
|
|
|
121
|
+ ResponseEntity<String> resp = restTemplate.exchange(URI.create(url), HttpMethod.DELETE, entity, String.class);
|
|
|
122
|
+ if (!resp.getStatusCode().is2xxSuccessful()) {
|
|
|
123
|
+ throw new BizException(ErrorCode.KB_SERVICE_FAILED,
|
|
|
124
|
+ "知识库删除失败 HTTP " + resp.getStatusCode().value());
|
|
|
125
|
+ }
|
|
|
126
|
+ return null;
|
|
|
127
|
+ } catch (HttpStatusCodeException e) {
|
|
|
128
|
+ if (e.getRawStatusCode() == 404) {
|
|
|
129
|
+ return null;
|
|
|
130
|
+ }
|
|
|
131
|
+ String b = e.getResponseBodyAsString(StandardCharsets.UTF_8);
|
|
|
132
|
+ throw new BizException(ErrorCode.KB_SERVICE_FAILED,
|
|
|
133
|
+ "知识库删除失败 HTTP " + e.getRawStatusCode() + ":" + abbreviate(b));
|
|
|
134
|
+ }
|
|
|
135
|
+ });
|
|
|
136
|
+ }
|
|
|
137
|
+
|
|
|
138
|
+ private <T> T executeWithRetry(String operation, Supplier<T> action) {
|
|
|
139
|
+ int maxRetries = Math.max(0, properties.getMaxRetries());
|
|
|
140
|
+ BizException last = null;
|
|
|
141
|
+ for (int attempt = 0; attempt <= maxRetries; attempt++) {
|
|
|
142
|
+ try {
|
|
|
143
|
+ return action.get();
|
|
|
144
|
+ } catch (BizException e) {
|
|
|
145
|
+ if (attempt >= maxRetries || !isRetryable(e)) {
|
|
|
146
|
+ throw e;
|
|
|
147
|
+ }
|
|
|
148
|
+ last = e;
|
|
|
149
|
+ log.warn("{}失败,第 {}/{} 次重试:{}", operation, attempt + 1, maxRetries, e.getMessage());
|
|
|
150
|
+ sleepBeforeRetry();
|
|
|
151
|
+ } catch (Exception e) {
|
|
|
152
|
+ BizException wrapped = wrapUnexpected(operation, e);
|
|
|
153
|
+ if (attempt >= maxRetries || !isRetryable(wrapped, e)) {
|
|
|
154
|
+ throw wrapped;
|
|
|
155
|
+ }
|
|
|
156
|
+ last = wrapped;
|
|
|
157
|
+ log.warn("{}异常,第 {}/{} 次重试:{}", operation, attempt + 1, maxRetries, e.getMessage());
|
|
|
158
|
+ sleepBeforeRetry();
|
|
|
159
|
+ }
|
|
|
160
|
+ }
|
|
|
161
|
+ if (last != null) {
|
|
|
162
|
+ throw last;
|
|
|
163
|
+ }
|
|
|
164
|
+ throw new BizException(ErrorCode.KB_SERVICE_FAILED, operation + "失败");
|
|
|
165
|
+ }
|
|
|
166
|
+
|
|
|
167
|
+ private static boolean isRetryable(BizException e) {
|
|
|
168
|
+ String msg = e.getMessage();
|
|
|
169
|
+ if (msg == null) {
|
|
|
170
|
+ return false;
|
|
|
171
|
+ }
|
|
|
172
|
+ if (msg.contains("HTTP 404")) {
|
|
|
173
|
+ return false;
|
|
|
174
|
+ }
|
|
|
175
|
+ if (msg.contains("HTTP 408") || msg.contains("HTTP 429")) {
|
|
|
176
|
+ return true;
|
|
|
177
|
+ }
|
|
|
178
|
+ if (msg.matches(".*HTTP [45]\\d\\d.*")) {
|
|
|
179
|
+ int code = extractHttpStatus(msg);
|
|
|
180
|
+ return code >= 500 || code == 408 || code == 429;
|
|
|
181
|
+ }
|
|
|
182
|
+ return false;
|
|
|
183
|
+ }
|
|
|
184
|
+
|
|
|
185
|
+ private static boolean isRetryable(BizException wrapped, Exception cause) {
|
|
|
186
|
+ if (cause instanceof ResourceAccessException) {
|
|
|
187
|
+ return true;
|
|
|
188
|
+ }
|
|
|
189
|
+ return isRetryable(wrapped);
|
|
|
190
|
+ }
|
|
|
191
|
+
|
|
|
192
|
+ private static int extractHttpStatus(String msg) {
|
|
|
193
|
+ int idx = msg.indexOf("HTTP ");
|
|
|
194
|
+ if (idx < 0) {
|
|
|
195
|
+ return 0;
|
|
|
196
|
+ }
|
|
|
197
|
+ int start = idx + 5;
|
|
|
198
|
+ int end = start;
|
|
|
199
|
+ while (end < msg.length() && Character.isDigit(msg.charAt(end))) {
|
|
|
200
|
+ end++;
|
|
|
201
|
+ }
|
|
|
202
|
+ if (end == start) {
|
|
|
203
|
+ return 0;
|
|
|
204
|
+ }
|
|
|
205
|
+ try {
|
|
|
206
|
+ return Integer.parseInt(msg.substring(start, end));
|
|
|
207
|
+ } catch (NumberFormatException e) {
|
|
|
208
|
+ return 0;
|
|
|
209
|
+ }
|
|
|
210
|
+ }
|
|
|
211
|
+
|
|
|
212
|
+ private void sleepBeforeRetry() {
|
|
|
213
|
+ int interval = Math.max(0, properties.getRetryIntervalMs());
|
|
|
214
|
+ if (interval <= 0) {
|
|
|
215
|
+ return;
|
|
|
216
|
+ }
|
|
|
217
|
+ try {
|
|
|
218
|
+ Thread.sleep(interval);
|
|
|
219
|
+ } catch (InterruptedException e) {
|
|
|
220
|
+ Thread.currentThread().interrupt();
|
|
|
221
|
+ }
|
|
|
222
|
+ }
|
|
|
223
|
+
|
|
|
224
|
+ private static BizException wrapUnexpected(String operation, Exception e) {
|
|
|
225
|
+ if (e instanceof BizException) {
|
|
|
226
|
+ return (BizException) e;
|
|
|
227
|
+ }
|
|
|
228
|
+ return new BizException(ErrorCode.KB_SERVICE_FAILED, operation + "异常:" + e.getMessage());
|
|
|
229
|
+ }
|
|
|
230
|
+
|
|
|
231
|
+ private static String encodePathSegment(String id) {
|
|
|
232
|
+ try {
|
|
|
233
|
+ return URLEncoder.encode(id, StandardCharsets.UTF_8.name()).replace("+", "%20");
|
|
|
234
|
+ } catch (UnsupportedEncodingException e) {
|
|
|
235
|
+ return id;
|
|
|
236
|
+ }
|
|
|
237
|
+ }
|
|
|
238
|
+
|
|
|
239
|
+ private String parseUploadResponse(String raw) {
|
|
|
240
|
+ if (!StringUtils.hasText(raw)) {
|
|
|
241
|
+ throw new BizException(ErrorCode.KB_SERVICE_FAILED, "知识库上传返回空响应");
|
|
|
242
|
+ }
|
|
|
243
|
+ JsonNode root;
|
|
|
244
|
+ try {
|
|
|
245
|
+ root = objectMapper.readTree(raw);
|
|
|
246
|
+ } catch (Exception e) {
|
|
|
247
|
+ throw new BizException(ErrorCode.KB_SERVICE_FAILED, "知识库上传响应非 JSON:" + abbreviate(raw));
|
|
|
248
|
+ }
|
|
|
249
|
+ assertBusinessOk(root);
|
|
|
250
|
+ String fileId = extractFileId(root);
|
|
|
251
|
+ if (!StringUtils.hasText(fileId)) {
|
|
|
252
|
+ throw new BizException(ErrorCode.KB_SERVICE_FAILED,
|
|
|
253
|
+ "知识库上传成功但未解析到 file_id,响应:" + abbreviate(raw));
|
|
|
254
|
+ }
|
|
|
255
|
+ return fileId;
|
|
|
256
|
+ }
|
|
|
257
|
+
|
|
|
258
|
+ private void assertBusinessOk(JsonNode root) {
|
|
|
259
|
+ if (root == null || !root.has("code")) {
|
|
|
260
|
+ return;
|
|
|
261
|
+ }
|
|
|
262
|
+ JsonNode c = root.get("code");
|
|
|
263
|
+ boolean ok = false;
|
|
|
264
|
+ if (c.isNumber()) {
|
|
|
265
|
+ int v = c.intValue();
|
|
|
266
|
+ ok = (v == 0 || v == 200);
|
|
|
267
|
+ } else if (c.isTextual()) {
|
|
|
268
|
+ String s = c.asText();
|
|
|
269
|
+ ok = "0".equals(s) || "200".equals(s) || "success".equalsIgnoreCase(s);
|
|
|
270
|
+ }
|
|
|
271
|
+ if (!ok) {
|
|
|
272
|
+ String msg = root.has("message") ? root.get("message").asText(null) : null;
|
|
|
273
|
+ if (!StringUtils.hasText(msg) && root.has("msg")) {
|
|
|
274
|
+ msg = root.get("msg").asText(null);
|
|
|
275
|
+ }
|
|
|
276
|
+ if (!StringUtils.hasText(msg)) {
|
|
|
277
|
+ msg = "知识库接口返回失败";
|
|
|
278
|
+ }
|
|
|
279
|
+ throw new BizException(ErrorCode.KB_SERVICE_FAILED, msg);
|
|
|
280
|
+ }
|
|
|
281
|
+ }
|
|
|
282
|
+
|
|
|
283
|
+ private static String extractFileId(JsonNode root) {
|
|
|
284
|
+ JsonNode data = root.get("data");
|
|
|
285
|
+ if (data != null && data.isTextual()) {
|
|
|
286
|
+ String t = data.asText(null);
|
|
|
287
|
+ if (StringUtils.hasText(t)) {
|
|
|
288
|
+ return t;
|
|
|
289
|
+ }
|
|
|
290
|
+ }
|
|
|
291
|
+ if (data != null && data.isObject()) {
|
|
|
292
|
+ for (String key : FILE_ID_KEYS) {
|
|
|
293
|
+ if (data.has(key) && !data.get(key).isNull()) {
|
|
|
294
|
+ String v = data.get(key).asText(null);
|
|
|
295
|
+ if (StringUtils.hasText(v)) {
|
|
|
296
|
+ return v;
|
|
|
297
|
+ }
|
|
|
298
|
+ }
|
|
|
299
|
+ }
|
|
|
300
|
+ }
|
|
|
301
|
+ for (String key : FILE_ID_KEYS) {
|
|
|
302
|
+ if (root.has(key) && !root.get(key).isNull()) {
|
|
|
303
|
+ String v = root.get(key).asText(null);
|
|
|
304
|
+ if (StringUtils.hasText(v)) {
|
|
|
305
|
+ return v;
|
|
|
306
|
+ }
|
|
|
307
|
+ }
|
|
|
308
|
+ }
|
|
|
309
|
+ return null;
|
|
|
310
|
+ }
|
|
|
311
|
+
|
|
|
312
|
+ private static String abbreviate(String s) {
|
|
|
313
|
+ if (s == null) {
|
|
|
314
|
+ return "";
|
|
|
315
|
+ }
|
|
|
316
|
+ String t = s.trim();
|
|
|
317
|
+ if (t.length() > 500) {
|
|
|
318
|
+ return t.substring(0, 500) + "...";
|
|
|
319
|
+ }
|
|
|
320
|
+ return t;
|
|
|
321
|
+ }
|
|
|
322
|
+
|
|
|
323
|
+ private void ensureReady() {
|
|
|
324
|
+ if (!properties.isEnabled()) {
|
|
|
325
|
+ throw new BizException(ErrorCode.KB_SERVICE_DISABLED);
|
|
|
326
|
+ }
|
|
|
327
|
+ if (!StringUtils.hasText(properties.getApiKey())) {
|
|
|
328
|
+ throw new BizException(ErrorCode.KB_SERVICE_FAILED, "未配置知识库访问密钥 fe.kb.api-key");
|
|
|
329
|
+ }
|
|
|
330
|
+ }
|
|
|
331
|
+}
|