package com.custom.webui.service.impl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.custom.webui.config.props.LlmProperties; import com.custom.webui.config.props.RagProperties; import com.custom.webui.dto.req.ChatMetaRequest; import com.custom.webui.dto.req.MessageUpdateRequest; import com.custom.webui.dto.resp.MessageDTO; import com.custom.webui.dto.resp.RagChunk; import com.custom.webui.dto.resp.StreamEvent; import com.custom.webui.entity.Chat; import com.custom.webui.entity.ChatCollection; import com.custom.webui.entity.Message; import com.custom.webui.exception.BusinessException; import com.custom.webui.entity.RagCollection; import com.custom.webui.entity.UploadFile; import com.custom.webui.entity.ChatCategory; import com.custom.webui.mapper.ChatCategoryMapper; import com.custom.webui.mapper.ChatCollectionMapper; import com.custom.webui.mapper.ChatMapper; import com.custom.webui.mapper.MessageMapper; import com.custom.webui.mapper.RagCollectionMapper; import com.custom.webui.mapper.UploadFileMapper; import com.custom.webui.service.ChatService; import com.custom.webui.service.LlmService; import com.custom.webui.service.MessageService; import com.custom.webui.service.RagProxyService; import com.custom.webui.util.MessageTreeUtil; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.annotation.PreDestroy; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import java.io.IOException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * 消息与流式对话服务实现。 * *

