diff --git a/src/main/java/com/knowledge/base/infrastructure/util/http/FilteredSseOutputAdapter.java b/src/main/java/com/knowledge/base/infrastructure/util/http/FilteredSseOutputAdapter.java index 0d3a62e..86952f9 100644 --- a/src/main/java/com/knowledge/base/infrastructure/util/http/FilteredSseOutputAdapter.java +++ b/src/main/java/com/knowledge/base/infrastructure/util/http/FilteredSseOutputAdapter.java @@ -1,5 +1,6 @@ package com.knowledge.base.infrastructure.util.http; +import cn.hutool.core.util.StrUtil; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; @@ -22,7 +23,9 @@ public class FilteredSseOutputAdapter implements WriterAdapter { @Override public void writeLine(String line) throws IOException { - if (line == null || line.isBlank()) return; + if (StrUtil.isBlank(line)) { + return; + } if (line.startsWith("data:")) { line = line.substring(5).trim(); @@ -32,19 +35,27 @@ public class FilteredSseOutputAdapter implements WriterAdapter { Map original = mapper.readValue(line, Map.class); Map filtered = new HashMap<>(); - // 累积 textResponse + // textResponse 累积 if (original.containsKey("textResponse")) { filtered.put("textResponse", original.get("textResponse")); lastChunk.put("textResponse", original.get("textResponse")); } - // 如果含有 sources,延迟输出,合并到最后一条 textResponse 中 + // 只缓存 sources,不立即发送 if (original.containsKey("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); emitter.send("data: " + payload + "\n\n"); }