From d8d82ceda75fa17972d6996f83078367a19c1730 Mon Sep 17 00:00:00 2001
From: Junjie <fallin.jie@qq.com>
Date: 星期四, 12 三月 2026 15:38:32 +0800
Subject: [PATCH] #
---
src/main/java/com/zy/ai/service/LlmChatService.java | 345 ++++++++++++++++++--------------------------------------
1 files changed, 113 insertions(+), 232 deletions(-)
diff --git a/src/main/java/com/zy/ai/service/LlmChatService.java b/src/main/java/com/zy/ai/service/LlmChatService.java
index 3e25561..a3835f5 100644
--- a/src/main/java/com/zy/ai/service/LlmChatService.java
+++ b/src/main/java/com/zy/ai/service/LlmChatService.java
@@ -1,8 +1,6 @@
package com.zy.ai.service;
import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONArray;
-import com.alibaba.fastjson.JSONObject;
import com.zy.ai.entity.ChatCompletionRequest;
import com.zy.ai.entity.ChatCompletionResponse;
import com.zy.ai.entity.LlmCallLog;
@@ -10,19 +8,21 @@
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
-import org.springframework.web.reactive.function.client.WebClient;
+import org.springframework.web.client.RestClientResponseException;
+import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Flux;
import java.util.ArrayList;
import java.util.Date;
+import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
@Slf4j
@@ -34,6 +34,7 @@
private final LlmRoutingService llmRoutingService;
private final LlmCallLogService llmCallLogService;
+ private final LlmSpringAiClientService llmSpringAiClientService;
@Value("${llm.base-url:}")
private String fallbackBaseUrl;
@@ -99,7 +100,7 @@
List<ResolvedRoute> routes = resolveRoutes();
if (routes.isEmpty()) {
log.error("璋冪敤 LLM 澶辫触: 鏈厤缃彲鐢� LLM 璺敱");
- recordCall(traceId, scene, false, 1, null, false, null, 0L, req, null, "none",
+ recordCall(traceId, scene, false, 1, null, false, null, 0L, req, null, null, "none",
new RuntimeException("鏈厤缃彲鐢� LLM 璺敱"), "no_route");
return null;
}
@@ -118,7 +119,7 @@
boolean canSwitch = shouldSwitch(route, false);
markFailure(route, ex, canSwitch);
recordCall(traceId, scene, false, i + 1, route, false, callResult.statusCode,
- System.currentTimeMillis() - start, routeReq, callResult.payload, "error", ex,
+ System.currentTimeMillis() - start, routeReq, resp, callResult.payload, "error", ex,
"invalid_completion");
if (hasNext && canSwitch) {
log.warn("LLM 鍒囨崲鍒颁笅涓�璺敱, current={}, reason={}", route.tag(), ex.getMessage());
@@ -130,7 +131,7 @@
}
markSuccess(route);
recordCall(traceId, scene, false, i + 1, route, true, callResult.statusCode,
- System.currentTimeMillis() - start, routeReq, buildResponseText(resp, callResult.payload),
+ System.currentTimeMillis() - start, routeReq, resp, buildResponseText(resp, callResult.payload),
"none", null, null);
return resp;
} catch (Throwable ex) {
@@ -139,7 +140,7 @@
boolean canSwitch = shouldSwitch(route, quota);
markFailure(route, ex, canSwitch);
recordCall(traceId, scene, false, i + 1, route, false, statusCodeOf(ex),
- System.currentTimeMillis() - start, routeReq, responseBodyOf(ex),
+ System.currentTimeMillis() - start, routeReq, null, responseBodyOf(ex),
quota ? "quota" : "error", ex, null);
if (hasNext && canSwitch) {
log.warn("LLM 鍒囨崲鍒颁笅涓�璺敱, current={}, reason={}", route.tag(), errorText(ex));
@@ -169,7 +170,7 @@
req.setMax_tokens(maxTokens != null ? maxTokens : 1024);
req.setStream(true);
- streamWithFailover(req, onChunk, onComplete, onError, "chat_stream");
+ streamWithFailover(req, onChunk, onComplete, onError, null, "chat_stream");
}
public void chatStreamWithTools(List<ChatCompletionRequest.Message> messages,
@@ -178,7 +179,8 @@
List<Object> tools,
Consumer<String> onChunk,
Runnable onComplete,
- Consumer<Throwable> onError) {
+ Consumer<Throwable> onError,
+ Consumer<ChatCompletionResponse.Usage> onUsage) {
ChatCompletionRequest req = new ChatCompletionRequest();
req.setMessages(messages);
req.setTemperature(temperature != null ? temperature : 0.3);
@@ -188,23 +190,24 @@
req.setTools(tools);
req.setTool_choice("auto");
}
- streamWithFailover(req, onChunk, onComplete, onError, tools != null && !tools.isEmpty() ? "chat_stream_tools" : "chat_stream");
+ streamWithFailover(req, onChunk, onComplete, onError, onUsage, tools != null && !tools.isEmpty() ? "chat_stream_tools" : "chat_stream");
}
private void streamWithFailover(ChatCompletionRequest req,
Consumer<String> onChunk,
Runnable onComplete,
Consumer<Throwable> onError,
+ Consumer<ChatCompletionResponse.Usage> onUsage,
String scene) {
String traceId = nextTraceId();
List<ResolvedRoute> routes = resolveRoutes();
if (routes.isEmpty()) {
- recordCall(traceId, scene, true, 1, null, false, null, 0L, req, null, "none",
+ recordCall(traceId, scene, true, 1, null, false, null, 0L, req, null, null, "none",
new RuntimeException("鏈厤缃彲鐢� LLM 璺敱"), "no_route");
if (onError != null) onError.accept(new RuntimeException("鏈厤缃彲鐢� LLM 璺敱"));
return;
}
- attemptStream(routes, 0, req, onChunk, onComplete, onError, traceId, scene);
+ attemptStream(routes, 0, req, onChunk, onComplete, onError, onUsage, traceId, scene);
}
private void attemptStream(List<ResolvedRoute> routes,
@@ -213,6 +216,7 @@
Consumer<String> onChunk,
Runnable onComplete,
Consumer<Throwable> onError,
+ Consumer<ChatCompletionResponse.Usage> onUsage,
String traceId,
String scene) {
if (index >= routes.size()) {
@@ -228,6 +232,7 @@
AtomicBoolean doneSeen = new AtomicBoolean(false);
AtomicBoolean errorSeen = new AtomicBoolean(false);
AtomicBoolean emitted = new AtomicBoolean(false);
+ AtomicReference<ChatCompletionResponse.Usage> usageRef = new AtomicReference<>();
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
Thread drain = new Thread(() -> {
@@ -257,38 +262,11 @@
drain.setDaemon(true);
drain.start();
- streamFlux(route, routeReq).subscribe(payload -> {
+ Flux<String> streamSource = streamFluxWithSpringAi(route, routeReq, usageRef::set);
+ streamSource.subscribe(payload -> {
if (payload == null || payload.isEmpty()) return;
- String[] events = payload.split("\\r?\\n\\r?\\n");
- for (String part : events) {
- String s = part;
- if (s == null || s.isEmpty()) continue;
- if (s.startsWith("data:")) {
- s = s.substring(5);
- if (s.startsWith(" ")) s = s.substring(1);
- }
- if ("[DONE]".equals(s.trim())) {
- doneSeen.set(true);
- continue;
- }
- try {
- JSONObject obj = JSON.parseObject(s);
- JSONArray choices = obj.getJSONArray("choices");
- if (choices != null && !choices.isEmpty()) {
- JSONObject c0 = choices.getJSONObject(0);
- JSONObject delta = c0.getJSONObject("delta");
- if (delta != null) {
- String content = delta.getString("content");
- if (content != null) {
- queue.offer(content);
- appendLimited(outputBuffer, content);
- }
- }
- }
- } catch (Exception e) {
- log.warn("瑙f瀽 LLM stream 鐗囨澶辫触: {}", e.getMessage());
- }
- }
+ queue.offer(payload);
+ appendLimited(outputBuffer, payload);
}, err -> {
errorSeen.set(true);
doneSeen.set(true);
@@ -296,80 +274,44 @@
boolean canSwitch = shouldSwitch(route, quota);
markFailure(route, err, canSwitch);
recordCall(traceId, scene, true, index + 1, route, false, statusCodeOf(err),
- System.currentTimeMillis() - start, routeReq, outputBuffer.toString(),
+ System.currentTimeMillis() - start, routeReq, usageResponse(usageRef.get()), outputBuffer.toString(),
quota ? "quota" : "error", err, "emitted=" + emitted.get());
if (!emitted.get() && canSwitch && index < routes.size() - 1) {
log.warn("LLM 璺敱澶辫触锛岃嚜鍔ㄥ垏鎹紝current={}, reason={}", route.tag(), errorText(err));
- attemptStream(routes, index + 1, req, onChunk, onComplete, onError, traceId, scene);
+ attemptStream(routes, index + 1, req, onChunk, onComplete, onError, onUsage, traceId, scene);
return;
}
if (onError != null) onError.accept(err);
}, () -> {
- if (!doneSeen.get()) {
- RuntimeException ex = new RuntimeException("LLM 娴佹剰澶栧畬鎴�");
- errorSeen.set(true);
- doneSeen.set(true);
- boolean canSwitch = shouldSwitch(route, false);
- markFailure(route, ex, canSwitch);
- recordCall(traceId, scene, true, index + 1, route, false, 200,
- System.currentTimeMillis() - start, routeReq, outputBuffer.toString(),
- "error", ex, "unexpected_stream_end");
- if (!emitted.get() && canSwitch && index < routes.size() - 1) {
- log.warn("LLM 璺敱娴佸紓甯稿畬鎴愶紝鑷姩鍒囨崲锛宑urrent={}", route.tag());
- attemptStream(routes, index + 1, req, onChunk, onComplete, onError, traceId, scene);
- } else {
- if (onError != null) onError.accept(ex);
+ markSuccess(route);
+ if (onUsage != null && usageRef.get() != null) {
+ try {
+ onUsage.accept(usageRef.get());
+ } catch (Exception ignore) {
}
- } else {
- markSuccess(route);
- recordCall(traceId, scene, true, index + 1, route, true, 200,
- System.currentTimeMillis() - start, routeReq, outputBuffer.toString(),
- "none", null, null);
- doneSeen.set(true);
}
+ recordCall(traceId, scene, true, index + 1, route, true, 200,
+ System.currentTimeMillis() - start, routeReq, usageResponse(usageRef.get()), outputBuffer.toString(),
+ "none", null, null);
+ doneSeen.set(true);
});
}
- private Flux<String> streamFlux(ResolvedRoute route, ChatCompletionRequest req) {
- WebClient client = WebClient.builder().baseUrl(route.baseUrl).build();
- return client.post()
- .uri("/chat/completions")
- .header(HttpHeaders.AUTHORIZATION, "Bearer " + route.apiKey)
- .contentType(MediaType.APPLICATION_JSON)
- .accept(MediaType.TEXT_EVENT_STREAM)
- .bodyValue(req)
- .exchangeToFlux(resp -> {
- int status = resp.rawStatusCode();
- if (status >= 200 && status < 300) {
- return resp.bodyToFlux(String.class);
- }
- return resp.bodyToMono(String.class)
- .defaultIfEmpty("")
- .flatMapMany(body -> Flux.error(new LlmRouteException(status, body)));
- })
- .doOnError(ex -> log.error("璋冪敤 LLM 娴佸紡澶辫触, route={}", route.tag(), ex));
+ private Flux<String> streamFluxWithSpringAi(ResolvedRoute route,
+ ChatCompletionRequest req,
+ Consumer<ChatCompletionResponse.Usage> usageConsumer) {
+ return llmSpringAiClientService.streamCompletion(route.baseUrl, route.apiKey, req, usageConsumer)
+ .doOnError(ex -> log.error("璋冪敤 Spring AI 娴佸紡澶辫触, route={}", route.tag(), ex));
}
private CompletionCallResult callCompletion(ResolvedRoute route, ChatCompletionRequest req) {
- WebClient client = WebClient.builder().baseUrl(route.baseUrl).build();
- RawCompletionResult raw = client.post()
- .uri("/chat/completions")
- .header(HttpHeaders.AUTHORIZATION, "Bearer " + route.apiKey)
- .contentType(MediaType.APPLICATION_JSON)
- .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_EVENT_STREAM)
- .bodyValue(req)
- .exchangeToMono(resp -> resp.bodyToFlux(String.class)
- .collectList()
- .map(list -> new RawCompletionResult(resp.rawStatusCode(), String.join("\\n\\n", list))))
- .block();
+ return callCompletionWithSpringAi(route, req);
+ }
- if (raw == null) {
- throw new RuntimeException("LLM 杩斿洖涓虹┖");
- }
- if (raw.statusCode < 200 || raw.statusCode >= 300) {
- throw new LlmRouteException(raw.statusCode, raw.payload);
- }
- return new CompletionCallResult(raw.statusCode, raw.payload, parseCompletion(raw.payload));
+ private CompletionCallResult callCompletionWithSpringAi(ResolvedRoute route, ChatCompletionRequest req) {
+ LlmSpringAiClientService.CompletionCallResult result =
+ llmSpringAiClientService.callCompletion(route.baseUrl, route.apiKey, req);
+ return new CompletionCallResult(result.getStatusCode(), result.getPayload(), result.getResponse());
}
private ChatCompletionRequest applyRoute(ChatCompletionRequest req, ResolvedRoute route, boolean stream) {
@@ -430,22 +372,36 @@
private String errorText(Throwable ex) {
if (ex == null) return "unknown";
- if (ex instanceof LlmRouteException) {
- LlmRouteException e = (LlmRouteException) ex;
- String body = e.body == null ? "" : e.body;
- if (body.length() > 240) {
+ if (ex instanceof RestClientResponseException) {
+ RestClientResponseException e = (RestClientResponseException) ex;
+ String body = e.getResponseBodyAsString();
+ if (body != null && body.length() > 240) {
body = body.substring(0, 240);
}
- return "status=" + e.statusCode + ", body=" + body;
+ return "status=" + e.getStatusCode().value() + ", body=" + body;
+ }
+ if (ex instanceof WebClientResponseException) {
+ WebClientResponseException e = (WebClientResponseException) ex;
+ String body = e.getResponseBodyAsString();
+ if (body != null && body.length() > 240) {
+ body = body.substring(0, 240);
+ }
+ return "status=" + e.getStatusCode().value() + ", body=" + body;
+ }
+ Integer springAiStatus = llmSpringAiClientService.statusCodeOf(ex);
+ if (springAiStatus != null) {
+ return "status=" + springAiStatus + ", body=" + llmSpringAiClientService.responseBodyOf(ex, 240);
}
return ex.getMessage() == null ? ex.toString() : ex.getMessage();
}
private boolean isQuotaExhausted(Throwable ex) {
- if (!(ex instanceof LlmRouteException)) return false;
- LlmRouteException e = (LlmRouteException) ex;
- if (e.statusCode == 429) return true;
- String text = (e.body == null ? "" : e.body).toLowerCase();
+ Integer status = statusCodeOf(ex);
+ if (status != null && status == 429) {
+ return true;
+ }
+ String text = responseBodyOf(ex);
+ text = text == null ? "" : text.toLowerCase(Locale.ROOT);
return text.contains("insufficient_quota")
|| text.contains("quota")
|| text.contains("浣欓")
@@ -476,98 +432,6 @@
return s == null || s.trim().isEmpty();
}
- private ChatCompletionResponse mergeSseChunk(ChatCompletionResponse acc, String payload) {
- if (payload == null || payload.isEmpty()) return acc;
- String[] events = payload.split("\\r?\\n\\r?\\n");
- for (String part : events) {
- String s = part;
- if (s == null || s.isEmpty()) continue;
- if (s.startsWith("data:")) {
- s = s.substring(5);
- if (s.startsWith(" ")) s = s.substring(1);
- }
- if ("[DONE]".equals(s.trim())) {
- continue;
- }
- try {
- JSONObject obj = JSON.parseObject(s);
- if (obj == null) continue;
- JSONArray choices = obj.getJSONArray("choices");
- if (choices != null && !choices.isEmpty()) {
- JSONObject c0 = choices.getJSONObject(0);
- if (acc.getChoices() == null || acc.getChoices().isEmpty()) {
- ChatCompletionResponse.Choice choice = new ChatCompletionResponse.Choice();
- ChatCompletionRequest.Message msg = new ChatCompletionRequest.Message();
- choice.setMessage(msg);
- ArrayList<ChatCompletionResponse.Choice> list = new ArrayList<>();
- list.add(choice);
- acc.setChoices(list);
- }
- ChatCompletionResponse.Choice choice = acc.getChoices().get(0);
- ChatCompletionRequest.Message msg = choice.getMessage();
- if (msg.getRole() == null || msg.getRole().isEmpty()) {
- msg.setRole("assistant");
- }
- JSONObject delta = c0.getJSONObject("delta");
- if (delta != null) {
- String c = delta.getString("content");
- if (c != null) {
- String prev = msg.getContent();
- msg.setContent(prev == null ? c : prev + c);
- }
- String role = delta.getString("role");
- if (role != null && !role.isEmpty()) msg.setRole(role);
- }
- JSONObject message = c0.getJSONObject("message");
- if (message != null) {
- String c = message.getString("content");
- if (c != null) {
- String prev = msg.getContent();
- msg.setContent(prev == null ? c : prev + c);
- }
- String role = message.getString("role");
- if (role != null && !role.isEmpty()) msg.setRole(role);
- }
- String fr = c0.getString("finish_reason");
- if (fr != null && !fr.isEmpty()) choice.setFinishReason(fr);
- }
- String id = obj.getString("id");
- if (id != null && !id.isEmpty()) acc.setId(id);
- Long created = obj.getLong("created");
- if (created != null) acc.setCreated(created);
- String object = obj.getString("object");
- if (object != null && !object.isEmpty()) acc.setObjectName(object);
- } catch (Exception ignore) {
- }
- }
- return acc;
- }
-
- private ChatCompletionResponse parseCompletion(String payload) {
- if (payload == null) return null;
- try {
- ChatCompletionResponse r = JSON.parseObject(payload, ChatCompletionResponse.class);
- if (r != null && r.getChoices() != null && !r.getChoices().isEmpty() && r.getChoices().get(0).getMessage() != null) {
- return r;
- }
- } catch (Exception ignore) {
- }
- ChatCompletionResponse sse = mergeSseChunk(new ChatCompletionResponse(), payload);
- if (sse.getChoices() != null && !sse.getChoices().isEmpty() && sse.getChoices().get(0).getMessage() != null && sse.getChoices().get(0).getMessage().getContent() != null) {
- return sse;
- }
- ChatCompletionResponse r = new ChatCompletionResponse();
- ChatCompletionResponse.Choice choice = new ChatCompletionResponse.Choice();
- ChatCompletionRequest.Message msg = new ChatCompletionRequest.Message();
- msg.setRole("assistant");
- msg.setContent(payload);
- choice.setMessage(msg);
- ArrayList<ChatCompletionResponse.Choice> list = new ArrayList<>();
- list.add(choice);
- r.setChoices(list);
- return r;
- }
-
private String nextTraceId() {
return UUID.randomUUID().toString().replace("-", "");
}
@@ -588,17 +452,23 @@
}
private Integer statusCodeOf(Throwable ex) {
- if (ex instanceof LlmRouteException) {
- return ((LlmRouteException) ex).statusCode;
+ if (ex instanceof RestClientResponseException) {
+ return ((RestClientResponseException) ex).getStatusCode().value();
}
- return null;
+ if (ex instanceof WebClientResponseException) {
+ return ((WebClientResponseException) ex).getStatusCode().value();
+ }
+ return llmSpringAiClientService.statusCodeOf(ex);
}
private String responseBodyOf(Throwable ex) {
- if (ex instanceof LlmRouteException) {
- return cut(((LlmRouteException) ex).body, LOG_TEXT_LIMIT);
+ if (ex instanceof RestClientResponseException) {
+ return cut(((RestClientResponseException) ex).getResponseBodyAsString(), LOG_TEXT_LIMIT);
}
- return null;
+ if (ex instanceof WebClientResponseException) {
+ return cut(((WebClientResponseException) ex).getResponseBodyAsString(), LOG_TEXT_LIMIT);
+ }
+ return cut(llmSpringAiClientService.responseBodyOf(ex, LOG_TEXT_LIMIT), LOG_TEXT_LIMIT);
}
private String buildResponseText(ChatCompletionResponse resp, String fallbackPayload) {
@@ -634,6 +504,7 @@
Integer httpStatus,
long latencyMs,
ChatCompletionRequest req,
+ ChatCompletionResponse responseObj,
String response,
String switchMode,
Throwable err,
@@ -657,9 +528,40 @@
item.setResponseContent(cut(response, LOG_TEXT_LIMIT));
item.setErrorType(cut(safeName(err), 128));
item.setErrorMessage(err == null ? null : cut(errorText(err), 1024));
- item.setExtra(cut(extra, 512));
+ item.setExtra(cut(buildExtraPayload(responseObj == null ? null : responseObj.getUsage(), extra), 512));
item.setCreateTime(new Date());
llmCallLogService.saveIgnoreError(item);
+ }
+
+ private ChatCompletionResponse usageResponse(ChatCompletionResponse.Usage usage) {
+ if (usage == null) {
+ return null;
+ }
+ ChatCompletionResponse response = new ChatCompletionResponse();
+ response.setUsage(usage);
+ return response;
+ }
+
+ private String buildExtraPayload(ChatCompletionResponse.Usage usage, String extra) {
+ if (usage == null && isBlank(extra)) {
+ return null;
+ }
+ HashMap<String, Object> payload = new HashMap<>();
+ if (usage != null) {
+ if (usage.getPromptTokens() != null) {
+ payload.put("promptTokens", usage.getPromptTokens());
+ }
+ if (usage.getCompletionTokens() != null) {
+ payload.put("completionTokens", usage.getCompletionTokens());
+ }
+ if (usage.getTotalTokens() != null) {
+ payload.put("totalTokens", usage.getTotalTokens());
+ }
+ }
+ if (!isBlank(extra)) {
+ payload.put("note", extra);
+ }
+ return payload.isEmpty() ? null : JSON.toJSONString(payload);
}
private static class CompletionCallResult {
@@ -671,27 +573,6 @@
this.statusCode = statusCode;
this.payload = payload;
this.response = response;
- }
- }
-
- private static class RawCompletionResult {
- private final int statusCode;
- private final String payload;
-
- private RawCompletionResult(int statusCode, String payload) {
- this.statusCode = statusCode;
- this.payload = payload;
- }
- }
-
- private static class LlmRouteException extends RuntimeException {
- private final int statusCode;
- private final String body;
-
- private LlmRouteException(int statusCode, String body) {
- super("http status=" + statusCode);
- this.statusCode = statusCode;
- this.body = body;
}
}
--
Gitblit v1.9.1