流式对话的完整时序(详见 {@link #streamChat}): *

 *  HTTP 请求进入
 *      │
 *      ├─ 同步:校验会话归属、确定 parentId、落库 user 消息
 *      ├─ 同步:创建 done=0 的 assistant 占位消息(前端拿到 id 立即渲染气泡)
 *      ├─ 同步:返回 SseEmitter(HTTP 头此时已提交为 text/event-stream)
 *      │
 *      └─ 异步(sseExecutor 线程池):
 *             RAG 检索 ──> 组装 prompt ──> 调 LLM 流式接口
 *                                              │
 *                      每收到一块 ──────────────┘──> SSE 推送 delta 事件
 *                                              │
 *                       流结束 ──> 写回完整 content + done=1 ──> 推送 done 事件 ──> complete()
 * 
* *

关键设计决策: *

    *
  1. 占位消息先行落库:让 done=0 成为「生成中」的持久化状态。 * 即使服务端进程崩溃,用户刷新后也能看到那条被中断的消息, * 而不是凭空消失或永远转圈。
  2. *
  3. 定期增量落库:每约 2 秒把已生成的内容写回 DB。 * 代价是少量额外写,收益是进程被 kill 时最多只丢 2 秒内容。
  4. *
  5. 客户端断开即中断生成:onCompletion/onError 回调里 cancel 掉 * 执行流任务的 Future,让 Thread.interrupt 传到 LLM 读取循环, * 及时释放线程 —— 这是防 SSE 内存/线程泄漏的核心。
  6. *
*/ @Slf4j @Service public class MessageServiceImpl implements MessageService { /** 增量落库间隔(毫秒) */ private static final long FLUSH_INTERVAL_MILLIS = 2000L; /** 新建会话的默认标题;标题仍等于它时才用首条提问覆盖 */ private static final String DEFAULT_CHAT_TITLE = "新对话"; /** * 会话标题最大长度(按 Unicode 码点计)。 * 24 个字在侧边栏单行里大约刚好不溢出,再长就会被 CSS 省略号截断 —— * 与其让 CSS 截,不如在后端就截好,前端拿到的标题本身就是完整的短标题。 */ private static final int MAX_TITLE_LENGTH = 24; private final MessageMapper messageMapper; private final ChatMapper chatMapper; private final ChatCollectionMapper chatCollectionMapper; private final RagCollectionMapper ragCollectionMapper; private final ChatCategoryMapper chatCategoryMapper; private final UploadFileMapper uploadFileMapper; private final ChatService chatService; private final LlmService llmService; private final RagProxyService ragProxyService; private final LlmProperties llmProperties; private final RagProperties ragProperties; private final ObjectMapper objectMapper; private final ExecutorService sseExecutor; /** 定时落库线程池,仅做轻量 DB 写入,1 个线程足够 */ private final ScheduledExecutorService flusher; /** * 编程式事务模板。 * *

为什么不用 {@code @Transactional}:{@code streamChat} 需要同步返回 * SseEmitter,不能整体包在事务里(会把 HTTP 请求线程和数据库连接一起挂住几分钟)。 * 因此只有「user 消息 + assistant 占位」这一小段需要原子性, * 用 TransactionTemplate 显式圈定范围最清晰,也避免了同类内部方法 * 自调用导致 @Transactional 失效的经典陷阱。 */ private final TransactionTemplate transactionTemplate; public MessageServiceImpl(MessageMapper messageMapper, ChatMapper chatMapper, ChatCollectionMapper chatCollectionMapper, RagCollectionMapper ragCollectionMapper, ChatCategoryMapper chatCategoryMapper, UploadFileMapper uploadFileMapper, ChatService chatService, LlmService llmService, RagProxyService ragProxyService, LlmProperties llmProperties, RagProperties ragProperties, ObjectMapper objectMapper, PlatformTransactionManager transactionManager, @Qualifier("sseExecutor") ExecutorService sseExecutor) { this.messageMapper = messageMapper; this.chatMapper = chatMapper; this.chatCollectionMapper = chatCollectionMapper; this.ragCollectionMapper = ragCollectionMapper; this.chatCategoryMapper = chatCategoryMapper; this.uploadFileMapper = uploadFileMapper; this.chatService = chatService; this.llmService = llmService; this.ragProxyService = ragProxyService; this.llmProperties = llmProperties; this.ragProperties = ragProperties; this.objectMapper = objectMapper; this.sseExecutor = sseExecutor; this.transactionTemplate = new TransactionTemplate(transactionManager); ThreadFactory tf = r -> { Thread t = new Thread(r, "sse-flusher"); t.setDaemon(true); return t; }; this.flusher = new ScheduledThreadPoolExecutor(1, tf); // 定时任务被取消后立即从队列移除,避免堆积已废弃的 flush 任务 ((ScheduledThreadPoolExecutor) this.flusher).setRemoveOnCancelPolicy(true); } @PreDestroy public void shutdown() { flusher.shutdownNow(); } // ============================================================ // 查询与编辑 // ============================================================ @Override public List getMessageTree(Long userId, Long chatId) { // 先做归属校验,越权直接 404 chatService.requireOwnedChat(userId, chatId); List flat = messageMapper.selectList( Wrappers.lambdaQuery() .eq(Message::getChatId, chatId) .orderByAsc(Message::getCreatedAt) .orderByAsc(Message::getId)); return MessageTreeUtil.buildTree(flat); } @Override @Transactional(rollbackFor = Exception.class) public MessageDTO updateMessage(Long userId, Long chatId, Long messageId, MessageUpdateRequest request) { Message message = requireOwnedMessage(userId, chatId, messageId); Message update = new Message(); update.setId(messageId); update.setContent(request.getContent()); if (request.getModel() != null && !request.getModel().isBlank()) { update.setModel(request.getModel().trim()); } // 手动编辑意味着内容已确定,标记为完成,避免前端一直显示「生成中」 update.setDone(true); messageMapper.updateById(update); // 会话排序需要跟着消息变化走,否则侧边栏顺序会显得错乱 touchChat(chatId); Message refreshed = messageMapper.selectById(messageId); log.info("编辑消息 messageId={} chatId={} 原长度={} 新长度={}", messageId, chatId, message.getContent() == null ? 0 : message.getContent().length(), request.getContent().length()); return MessageTreeUtil.toDto(refreshed); } @Override @Transactional(rollbackFor = Exception.class) public void deleteMessage(Long userId, Long chatId, Long messageId) { requireOwnedMessage(userId, chatId, messageId); // 收集自身 + 全部子孙:删中间节点时后续对话已失去上下文,一并删除更符合直觉 List all = messageMapper.selectList( Wrappers.lambdaQuery().eq(Message::getChatId, chatId)); Map> childrenByParent = new HashMap<>(); for (Message m : all) { if (m.getParentId() != null) { childrenByParent.computeIfAbsent(m.getParentId(), k -> new ArrayList<>()).add(m.getId()); } } List toDelete = new ArrayList<>(); collectSubtree(messageId, childrenByParent, toDelete); if (toDelete.isEmpty()) { return; } messageMapper.deleteBatchIds(toDelete); touchChat(chatId); log.info("删除消息子树 chatId={} rootMessageId={} 共删除 {} 条", chatId, messageId, toDelete.size()); } /** 深度优先收集子树 id(含自身) */ private void collectSubtree(Long rootId, Map> childrenByParent, List acc) { acc.add(rootId); List children = childrenByParent.get(rootId); if (children == null) { return; } for (Long child : children) { collectSubtree(child, childrenByParent, acc); } } @Override public Message requireOwnedMessage(Long userId, Long chatId, Long messageId) { // 先校验会话归属,再校验消息归属,两道关卡都是必要的: // 只校验消息的话,攻击者可以构造「自己的会话 id + 他人的消息 id」组合 chatService.requireOwnedChat(userId, chatId); Message message = messageMapper.selectById(messageId); if (message == null || !message.getChatId().equals(chatId)) { throw BusinessException.notFound("消息不存在"); } return message; } @Override public Long findLeaflessParent(Long chatId) { // 取该会话最新的一条消息作为父节点。 // 注意这里用「最新」而不是「没有子节点的」,因为用户可能在 // 中间分支上继续追问,此时该分支已有子节点但最新消息仍在它的子树里。 List latest = messageMapper.selectList( Wrappers.lambdaQuery() .eq(Message::getChatId, chatId) .orderByDesc(Message::getCreatedAt) .orderByDesc(Message::getId) .last("LIMIT 1")); return latest.isEmpty() ? null : latest.get(0).getId(); } // ============================================================ // SSE 流式对话核心 // ============================================================ @Override public SseEmitter streamChat(Long userId, Long chatId, String content, Long parentId, String modelName, boolean useRag, String imageText, List imageFileIds) { // 允许「只发图片不打字」:有图片时内容可以为空。 // 此时给一个占位文案,否则消息树里会出现一条空白气泡, // 侧边栏标题、检索 query 也都没有着落。 boolean hasImages = imageFileIds != null && !imageFileIds.isEmpty(); if (content == null || content.isBlank()) { if (!hasImages) { throw BusinessException.badRequest("消息内容不能为空"); } content = "[图片]"; } Chat chat = chatService.requireOwnedChat(userId, chatId); ChatMetaRequest meta = chatService.parseMeta(chat); // 确定挂载点:显式指定优先,否则接在当前分支末尾 Long effectiveParentId = parentId != null ? parentId : findLeaflessParent(chatId); if (effectiveParentId != null) { // 校验父消息确实属于该会话,防止挂到别的会话的消息上造成跨会话数据污染 Message parent = messageMapper.selectById(effectiveParentId); if (parent == null || !parent.getChatId().equals(chatId)) { throw BusinessException.badRequest("parentId 不属于当前会话"); } } String effectiveModel = (modelName != null && !modelName.isBlank()) ? modelName.trim() : (meta.getModelName() != null && !meta.getModelName().isBlank() ? meta.getModelName() : llmService.defaultModel()); // 同步落库:user 消息 + assistant 占位消息 PersistResult persisted = persistUserAndPlaceholder( chatId, effectiveParentId, content, effectiveModel, imageText, imageFileIds); // 0L = 永不超时。SSE 连接的生命周期由「流结束」或「客户端断开」决定, // 不由超时决定;设成固定值会在长回答生成到一半时把连接掐断。 // // Spring 实现细节:SseEmitter(0L) 会以 0 延迟提交一个超时任务, // 该任务执行时未必真的触发 onTimeout(ResponseBodyEmitter 内部 // 会检查 timeout 是否为 null)。功能上安全,只是多一次空任务调度。 // 若希望语义更直白,可改用 new SseEmitter(Long.MAX_VALUE)。 SseEmitter emitter = new SseEmitter(0L); AtomicReference> taskRef = new AtomicReference<>(); AtomicBoolean clientGone = new AtomicBoolean(false); // ---- 客户端断开 / 出错 / 正常完成时的资源回收 ---- // 这是防泄漏的关键:EventSource.close() 或页面卸载会触发 onCompletion, // 我们借此中断服务端的生成线程。 emitter.onCompletion(() -> { log.debug("SSE 连接完成 chatId={} messageId={}", chatId, persisted.assistantMessageId()); cancel(taskRef, clientGone, chatId, persisted.assistantMessageId()); }); emitter.onTimeout(() -> { log.warn("SSE 连接超时 chatId={}", chatId); cancel(taskRef, clientGone, chatId, persisted.assistantMessageId()); }); emitter.onError(e -> { log.warn("SSE 连接异常 chatId={} err={}", chatId, e.toString()); cancel(taskRef, clientGone, chatId, persisted.assistantMessageId()); }); // ---- 异步执行生成任务 ---- // sseExecutor 声明为 ExecutorService,因此可以直接 submit 拿到 Future Future task = sseExecutor.submit( () -> runGeneration(emitter, chat, meta, effectiveModel, persisted, useRag, imageText, clientGone)); taskRef.set(task); return emitter; } /** * 真正的生成流程,运行在 sseExecutor 线程上。 * *

这里的每个 catch 分支都必须保证 emitter 被 complete 或 completeWithError, * 否则连接会一直挂在那里直到 Tomcat 回收。 */ private void runGeneration(SseEmitter emitter, Chat chat, ChatMetaRequest meta, String model, PersistResult persisted, boolean useRag, String imageText, AtomicBoolean clientGone) { Long chatId = chat.getId(); Long assistantMessageId = persisted.assistantMessageId(); // 累积区:只在当前生成线程内访问,无需加锁 StringBuilder buffer = new StringBuilder(); AtomicReference lastFlushed = new AtomicReference<>(""); List sources = new ArrayList<>(); java.util.concurrent.ScheduledFuture flushTask = null; try { // 1) start 事件:前端拿到 assistantMessageId,建立占位气泡 send(emitter, "start", StreamEvent.start( chatId, persisted.userMessageId(), assistantMessageId, model)); // 2) 会话标题 // // 放在最前面而不是等流结束:标题只依赖「首条用户提问」, // 与模型输出毫无关系。若等到生成结束再下发,遇到慢模型 // (7B 量化模型在 CPU 上可能跑几十秒)侧边栏会长时间显示「新对话」, // 用户以为没生效。这里在首个 token 之前就定好,零等待。 maybeGenerateTitle(chat, emitter); // 3) RAG 检索 String ragContext = null; if (useRag && ragProperties.isEnabled()) { ragContext = retrieveContext(chatId, persisted.userMessageContent(), sources); } // 4) 组装完整 prompt 上下文(含图片 OCR 文字) List context = buildContext(chat, meta, persisted, ragContext, imageText); // 本轮实际带进去的历史条数(不含 system),随 done 事件下发用于诊断: // 「模型不记得上文」这类问题应当一个请求就能确认,而不是去翻日志 int contextMessages = (int) context.stream() .filter(m -> !Message.ROLE_SYSTEM.equals(m.role())) .count(); // 4) 启动定期落库定时器(进程被 kill 时最多丢 FLUSH_INTERVAL 的内容) flushTask = flusher.scheduleAtFixedRate( () -> flushPartial(assistantMessageId, buffer, lastFlushed), FLUSH_INTERVAL_MILLIS, FLUSH_INTERVAL_MILLIS, TimeUnit.MILLISECONDS); // 5) 调用 LLM 并逐块推送 llmService.streamChat(context, new LlmService.LlmOptions( model, meta.getTemperature(), meta.getTopP(), meta.getNumCtx()), (token, thinking) -> { // thinking 内容不入库,仅实时推给前端展示 if (!thinking) { buffer.append(token); } send(emitter, "delta", StreamEvent.delta(assistantMessageId, token, thinking)); }); // 6) 流结束:写回完整内容,done=1 String fullContent = buffer.toString(); finishAssistantMessage(assistantMessageId, fullContent, buildMetadata(model, sources, chatId)); touchChat(chatId); send(emitter, "done", StreamEvent.done(assistantMessageId, fullContent, sources, contextMessages)); emitter.complete(); } catch (Exception e) { log.error("流式生成失败 chatId={} messageId={}", chatId, assistantMessageId, e); // 把已生成的部分内容落库并标记完成,避免留下永远 done=0 的消息 String partial = buffer.toString(); String errorMessage = friendlyError(e); finalizeOnFailure(assistantMessageId, partial, errorMessage); if (!clientGone.get()) { // 尽力而为地通知前端;此时连接可能已断,send 失败可忽略 send(emitter, "error", StreamEvent.error(errorMessage)); try { emitter.complete(); } catch (Exception ignore) { // 连接已关闭,忽略 } } } finally { if (flushTask != null) { flushTask.cancel(false); } if (clientGone.get()) { log.info("客户端提前断开 chatId={} messageId={} 已保存 {} 字", chatId, assistantMessageId, buffer.length()); } } } // ==================== 落库相关 ==================== /** * 原子地保存 user 消息与 assistant 占位消息。 * *

为什么必须在一个事务里:这两条记录是强关联的。 * 如果只写入 user 消息而 assistant 占位失败,前端会收到一个 * 永远不会有回复的提问;反过来则会凭空出现一条空的 AI 气泡。 * 用 {@link TransactionTemplate} 把两条 insert 圈在同一个事务里, * 任一失败则整体回滚。 * *

assistant 占位消息的 {@code parentId} 指向 user 消息, * 这是消息树能够产生分支的基础:重新生成时会在同一个 user 消息下 * 再插入一条 assistant 消息,两条互为兄弟节点。 */ private PersistResult persistUserAndPlaceholder(Long chatId, Long parentId, String content, String model, String imageText, List imageFileIds) { return transactionTemplate.execute(status -> { Message userMessage = new Message(); userMessage.setChatId(chatId); userMessage.setParentId(parentId); userMessage.setRole(Message.ROLE_USER); userMessage.setContent(content); userMessage.setDone(true); // 用户消息本身就是完整的 // 把图片 id 与 OCR 文字一起记进 metadata。 // 两者都要存: // imageFileIds -> 刷新页面后仍能显示原图 // imageText -> 「重新生成」时能复用图片上下文, // 否则同一个问题重新生成会得到「不知道你在说什么」 if ((imageFileIds != null && !imageFileIds.isEmpty()) || (imageText != null && !imageText.isBlank())) { try { Map imgMeta = new java.util.LinkedHashMap<>(); if (imageFileIds != null && !imageFileIds.isEmpty()) { imgMeta.put("imageFileIds", imageFileIds); } if (imageText != null && !imageText.isBlank()) { // OCR 文本可能很长,按上下文上限截断,避免 metadata 无限膨胀 imgMeta.put("imageText", abbreviate(imageText, ragProperties.getMaxContextChars())); } userMessage.setMetadata(objectMapper.writeValueAsString(imgMeta)); } catch (Exception e) { log.warn("写入图片元数据失败: {}", e.getMessage()); } } userMessage.setCreatedAt(LocalDateTime.now()); messageMapper.insert(userMessage); Message assistant = new Message(); assistant.setChatId(chatId); // assistant 挂在 user 消息下,这是消息树分枝的基础 assistant.setParentId(userMessage.getId()); assistant.setRole(Message.ROLE_ASSISTANT); assistant.setContent(""); assistant.setModel(model); assistant.setDone(false); // 生成中 assistant.setCreatedAt(LocalDateTime.now()); messageMapper.insert(assistant); return new PersistResult(userMessage.getId(), content, assistant.getId()); }); } /** 定期把已生成的内容写回 DB */ private void flushPartial(Long messageId, StringBuilder buffer, AtomicReference lastFlushed) { // StringBuilder 非线程安全:这里用 toString 快照,且容忍瞬时不一致 String snapshot; try { snapshot = buffer.toString(); } catch (Exception e) { return; } if (snapshot.isEmpty() || snapshot.equals(lastFlushed.get())) { return; } try { Message patch = new Message(); patch.setId(messageId); patch.setContent(snapshot); messageMapper.updateById(patch); lastFlushed.set(snapshot); } catch (Exception e) { // 定时落库失败不应影响主流程,丢弃本次快照即可 log.warn("增量落库失败 messageId={} err={}", messageId, e.getMessage()); } } /** * 流正常结束:写完整内容并置 done=1。 * *

不加 {@code @Transactional}:这是单条 update,本身即原子操作; * 而且它由生成线程调用,包事务只会白白多占一个数据库连接。 */ private void finishAssistantMessage(Long messageId, String content, String metadata) { Message patch = new Message(); patch.setId(messageId); patch.setContent(content); patch.setDone(true); patch.setMetadata(metadata); messageMapper.updateById(patch); } /** 流异常结束:保留已生成内容,标记 done=1 并记录错误原因 */ private void finalizeOnFailure(Long messageId, String partial, String errorMessage) { try { Message patch = new Message(); patch.setId(messageId); // 部分内容也保留:用户能看到模型说到一半的内容,比空白更有信息量 patch.setContent(partial.isEmpty() ? "(生成失败:" + errorMessage + ")" : partial); patch.setDone(true); patch.setMetadata(objectMapper.writeValueAsString(Map.of("error", errorMessage))); messageMapper.updateById(patch); } catch (Exception e) { log.error("标记失败消息状态时出错 messageId={}", messageId, e); } } private void touchChat(Long chatId) { try { Chat patch = new Chat(); patch.setId(chatId); patch.setUpdatedAt(LocalDateTime.now()); chatMapper.updateById(patch); } catch (Exception e) { log.warn("更新会话活跃时间失败 chatId={}", chatId); } } // ==================== 上下文组装 ==================== /** * 构造发给 LLM 的完整上下文。 * *

顺序:system prompt(含 RAG 片段)→ 历史对话(当前分支的祖先链)→ 本轮用户输入。 * *

历史只取当前分支的祖先链,这是消息树设计的直接收益: * 用户在不同分支上切换时,模型看到的上下文会随之变化, * 不会把其他分支的内容误当作本次对话的历史。 */ private List buildContext(Chat chat, ChatMetaRequest meta, PersistResult persisted, String ragContext, String imageText) { List context = new ArrayList<>(); // ---- system prompt ---- StringBuilder systemPrompt = new StringBuilder(); if (meta.getSystemPrompt() != null && !meta.getSystemPrompt().isBlank()) { systemPrompt.append(meta.getSystemPrompt().trim()); } if (ragContext != null && !ragContext.isBlank()) { if (!systemPrompt.isEmpty()) { systemPrompt.append("\n\n"); } systemPrompt.append(""" 以下是从用户知识库中检索到的参考资料,每条前面有 [编号] 与来源信息。 请遵守以下规则: 1. 优先依据这些资料回答;如果资料中没有相关信息, 请明确说明「知识库中未找到相关内容」,不要编造。 2. 在引用了某条资料的句子末尾标注对应编号,格式为 [1]、[2], 可同时标注多个,如 [1][3]。编号必须与资料的编号一致。 3. 只标注真正用到的资料,不要为了凑数引用无关资料。 4. 不要复述资料的文件名与章节名,来源会由界面单独展示。 """).append(ragContext); } // ---- 随消息上传的图片内容(OCR 结果)---- // 作为 system 消息注入而不是拼进用户输入: // 这样用户看到的自己那条消息仍是原本的文字,不会被一堆 OCR 文本淹没。 if (imageText != null && !imageText.isBlank()) { if (!systemPrompt.isEmpty()) { systemPrompt.append("\n\n"); } systemPrompt.append(""" 用户随消息上传了图片,以下是图片中的文字内容(由 OCR 识别,可能有识别误差): --- """).append(abbreviate(imageText, llmProperties.getPerPartCharLimit())) .append(""" --- 请结合这些图片内容回答用户的问题。如果用户的问题与图片内容相关, 请直接依据图片中的信息作答;若图片内容与问题无关,不必强行提及。 """); } if (!systemPrompt.isEmpty()) { context.add(new LlmService.LlmMessage(Message.ROLE_SYSTEM, systemPrompt.toString())); } // ---- 历史对话:沿 parentId 回溯当前分支 ---- List history = loadBranchHistory(chat.getId(), persisted.assistantMessageId()); // assistant 占位消息内容为空,过滤掉 List historyMessages = history.stream() .filter(m -> m.getContent() != null && !m.getContent().isBlank()) .filter(m -> Message.ROLE_USER.equals(m.getRole()) || Message.ROLE_ASSISTANT.equals(m.getRole())) .map(m -> new LlmService.LlmMessage(m.getRole(), m.getContent())) .toList(); // ---- 按字符预算装配历史 ---- // // 关键点:**从最近的消息往回装**,装到预算用完为止。 // 之前的实现是「取最近 20 条后全部塞进去」,只受条数限制、 // 不受 token 限制 —— 20 条长回答轻易就能到上万字符, // 加上图片 OCR 文字直接超过 num_ctx,模型服务便从头静默截断, // 把最前面的 system 消息(图片内容、知识库资料)整段丢掉, // 于是「模型好像没看到图片」。这是本项目最难查的一类 bug: // 不报错、不报警,只是模型装作没看见。 // // 后来又踩了第二层坑(用户报「每轮对话都不记得上文」): // 循环从最近一条往前走,而最近一条往往正是模型的**上一条长回答** // (实测 5815 / 8809 字)。它一超过预算,第一次比较就 break, // 整段历史被丢光 —— 模型只收到用户刚问的那一句。 // // 所以现在有两条硬规则: // 1. **本轮提问无条件完整保留**(截断自己的问题等于没问出去) // 2. 预留给历史的额度里,如果**最新一条**放不下,至少截取一段摘要 // (开头 + 结尾),而不是整段放弃 int budget = Math.max(500, llmProperties.getContextCharBudget()); int systemCost = systemPrompt.length(); int remaining = budget - systemCost; // 规则 1:先无条件扣掉本轮提问的额度。 // loadBranchHistory 的终点是 assistant 占位消息(已被过滤), // 因此列表最后一条就是本轮的用户消息。 LlmService.LlmMessage currentTurn = null; int currentTurnCost = 0; if (!historyMessages.isEmpty() && Message.ROLE_USER.equals(historyMessages.get(historyMessages.size() - 1).role())) { currentTurn = historyMessages.get(historyMessages.size() - 1); currentTurnCost = currentTurn.content().length(); remaining -= currentTurnCost; if (remaining < 0) { log.warn("本轮提问本身就超出上下文预算 chatId={} 提问={}字 budget={}," + "仍会完整发送(截断问题等于没问),但本轮不带任何历史对话。" + "如需携带历史请调大 webui.llm.context-char-budget", chat.getId(), currentTurnCost, budget); } } if (remaining <= 0) { // system 部分已占满预算(例如超长 OCR 文字), // 此时优先保住 system —— 它承载本轮的新信息(图片/资料), // 比历史对话重要得多。历史整体放弃,并留下明确日志。 log.warn("system 内容已占满上下文预算 chatId={} systemChars={} budget={}," + "本轮不携带历史对话。可调大 webui.llm.context-char-budget 或 num-ctx", chat.getId(), systemCost, budget); } else { int limit = Math.max(1, llmProperties.getHistoryLimit()); // 本轮提问单独处理,不参与历史条数上限与预算竞争 int endExclusive = currentTurn != null ? historyMessages.size() - 1 : historyMessages.size(); int from = Math.max(0, endExclusive - limit); // 从最近一条往前累加,超出预算就停 java.util.LinkedList picked = new java.util.LinkedList<>(); int used = 0; int excerpted = 0; for (int i = endExclusive - 1; i >= from; i--) { LlmService.LlmMessage msg = historyMessages.get(i); int cost = msg.content() == null ? 0 : msg.content().length(); if (used + cost > remaining) { /* * 放不下。这里**绝不能直接放弃整段历史** —— 这是实测踩到的 * 一个严重 bug: * * 循环是从「最近一条」往前走的,而最近一条通常正是模型上一条 * 回答。本地模型的长回答动辄 4000~9000 字(实测 8809 字), * 一超过预算,第一次比较就 break,picked 里空空如也 —— * 于是「模型收到的上下文里只有用户刚问的那句话」, * 表现为「每轮对话都不记得上文」。 * * 所以:**最新的一条必须留一点**。放不下就截取一段 * (开头 + 结尾),保证模型至少知道上一轮说了什么。 * 更老的条目才允许整条丢弃,这样保留的永远是一段连续的近期对话。 */ if (excerpted == 0) { String excerpt = excerptForContext(msg.content(), remaining - used); if (excerpt != null) { picked.addFirst(new LlmService.LlmMessage(msg.role(), excerpt)); used += excerpt.length(); excerpted++; } } break; } picked.addFirst(msg); used += cost; } context.addAll(picked); // 规则 1 落地:本轮提问完整追加在最后 if (currentTurn != null) { context.add(currentTurn); } int skipped = (endExclusive - from) - picked.size(); if (excerpted > 0) { log.info("历史对话裁剪 chatId={} 保留={} 条(其中最新一条超预算、已截取摘要)丢弃={} 条 " + "(budget={} system={} 已用={})。" + "想让更多历史原样进入上下文,可调大 webui.llm.context-char-budget", chat.getId(), picked.size(), skipped, budget, systemCost, used); } else if (skipped > 0) { log.info("历史对话按字符预算裁剪 chatId={} 保留={} 条 丢弃={} 条 " + "(budget={} system={} 已用={})", chat.getId(), picked.size(), skipped, budget, systemCost, used); } else { log.debug("上下文组装完成 chatId={} system={}字 历史={}条 合计={}字(预算{})", chat.getId(), systemCost, picked.size(), systemCost + used, budget); } } // 最终兜底:万一还是超(例如单条用户消息本身就极长), // 打印一条可定位的告警,避免又变成「静默失效」 int totalChars = systemCost + context.stream() .filter(m -> !Message.ROLE_SYSTEM.equals(m.role())) .mapToInt(m -> m.content() == null ? 0 : m.content().length()) .sum(); if (totalChars > budget) { log.warn("上下文仍超出预算 chatId={} 合计={} 字 > 预算={} 字," + "Ollama 可能从开头截断(system 在最前,风险最高)。" + "请调大 webui.llm.context-char-budget 或 Ollama 的 num_ctx", chat.getId(), totalChars, budget); } return context; } /** * 把一条超长历史消息压成能塞进预算的摘要(开头 + 结尾)。 * *

为什么不直接砍掉后半段(只留开头):用户下一句追问往往针对上一轮回答的 * 结论,只留开头会让模型答非所问;只留结尾又会丢掉问题背景。 * 所以两头都留,中间用省略标记连起来。 * *

预算小到连标记都放不下时返回 {@code null}(调用方会放弃这条)。 * 这里的 {@code MIN_EXCERPT} 保证「摘要至少是一句完整的话」, * 而不是塞进去两三个字占着位置却毫无信息量。 */ private static final int MIN_EXCERPT = 120; private String excerptForContext(String content, int budget) { if (content == null || content.isBlank() || budget < MIN_EXCERPT) { return null; } if (content.length() <= budget) { return content; } String marker = "\n……(此处省略约 " + (content.length() - budget) + " 字)……\n"; int stay = budget - marker.length(); if (stay < MIN_EXCERPT) { // 预算太小,连省略标记都放不下:退化成纯截断,但仍然保留头部 return content.substring(0, Math.max(1, budget)); } // 结尾留 40%:结论更重要,但也要给开头留够背景 int tail = Math.max(MIN_EXCERPT / 2, (int) (stay * 0.4)); int head = stay - tail; return content.substring(0, head) + marker + content.substring(content.length() - tail); } /** * 加载从会话根到指定消息的完整链路。 * *

实现上用一次全量查询 + 内存回溯,而不是递归 SQL: * 单会话消息量通常在数百条量级,一次查询的开销远低于多次 round-trip, * 且逻辑更直观、易测试。消息量真的变大时再切换到递归 CTE 或路径枚举。 */ private List loadBranchHistory(Long chatId, Long leafMessageId) { List all = messageMapper.selectList( Wrappers.lambdaQuery() .eq(Message::getChatId, chatId) .orderByAsc(Message::getCreatedAt) .orderByAsc(Message::getId)); Map byId = new HashMap<>(all.size() * 2); for (Message m : all) { byId.put(m.getId(), m); } return MessageTreeUtil.pathToRoot(byId, leafMessageId); } /** * RAG 检索并填充 sources。 * *

全程容错:知识库检索失败绝不能让对话失败,最差情况退化成纯聊天。 */ private String retrieveContext(Long chatId, String query, List sources) { try { List collections = new ArrayList<>(chatCollectionMapper.selectList( Wrappers.lambdaQuery().eq(ChatCollection::getChatId, chatId)) .stream().map(ChatCollection::getCollectionName).toList()); // 整类绑定:把该会话绑定的分类展开成集合。 // 在这里展开(而不是绑定时写死集合名)的关键收益是 —— // 之后往分类里新增的文档,已有会话能自动检索到。 List boundCategoryIds = chatCategoryMapper.selectList( Wrappers.lambdaQuery().eq(ChatCategory::getChatId, chatId)) .stream().map(ChatCategory::getCategoryId).toList(); if (!boundCategoryIds.isEmpty()) { List fileIds = uploadFileMapper.selectList( Wrappers.lambdaQuery() .select(UploadFile::getId) .in(UploadFile::getCategoryId, boundCategoryIds)) .stream().map(UploadFile::getId).toList(); if (!fileIds.isEmpty()) { for (RagCollection rc : ragCollectionMapper.selectList( Wrappers.lambdaQuery() .in(RagCollection::getFileId, fileIds) .eq(RagCollection::getStatus, RagCollection.STATUS_READY))) { if (!collections.contains(rc.getCollectionName())) { collections.add(rc.getCollectionName()); } } } log.debug("会话 {} 绑定 {} 个分类,展开后共 {} 个集合", chatId, boundCategoryIds.size(), collections.size()); } if (collections.isEmpty()) { log.debug("会话 {} 未绑定知识库,跳过 RAG 检索", chatId); return null; } List chunks = ragProxyService.search( query, collections, ragProperties.getDefaultTopK()); if (chunks.isEmpty()) { return null; } // 向量库里记录的 filename 是磁盘存储名(UUID.ext), // 直接展示会给用户看一串无意义的哈希。这里用集合名反查 // upload_file 表,换成用户上传时的原始文件名。 Map displayNames = resolveDisplayNames(collections); for (RagChunk c : chunks) { StreamEvent.Source s = new StreamEvent.Source(); String displayName = displayNames.get(c.getCollectionName()); s.setFilename(displayName != null ? displayName : c.getFilename()); // 章节:让引用从「文件名」细化到「文档的哪一节」 s.setSection(c.getSection()); s.setScore(c.getScore()); s.setSnippet(abbreviate(c.getText(), 120)); s.setChunkIndex(c.getChunkIndex()); s.setCollectionName(c.getCollectionName()); sources.add(s); } return ragProxyService.buildRagContext(chunks); } catch (Exception e) { log.warn("RAG 检索失败,降级为纯对话 chatId={} err={}", chatId, e.getMessage()); return null; } } /** * 用会话的第一条用户提问作为标题。 * *

触发条件:会话标题仍是默认值「新对话」。已有标题(用户手动改过、 * 或已设置过)则不再覆盖,避免把用户取的名字冲掉。 * *

为什么不再调用 LLM 做摘要? * 早先的实现是把首条提问丢给模型「概括成 15 字标题」,实践下来问题很多: *

* 直接截取首条提问既符合用户预期(「标题就是我说的第一句话」), * 又是零延迟、确定性的行为。因此这里刻意不做任何模型调用。 */ private void maybeGenerateTitle(Chat chat, SseEmitter emitter) { try { if (chat.getTitle() != null && !DEFAULT_CHAT_TITLE.equals(chat.getTitle())) { return; } // 取该会话第一条 user 消息 —— 会话标题就来自它 List firstUserMessages = messageMapper.selectList( Wrappers.lambdaQuery() .eq(Message::getChatId, chat.getId()) .eq(Message::getRole, Message.ROLE_USER) .orderByAsc(Message::getId) .last("LIMIT 1")); if (firstUserMessages.isEmpty()) { return; } String title = buildTitleFromQuestion(firstUserMessages.get(0).getContent()); if (title.isEmpty()) { return; } chatService.updateTitle(chat.getId(), title); send(emitter, "title", StreamEvent.title(chat.getId(), title)); log.info("已用首条提问设置会话标题 chatId={} title={}", chat.getId(), title); } catch (Exception e) { // 取标题失败不该影响对话,记一笔即可 log.warn("设置会话标题失败 chatId={} err={}", chat.getId(), e.getMessage()); } } /** * 把用户提问规整成适合做侧边栏标题的短文本。 * *

处理内容: *

    *
  1. 把连续空白(含换行)压成单个空格 —— 多行提问在侧边栏里 * 只能单行显示,留换行会导致高度异常
  2. *
  3. 去掉首尾空白与成对引号
  4. *
  5. 超过 {@link #MAX_TITLE_LENGTH} 个字符则截断并加省略号
  6. *
* *

注意用 {@code codePointCount} 而非 {@code length()}:Java 的 * {@code String.length()} 数的是 UTF-16 码元,emoji 等增补字符占两个码元, * 直接按 length 截断可能把一个 emoji 劈成两半,产生乱码。 */ private String buildTitleFromQuestion(String question) { if (question == null || question.isBlank()) { return ""; } String title = question.replaceAll("\\s+", " ").trim(); // 去掉模型/用户可能带上的成对引号 title = title.replaceAll("^[\"'“”‘’]+|[\"'“”‘’]+$", "").trim(); if (title.isEmpty()) { return ""; } if (title.codePointCount(0, title.length()) > MAX_TITLE_LENGTH) { int endIndex = title.offsetByCodePoints(0, MAX_TITLE_LENGTH); title = title.substring(0, endIndex) + "…"; } // 兜底:数据库列宽 255,极端情况下再截一层,避免插入报错 return title.length() > 255 ? title.substring(0, 255) : title; } /** * 把「向量集合名」映射到「用户上传时的原始文件名」。 * *

为什么需要这一步:Python 侧写入向量元数据的 filename 是磁盘存储名 * (形如 {@code 496ae5fa...md},由服务端生成以防路径穿越), * 它对用户毫无意义。集合名是确定性的 {@code user_{uid}_file_{fid}}, * 通过 {@code rag_collection -> upload_file} 两跳就能换回可读的名字。 * *

查不到时返回空映射,调用方回退到原始 filename —— 宁可显示哈希, * 也不能因为查库失败而丢掉整条引用信息。 */ private Map resolveDisplayNames(List collectionNames) { if (collectionNames == null || collectionNames.isEmpty()) { return Collections.emptyMap(); } try { List records = ragCollectionMapper.selectList( Wrappers.lambdaQuery() .in(RagCollection::getCollectionName, collectionNames)); if (records.isEmpty()) { return Collections.emptyMap(); } List fileIds = records.stream() .map(RagCollection::getFileId) .filter(Objects::nonNull) .toList(); if (fileIds.isEmpty()) { return Collections.emptyMap(); } Map filenameById = new HashMap<>(); for (UploadFile file : uploadFileMapper.selectBatchIds(fileIds)) { filenameById.put(file.getId(), file.getFilename()); } Map result = new HashMap<>(); for (RagCollection record : records) { String filename = filenameById.get(record.getFileId()); if (filename != null) { result.put(record.getCollectionName(), filename); } } return result; } catch (Exception e) { log.warn("解析文件显示名失败,引用将回退为存储名: {}", e.getMessage()); return Collections.emptyMap(); } } private String buildMetadata(String model, List sources, Long chatId) { try { Map metadata = new HashMap<>(); metadata.put("model", model); metadata.put("finishedAt", LocalDateTime.now().toString()); if (!sources.isEmpty()) { metadata.put("ragSourceCount", sources.size()); metadata.put("ragSources", sources); } return objectMapper.writeValueAsString(metadata); } catch (Exception e) { return null; } } // ==================== SSE 发送与资源回收 ==================== /** * 发送一个 SSE 事件。 * *

客户端断开时 send 会抛 IOException。这里刻意不把它当成致命错误 * 向上抛:让生成循环继续跑完并把内容落库, * 用户刷新页面后仍能看到完整回复,体验优于直接丢弃。 */ private void send(SseEmitter emitter, String eventName, Object payload) { try { emitter.send(SseEmitter.event() .name(eventName) .data(payload, org.springframework.http.MediaType.APPLICATION_JSON)); } catch (IOException | IllegalStateException e) { // IllegalStateException:emitter 已 complete 后再 send log.debug("SSE 发送失败(客户端可能已断开)event={} err={}", eventName, e.getMessage()); } } /** 取消生成任务并标记客户端已离开 */ private void cancel(AtomicReference> taskRef, AtomicBoolean clientGone, Long chatId, Long messageId) { clientGone.set(true); Future task = taskRef.get(); if (task != null && !task.isDone()) { // interrupt 会传到 MockLlmService 的 sleep 与 Ollama 的 socket 读取, // 从而尽快结束线程,避免线程池被废弃连接占满 boolean cancelled = task.cancel(true); log.info("中断流式任务 chatId={} messageId={} cancelled={}", chatId, messageId, cancelled); } } /** 把内部异常翻译成用户能看懂、且能指导下一步操作的提示 */ private String friendlyError(Exception e) { if (e instanceof BusinessException be) { return be.getMessage(); } String msg = e.getMessage(); if (msg != null && msg.contains("Connection refused")) { return "无法连接 LLM 服务,请确认 Ollama 已启动(OLLAMA_HOST=0.0.0.0 ollama serve)"; } return "生成回复时发生错误: " + (msg == null ? e.getClass().getSimpleName() : msg); } private String abbreviate(String s, int max) { if (s == null) { return ""; } String normalized = s.replaceAll("\\s+", " ").trim(); return normalized.length() <= max ? normalized : normalized.substring(0, max) + "..."; } /** * 持久化结果。用 record 承载,避免在多个方法间传递一长串参数。 * * @param userMessageId user 消息 id * @param userMessageContent user 消息内容(RAG 检索的 query) * @param assistantMessageId assistant 占位消息 id */ private record PersistResult(Long userMessageId, String userMessageContent, Long assistantMessageId) { } }