This commit is contained in:
luke 2025-06-23 18:19:08 +08:00
parent bf2363b7ce
commit 69a71dfa43

View File

@ -1,5 +1,6 @@
package com.knowledge.base.infrastructure.util.http; package com.knowledge.base.infrastructure.util.http;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
@ -22,7 +23,9 @@ public class FilteredSseOutputAdapter implements WriterAdapter {
@Override @Override
public void writeLine(String line) throws IOException { public void writeLine(String line) throws IOException {
if (line == null || line.isBlank()) return; if (StrUtil.isBlank(line)) {
return;
}
if (line.startsWith("data:")) { if (line.startsWith("data:")) {
line = line.substring(5).trim(); line = line.substring(5).trim();
@ -32,19 +35,27 @@ public class FilteredSseOutputAdapter implements WriterAdapter {
Map<String, Object> original = mapper.readValue(line, Map.class); Map<String, Object> original = mapper.readValue(line, Map.class);
Map<String, Object> filtered = new HashMap<>(); Map<String, Object> filtered = new HashMap<>();
// 累积 textResponse // textResponse 累积
if (original.containsKey("textResponse")) { if (original.containsKey("textResponse")) {
filtered.put("textResponse", original.get("textResponse")); filtered.put("textResponse", original.get("textResponse"));
lastChunk.put("textResponse", original.get("textResponse")); lastChunk.put("textResponse", original.get("textResponse"));
} }
// 如果含有 sources延迟输出合并到最后一条 textResponse // 只缓存 sources不立即发送
if (original.containsKey("sources")) { if (original.containsKey("sources")) {
lastChunk.put("sources", original.get("sources")); lastChunk.put("sources", original.get("sources"));
return; // 暂不发送
} }
if (!filtered.isEmpty()) { // 最后一条才合并 sources 输出
if (Boolean.TRUE.equals(original.get("close"))) {
// 合并缓存中的 sources
filtered.putAll(lastChunk);
lastChunk.clear(); // 清空缓存
String payload = mapper.writeValueAsString(filtered);
emitter.send("data: " + payload + "\n\n");
} else if (!filtered.isEmpty()) {
// 普通中间片段
String payload = mapper.writeValueAsString(filtered); String payload = mapper.writeValueAsString(filtered);
emitter.send("data: " + payload + "\n\n"); emitter.send("data: " + payload + "\n\n");
} }