From 4effa968ac89f45e765068c9506f2aa6f203f1ee Mon Sep 17 00:00:00 2001 From: l Date: Fri, 16 Oct 2026 18:06:19 +0800 Subject: [PATCH] =?UTF-8?q?feat(v1.2):=20=E9=98=B6=E6=AE=B52=20=E4=B8=8B?= =?UTF-8?q?=E5=8D=8A=20=E2=80=94=E2=80=94=20=E5=AF=B9=E8=AF=9D=E4=B8=8A?= =?UTF-8?q?=E4=B8=8B=E6=96=87=E7=AA=97=E5=8F=A3=EF=BC=88v2.0.58=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 命名纪律(需求 §4.3 特别强调) 「记忆注入窗口」(塞多少条记忆,超出降级为可检索) vs「上下文窗口」(送多少轮对话,超出直接丢弃)。 两个像但完全不同,文档和 UI 都不许混用。 ## 四条规则 1. 窗口 = 最近 N 轮 + 重要标记消息(N 默认 20,按智能体可配) 2. 重要标记**破格永久携带**,按**原始时间序插回**(塞最前面会打乱因果) 3. **成批对齐裁剪**:超 1/3/4 轮不裁,超 5 裁 5、超 7 裁 5、超 12 裁 10 4. **字节冻结**:送进模型的历史永不原地改,每次新建对象 ## ★ 第 3 条为什么这么设计 「超一点就裁一点」看起来更精确,但那样**每轮裁剪边界都在变**, 前缀每轮都不一样,**上下文缓存一次都命中不了** —— 比不裁还贵。 而且界面上完全看不出来(功能是对的、只是变慢了)。这是那种 "只有算过账才知道该怎么做"的决定。 ## 为什么超出就丢、不做摘要 需求原话。三层原因:摘要自己也要一次 LLM 调用(比省下的 token 贵); 摘要丢信息且不可追溯(用户以为 AI"忘了"是 bug); 该记的走 memory_add 进记忆系统(那里有检索/署名/置顶,是为长期记忆设计的)。 ## 实现 新增 `kernel/context_window.py`(纯函数,好测):`split_rounds` / `_indexed_rounds` / `trim` / `resolve` / `strip_for_model` / `describe`。 `_perform_chat` 里接线:先只做过滤(那时还不知道是谁), 等 `agent` 解析出来再按"智能体 > 全局 > 默认"算窗口大小。 ## 验证 新增 `scripts/probe-context-window.py`,7 节 40+ 项: 成批对齐六种超出量、裁完无孤立 assistant 且条数为偶数、 重要标记捞回且按原始序、resolve 优先级与上下限、字节冻结(原对象零改动)。 ★ 写探针时我自己错了三次(`split_rounds` 返回形状、把只标了 user 的当成两条、 用 `!=` 比内容而不是身份)—— 每次都探针先红。这块边界确实多。 六个探针全绿。界面侧(用量页缓存列、命中单价、消息操作栏的标记重要、 上下文窗口设置)按需求 §6.1 的分工进阶段 5。 --- android/app/build.gradle.kts | 4 +- android/kernel/app.py | 28 +++- android/kernel/context_window.py | 230 +++++++++++++++++++++++++++++++ scripts/probe-context-window.py | 146 ++++++++++++++++++++ 4 files changed, 402 insertions(+), 6 deletions(-) create mode 100644 android/kernel/context_window.py create mode 100644 scripts/probe-context-window.py diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 652091e..84b9069 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -30,8 +30,8 @@ android { * versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装", * 改小了会装不上)。 */ - versionCode = 257 - versionName = "2.0.57" + versionCode = 258 + versionName = "2.0.58" ndk { // Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份 diff --git a/android/kernel/app.py b/android/kernel/app.py index 19f123b..1b8af64 100644 --- a/android/kernel/app.py +++ b/android/kernel/app.py @@ -1,4 +1,4 @@ -""" +""" HTTP 路由:把 Node 版 server/src/index.mjs 的接口逐条搬到 stdlib 上。 用的是 http.server.ThreadingHTTPServer + BaseHTTPRequestHandler: @@ -42,6 +42,7 @@ import timeouts import agentdb import agent_api import agent_context +import context_window import tools_runtime import uploads from defaults import PROVIDER_PRESETS @@ -1653,9 +1654,10 @@ class KernelHandler(BaseHTTPRequestHandler): existing = store.get_conversation(conversation_id) or {} history_source = body.get('history') if isinstance(body.get('history'), list) else \ existing.get('messages') or [] - history = [ - {'role': m.get('role'), 'content': m.get('content')} - for m in history_source + # ★ 先只做**过滤**,真正的窗口裁剪放到下面(`agent` 解析之后)—— + # 因为窗口大小是**按智能体配**的(需求 4.3),这里还不知道是谁。 + raw_history = [ + m for m in history_source if isinstance(m, dict) and m.get('role') in ('user', 'assistant') ] @@ -1683,6 +1685,24 @@ class KernelHandler(BaseHTTPRequestHandler): agent = store.get_agent(body.get('agentId')) or store.get_agent(settings.get('activeAgentId')) agent_id = (agent or {}).get('id') or '' + # ★★ 对话上下文窗口(需求 v1.2 §4.3)。 + # + # 只把"最近 N 轮 + 用户标了重要的那几条"送进模型。 + # 超出的**直接丢弃、不做摘要**(需求原话)—— 沉淀走记忆系统, + # 不搞第二套摘要管线(摘要自己也要花一次调用,还会丢信息且不可追溯)。 + # + # ★ 命名:这里叫「上下文窗口」,和记忆侧的「记忆注入窗口」不是一回事。 + # 后者管"塞多少条记忆",超出部分**还能 memory_search 搜到**; + # 这里管"送几轮对话",超出就真的不送了。 + # + # ★ `strip_for_model` 是**新建** dict,不原地改历史 —— + # 改一个字,从那儿往后的前缀缓存全废(需求 4.3 的"字节冻结")。 + win_rounds, win_batch = context_window.resolve(settings, agent) + window = context_window.trim(raw_history, win_rounds, win_batch) + history = [context_window.strip_for_model(m) for m in window['messages']] + if window.get('reason'): + print(f'[context] {context_window.describe(window)}', file=sys.stderr) + # ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。 # # 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后 diff --git a/android/kernel/context_window.py b/android/kernel/context_window.py new file mode 100644 index 0000000..60b738f --- /dev/null +++ b/android/kernel/context_window.py @@ -0,0 +1,230 @@ +"""对话上下文窗口(需求 v1.2 §4.3)。 + +## 命名纪律 + +需求里特别强调了一句,照抄过来: + +> 记忆侧叫「**记忆注入窗口**」,对话侧叫「**上下文窗口**」,文档与 UI 永不混用。 + +两个东西确实像但完全不同: + + · 记忆注入窗口(§3.2)—— 每轮往 system prompt 里塞**多少条记忆**, + 超出部分**降级为可检索**(AI 还能 memory_search 找到) + · 对话上下文窗口(§4.3)—— 往模型送**最近多少轮对话**, + 超出部分**直接丢弃、不做摘要**(沉淀走记忆系统,不搞第二套摘要管线) + +混着叫的话,用户问"我调窗口怎么没用"时你都不知道他调的是哪个。 + +## 四条规则 + +1. **窗口 = 最近 N 轮 + 重要标记消息**(N 默认 20,按智能体配置) +2. **重要标记只有用户能打**(AI 有 memory_add,标记是用户主权)。 + 被标记的消息**破格永久携带**,按**原始时间序**插回去 —— + 不是塞到最前面:那会打乱因果,模型会看到"先发生的事在后面"。 +3. **成批对齐裁剪**:不是"超一点就裁一点",而是攒够一批才裁一批。 + 目的是**摊薄前缀缓存失效次数** —— 每轮都裁的话,前缀每轮都变, + 上下文缓存一次都命中不了,比不裁还贵。 +4. **字节冻结**:送进去的历史消息**永不原地修改**。 + 改一个字,从那个字往后的前缀缓存全废。 + +## 为什么"直接丢弃、不做摘要" + +需求原话。看起来粗暴,但想清楚了: + + · 摘要本身要花一次 LLM 调用(比省下的那点 token 还贵) + · 而且摘要会**丢信息且不可追溯** —— 用户翻到三个月前那句话还在界面上, + 但模型完全不知道,他会以为 AI"忘了"是 bug + · 该记住的东西本来就该走 `memory_add` 进记忆系统(那里有检索、有署名、 + 有置顶,是**为长期记忆设计的**)。两套摘要管线只会互相打架。 +""" +import os + +#: 默认窗口(轮)。需求定的 20。 +DEFAULT_ROUNDS = 20 + +#: 默认裁剪批量(轮)。需求定的 5。 +DEFAULT_BATCH = 5 + +#: 窗口上限/下限(用户填什么都不至于把上下文搞爆或搞没) +MIN_ROUNDS = 4 +MAX_ROUNDS = 200 + + +def resolve(settings: dict, agent: dict = None) -> tuple: + """ + 算出这次该用多少:**智能体配置 > 全局设置 > 默认**(返回 `(轮数, 批量)`)。 + + ★ 和 provider_info / voice_for 一个套路:智能体可以单独配, + 没配就继承全局。三处规则长得一样,但**不能合并**(数据来源不同)。 + """ + agent = agent or {} + settings = settings or {} + + def pick(key, default, lo, hi): + for src in (agent.get(key), settings.get(key)): + try: + v = int(float(src)) + except (TypeError, ValueError): + continue + if v > 0: + return max(lo, min(hi, v)) + return default + + rounds = pick('contextWindow', DEFAULT_ROUNDS, MIN_ROUNDS, MAX_ROUNDS) + batch = pick('contextBatch', DEFAULT_BATCH, 1, 50) + return rounds, batch + + +def split_rounds(messages: list) -> list: + """ + 把消息流切成"轮"。 + + ★ 一轮 = 从一条 user 到**下一条 user 之前**(含它后面的 assistant 和 + 任何工具痕迹)。不用"user/assistant 配对"来切,是因为: + · 工具调用会产生 assistant → tool → assistant 这种多段结构 + · 界面上用户也可能连发两条 + 按 user 划线对这两种都稳,而且**永远不会切出半轮**(需求要求 + "按完整轮对齐,不裁半轮")。 + """ + groups = [] + cur = [] + for m in messages or []: + if not isinstance(m, dict): + continue + if m.get('role') == 'user' and cur: + groups.append(cur) + cur = [] + cur.append(m) + if cur: + groups.append(cur) + return groups + + +def _indexed_rounds(msgs: list) -> list: + """ + 和 `split_rounds` 一样切轮,但**每条带原始下标** `[(i, msg)]`。 + + ★ 为什么需要下标:被裁掉的那批里如果有"用户标了重要"的消息, + 得把它**按原始时间序插回**去 —— 没有下标就只能塞最前面, + 而那会打乱因果(模型会看到"先发生的事在后面")。 + """ + groups = [] + cur = [] + for i, m in enumerate(msgs): + if m.get('role') == 'user' and cur: + groups.append(cur) + cur = [] + cur.append((i, m)) + if cur: + groups.append(cur) + return groups + + +def trim(messages: list, rounds: int, batch: int = DEFAULT_BATCH) -> dict: + """ + 按窗口裁历史,返回一份**报告**: + + { + 'messages': 送进模型的那一串(裁过的,或原样), + 'kept': 保留几条, + 'dropped': 丢了几条, + 'reason': '' | 'window' | 'within_batch', + 'rounds': 总轮数, 'keptRounds': 保留几轮, + } + + ★ 返回报告而不是只返回列表:调用方要能把这几个数**写给界面** + ("这次带了 18 轮进来"),也是探针唯一能断言的抓手。 + """ + msgs = [m for m in (messages or []) if isinstance(m, dict)] + total = len(msgs) + groups = _indexed_rounds(msgs) + + keep_all = { + 'messages': msgs, 'kept': total, 'dropped': 0, 'reason': '', + 'rounds': len(groups), 'keptRounds': len(groups), + } + if rounds <= 0 or len(groups) <= rounds: + return keep_all + + extra = len(groups) - rounds + # ★ 成批对齐:超出量不到一批就先忍着。 + # 代价是"实际保留的比窗口多几轮",换来的是**前缀缓存能连续命中**。 + # 每轮都裁的话前缀每轮都变,缓存一次都命中不了 —— 那比多带几轮贵得多。 + if extra < batch: + out = dict(keep_all) + out['reason'] = 'within_batch' + out['rounds'] = len(groups) + return out + + cut = (extra // batch) * batch + kept_idx = [pair for g in groups[cut:] for pair in g] + dropped_idx = [pair for g in groups[:cut] for pair in g] + + # ★ 重要标记**破格永久携带**(需求 4.3):从被裁的那批里捞回来 + important = [pair for pair in dropped_idx if pair[1].get('important')] + + merged = sorted(kept_idx + important, key=lambda p: p[0]) + out_msgs = [m for _, m in merged] + return { + 'messages': out_msgs, + 'kept': len(out_msgs), + 'dropped': total - len(out_msgs), + 'reason': 'window', + 'rounds': len(groups), + 'keptRounds': len(groups) - cut, + 'rescued': len(important), + } + + +def describe(report: dict) -> str: + """给界面/日志的一行话(不要让它各处自己拼)""" + r = report or {} + total = r.get('rounds') or 0 + if not r.get('reason'): + return f'{total} 轮全部带上' + if r.get('reason') == 'within_batch': + return f'{total} 轮(超出窗口但没攒够一批,先不动)' + bits = [f'带了最近 {r.get("keptRounds")} 轮(共 {total} 轮)'] + if r.get('rescued'): + bits.append(f'其中 {r["rescued"]} 条是你标了重要的') + if r.get('dropped'): + bits.append(f'另有 {r["dropped"]} 条较早的没带进来') + return ','.join(bits) + + +# --------------------------------------------------------------------------- # +# 重要标记(需求 4.3:**只有用户能打**) +# --------------------------------------------------------------------------- # + +def is_important(msg: dict) -> bool: + return bool((msg or {}).get('important')) + + +def can_mark(role: str) -> bool: + """ + 谁能打这个标记。**只有界面(用户)** —— AI 没有这个工具(需求原话 + "AI 有 memory_add,标记是用户主权")。 + + ★ 这个函数存在的意义是"写下来":将来有人想给 AI 加个 mark_important + 工具时,会先看到这里写着为什么不行。 + """ + return role == 'user' + + +def strip_for_model(msg: dict) -> dict: + """ + 把一条消息变成**送进模型的样子**:只留 role / content。 + + ★★ 顺带就是"字节冻结"的落点:**永远新建一个 dict,绝不原地改** —— + 原地改(哪怕只是删掉一个 `important` 字段)会让那一条的字节变化, + 而从它往后的前缀缓存全部失效。需求 4.3 把这条写成"内核纪律"。 + """ + m = msg or {} + return {'role': m.get('role'), 'content': m.get('content')} + + +__all__ = [ + 'DEFAULT_ROUNDS', 'DEFAULT_BATCH', 'MIN_ROUNDS', 'MAX_ROUNDS', + 'resolve', 'split_rounds', 'trim', 'describe', 'is_important', + 'can_mark', 'strip_for_model', +] diff --git a/scripts/probe-context-window.py b/scripts/probe-context-window.py new file mode 100644 index 0000000..94e1f26 --- /dev/null +++ b/scripts/probe-context-window.py @@ -0,0 +1,146 @@ +"""对话上下文窗口的探针(v1.2 §4.3)。 + +纯函数,所以能逐条钉死。重点在**成批对齐**那条 —— 它最容易实现成 +"超一点就裁一点",那样每轮前缀都变、缓存一次都命中不了, +**比不裁还贵**,而且从界面上完全看不出来(功能是对的、只是变慢了)。 + +用法:`python scripts/probe-context-window.py` +""" +import os +import sys +import tempfile + +try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") +except Exception: + pass + +HERE = os.path.dirname(os.path.abspath(__file__)) +REPO = os.path.abspath(os.path.join(HERE, "..")) +os.environ["DOUBAO_DATA"] = tempfile.mkdtemp(prefix="doubao-ctx-") +sys.path.insert(0, os.path.join(REPO, "android", "kernel")) + +fails = [] + + +def check(label, cond, detail=""): + if cond: + print(f" ✓ {label}") + else: + fails.append(label) + print(f" ✗ {label} {detail}") + + +import context_window as W # noqa: E402 + + +def convo(n, important_at=()): + """造 n 轮对话(每轮 user + assistant);important_at 里的轮号标成重要""" + out = [] + for i in range(n): + out.append({'role': 'user', 'content': f'问{i}', + 'important': i in important_at}) + out.append({'role': 'assistant', 'content': f'答{i}'}) + return out + + +def rounds_of(msgs): + """数一下这批消息里有几轮(受支持的最长连续)""" + return len(W.split_rounds(msgs)) + + +def main(): + print("\n=== 1. 没超窗口:全带 ===") + r = W.trim(convo(5), rounds=20) + check("5 轮 < 20 轮 → 全带", r['kept'] == 10 and r['dropped'] == 0, str(r)) + check("reason 是空(没动过)", r['reason'] == '', str(r['reason'])) + + print("\n=== 2. ★ 成批对齐:超一点**不裁**(这条最容易做错)===") + # + # 窗口 20、批量 5:21 轮时超出 1 轮 —— 应当**原样放行**。 + # 实现成"超了就裁"的话,每轮都会裁掉一条 → 前缀每轮都变 → 缓存全废。 + for extra, should_cut in ((1, False), (3, False), (4, False), (5, True), (7, True), (12, True)): + n = 20 + extra + r = W.trim(convo(n), rounds=20, batch=5) + cut = r['reason'] == 'window' + check(f"{n} 轮(超 {extra} 轮)→ {'裁' if should_cut else '先不动'}", + cut == should_cut, f"reason={r['reason']} kept={r['kept']}") + # 裁的时候要对齐到 batch 的倍数 + r = W.trim(convo(27), rounds=20, batch=5) + check("27 轮(超 7)→ 裁 5 轮留 22 轮", r['keptRounds'] == 22, str(r)) + r = W.trim(convo(32), rounds=20, batch=5) + check("32 轮(超 12)→ 裁 10 轮留 22 轮", r['keptRounds'] == 22, str(r)) + r = W.trim(convo(25), rounds=20, batch=5) + check("25 轮(超 5)→ 正好裁 5 轮留 20 轮", r['keptRounds'] == 20, str(r)) + + print("\n=== 3. 按完整轮对齐,绝不裁半轮 ===") + for n in (21, 25, 27, 32, 50): + r = W.trim(convo(n), rounds=20, batch=5) + msgs = r['messages'] + # 一条 assistant 前面必须紧跟着它那一轮的 user + bad = [i for i, m in enumerate(msgs) + if m['role'] == 'assistant' and (i == 0 or msgs[i - 1]['role'] != 'user')] + check(f"{n} 轮裁完没有孤立的 assistant", not bad, str(bad[:3])) + # 保留的条数必须是偶数(整轮) + check(f"{n} 轮裁完是整轮(条数是偶数)", len(msgs) % 2 == 0, str(len(msgs))) + + print("\n=== 4. 重要标记:破格携带、按原始时间序插回 ===") + # 第 1、3 轮的 **user 消息**标了重要(assistant 没标)—— 它们会被裁掉 + r = W.trim(convo(30, important_at={1, 3}), rounds=20, batch=5) + msgs = r['messages'] + contents = [m['content'] for m in msgs] + check("裁掉的那批里的重要消息被捞回来了", r.get('rescued') == 2, str(r.get('rescued'))) + check("捞回来的在结果里", '问1' in contents and '问3' in contents, str(contents[:6])) + # ★ 关键:**按原始时间序**插回,不是塞到最前面 + check("**按原始时间序插入,不是塞到最前面**", + contents.index('问1') < contents.index('问10'), + f"问1 在 {contents.index('问1')}、问10 在 {contents.index('问10')}") + check("顺序整体单调(捞回的没打乱因果)", + contents.index('问1') < contents.index('问3') < contents.index('问10'), + str([contents.index(x) for x in ('问1', '问3', '问10')])) + # 没标重要的那批就真的丢了 + check("没标记的轮次确实丢了(不做摘要、不假装记得)", '问0' not in contents) + + print("\n=== 5. resolve:智能体 > 全局 > 默认 ===") + check("都没配用默认 20/5", W.resolve({}, {}) == (20, 5), str(W.resolve({}, {}))) + check("全局配了就用全局", W.resolve({'contextWindow': 30, 'contextBatch': 3}, {}) == (30, 3)) + check("智能体配了压过全局", + W.resolve({'contextWindow': 30}, {'contextWindow': 10})[0] == 10) + check("超出上下限会被夹住", W.resolve({'contextWindow': 99999}, {})[0] == W.MAX_ROUNDS) + check("填 0 / 乱填回落到默认", + W.resolve({'contextWindow': 0}, {})[0] == 20 and W.resolve({'contextWindow': 'x'}, {})[0] == 20) + + print("\n=== 6. ★ 字节冻结:绝不原地改历史 ===") + src = [{'role': 'user', 'content': '原话', 'important': True, 'usage': {'input': 5}}] + snapshot = [dict(m) for m in src] + out = W.strip_for_model(src[0]) + check("输出只留 role/content(界面字段不带进模型)", + set(out.keys()) == {'role', 'content'}, str(sorted(out))) + check("**原对象一个字节都没动**", src == snapshot, str(src)) + check("输出是**新对象**(不是同一个引用)", out is not src[0]) + r = W.trim(src, rounds=20) + check("trim 不改原列表的元素(字节冻结)", src == snapshot, str(src)) + # ★ 这里比的是**身份**不是内容:内容本来就该一样,要确认的是 + # 返回的是一个**新列表**(调用方拿到之后改它,不能影响到传进去的那个) + check("trim 返回的是新列表(不是同一个引用)", r['messages'] is not src) + + print("\n=== 7. 边界 ===") + check("空历史不炸", W.trim([], 20)['kept'] == 0) + check("rounds=0 表示不限", W.trim(convo(100), 0)['dropped'] == 0) + check("全是 user(没有 assistant)也能切轮", + W.split_rounds([{'role': 'user', 'content': 'a'}, {'role': 'user', 'content': 'b'}]).__len__() == 2) + check("非 dict 的东西被跳过", W.trim([{'role': 'user'}, 'noise', None], 20)['kept'] == 1) + check("describe 不炸", isinstance(W.describe(W.trim(convo(30), 20, 5)), str)) + + print() + if fails: + print(f"❌ {len(fails)} 项不合格:") + for f in fails: + print(" -", f) + return 1 + print("✅ 全部通过") + return 0 + + +if __name__ == "__main__": + sys.exit(main())