| | |
| | | List<LlmService.LlmMessage> 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), |
| | |
| | | buildMetadata(model, sources, chatId)); |
| | | touchChat(chatId); |
| | | |
| | | send(emitter, "done", StreamEvent.done(assistantMessageId, fullContent, sources)); |
| | | send(emitter, "done", |
| | | StreamEvent.done(assistantMessageId, fullContent, sources, contextMessages)); |
| | | |
| | | emitter.complete(); |
| | | |
| | |
| | | // 关键点:**从最近的消息往回装**,装到预算用完为止。 |
| | | // 之前的实现是「取最近 20 条后全部塞进去」,只受条数限制、 |
| | | // 不受 token 限制 —— 20 条长回答轻易就能到上万字符, |
| | | // 加上图片 OCR 文字直接超过 num_ctx,Ollama 便从头静默截断, |
| | | // 加上图片 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 文字), |
| | |
| | | chat.getId(), systemCost, budget); |
| | | } else { |
| | | int limit = Math.max(1, llmProperties.getHistoryLimit()); |
| | | int from = Math.max(0, historyMessages.size() - limit); |
| | | // 本轮提问单独处理,不参与历史条数上限与预算竞争 |
| | | int endExclusive = currentTurn != null ? historyMessages.size() - 1 : historyMessages.size(); |
| | | int from = Math.max(0, endExclusive - limit); |
| | | |
| | | // 从最近一条往前累加,超出预算就停 |
| | | java.util.LinkedList<LlmService.LlmMessage> picked = new java.util.LinkedList<>(); |
| | | int used = 0; |
| | | for (int i = historyMessages.size() - 1; i >= from; i--) { |
| | | 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); |
| | |
| | | } |
| | | |
| | | context.addAll(picked); |
| | | // 规则 1 落地:本轮提问完整追加在最后 |
| | | if (currentTurn != null) { |
| | | context.add(currentTurn); |
| | | } |
| | | |
| | | int skipped = (historyMessages.size() - from) - picked.size(); |
| | | if (skipped > 0) { |
| | | 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); |
| | |
| | | } |
| | | |
| | | /** |
| | | * 把一条超长历史消息压成能塞进预算的摘要(开头 + 结尾)。 |
| | | * |
| | | * <p>为什么不直接砍掉后半段(只留开头):用户下一句追问往往针对上一轮回答的 |
| | | * <b>结论</b>,只留开头会让模型答非所问;只留结尾又会丢掉问题背景。 |
| | | * 所以两头都留,中间用省略标记连起来。 |
| | | * |
| | | * <p>预算小到连标记都放不下时返回 {@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); |
| | | } |
| | | |
| | | /** |
| | | * 加载从会话根到指定消息的完整链路。 |
| | | * |
| | | * <p>实现上用一次全量查询 + 内存回溯,而不是递归 SQL: |