feat(v1.2): 阶段2 下半 —— 对话上下文窗口(v2.0.58)

## 命名纪律(需求 §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。
This commit is contained in:
l
2026-10-16 18:06:19 +08:00
parent 76d6445ed6
commit 4effa968ac
4 changed files with 402 additions and 6 deletions

View File

@@ -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)
# ★★ 会话隔离:**一个会话属于一个智能体**(豆包也是这个模型)。
#
# 以前这里完全不看会话的主人是谁,于是用户中途换了智能体之后