feat(v1.2): 阶段2 上半 —— 缓存友好段序 + 缓存统计归一化(v2.0.57)

## 缓存友好段序(附录 C 的 v1.2 修订)

主流模型的上下文缓存是**前缀匹配**:一处不同则其后全部失效。
原来的段序把 `<emotion>` 夹在 `<memory>` **前面** —— 情绪一变,
连最长的 memory 段一起失效,而情绪是 AI 每聊几句就可能改的东西。

按稳定性重排:
  稳定前缀  {prompt} → <skills> → <worldview> → <memory>
  易变尾巴  <stats> → <status> → <emotion> → <peer_emotions>

顺带把 `<stats>`/`<status>` 两个占位段位留好(阶段 3 实现)。先留是为了让
模板和渲染两边**一开始就一致**,否则会有"模板里有、渲染不管"的中间状态,
表现是提示词里原样留着 `{stats}` 大括号。

★ 这是整个 v1.2 里**改动最小、省的钱最多**的一处。

## 缓存统计归一化

三家的字段名完全不同,且后两家**只给命中**、未命中要自己推:
  DeepSeek  prompt_cache_hit_tokens / prompt_cache_miss_tokens
  Claude    cache_read_input_tokens
  OpenAI    prompt_tokens_details.cached_tokens(嵌套)

不归一化的话,界面上那个"缓存命中率"会因为换模型就**静默变成 0** ——
静默的 0 最难发现。都没给时返回 0/0,界面**不显示**那一列,
而不是显示一个假的 0%。

落库:`token_usage` 加 `cache_hit`/`cache_miss` 两列 + 老库迁移。
接口:`_usage_payload` 和 `get_token_usage` 都带上了。

## 验证

探针新增两节 17 项:段序 7 项(含"模板顺序必须和 SECTIONS 一致"、
"空段不能留裸占位符")+ 缓存 10 项(四种格式、跨提供商累加、
落库查询、老库迁移)。

★ 顺带证明了一件事:段序一改,探针第 8 节那条**记着旧顺序**的老断言
立刻变红。顺序是协议的一部分,改它就该有人拦。

五个探针全绿。阶段 2 下半(对话上下文窗口 + 用量界面缓存列)下一轮。
This commit is contained in:
l
2026-10-16 18:02:14 +08:00
parent b55ce63c6e
commit 76d6445ed6
9 changed files with 266 additions and 24 deletions

View File

@@ -109,6 +109,12 @@ CREATE TABLE IF NOT EXISTS token_usage (
model TEXT NOT NULL DEFAULT '',
input INTEGER NOT NULL DEFAULT 0,
output INTEGER NOT NULL DEFAULT 0,
-- v1.2:缓存命中 / 未命中。各家的字段名完全不同,存进来的是
-- agent_loop.cache_pair() **归一化之后**的两个数。
-- 都是 0 表示"这家没提供缓存信息"——界面据此**不显示**那一列,
-- 而不是显示一个假的 0%(那是误导)。
cache_hit INTEGER NOT NULL DEFAULT 0,
cache_miss INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_token_agent ON token_usage(agent_id);
@@ -159,6 +165,14 @@ def _migrate(conn) -> None:
# 老数据的自由文本 → text;preset 全是默认的「平常」
conn.execute('UPDATE emotions SET text = emotion')
# v1.2 第二条:token_usage 加缓存两列(老库没有,读的时候会 no such column)
tcols = {r['name'] for r in conn.execute('PRAGMA table_info(token_usage)').fetchall()}
if tcols:
if 'cache_hit' not in tcols:
conn.execute('ALTER TABLE token_usage ADD COLUMN cache_hit INTEGER NOT NULL DEFAULT 0')
if 'cache_miss' not in tcols:
conn.execute('ALTER TABLE token_usage ADD COLUMN cache_miss INTEGER NOT NULL DEFAULT 0')
#: v1.2 情绪的五档枚举(需求 3.5)。
#:
@@ -475,20 +489,26 @@ def peer_emotions(worldview_id: str, exclude_agent: str, agent_ids: list) -> lis
# Token 统计
# --------------------------------------------------------------------------- #
def token_add(agent_id: str, model: str, input_tokens: int, output_tokens: int) -> None:
def token_add(agent_id: str, model: str, input_tokens: int, output_tokens: int,
cache_hit: int = 0, cache_miss: int = 0) -> None:
"""
记一次消耗。
★ 输入 / 输出**分开记**(需求 3.1),而且按**模型**分桶 ——
"按模型"是靠每行带 model 名做到的:桶是查询时 group by 出来的,
不是提前建好的。这样换模型不会有"桶没建好"的问题。
★ v1.2 多两个参数:缓存命中 / 未命中。**默认 0** 是有意的 ——
`agent_loop.cache_pair()` 归一化之后如果两家都没给,就是 0/0,
界面据此不显示那一列(显示假的 0% 是误导)。
"""
init()
conn = _connect()
conn.execute(
'INSERT INTO token_usage (agent_id, model, input, output, created_at) '
'VALUES (?, ?, ?, ?, ?)',
(agent_id or '', model or '', int(input_tokens or 0), int(output_tokens or 0), now_iso()),
'INSERT INTO token_usage (agent_id, model, input, output, cache_hit, cache_miss, created_at) '
'VALUES (?, ?, ?, ?, ?, ?, ?)',
(agent_id or '', model or '', int(input_tokens or 0), int(output_tokens or 0),
int(cache_hit or 0), int(cache_miss or 0), now_iso()),
)
conn.commit()
@@ -497,23 +517,36 @@ def token_usage(agent_id: str) -> dict:
"""
这个智能体的累计用量。
返回 `{'total': {'input':..,'output':..}, 'byModel': [{'model':..,'input':..,'output':..}]}`
返回 `{'total': {input, output, cacheHit, cacheMiss},
'byModel': [{model, input, output, cacheHit, cacheMiss}]}`
★ 缓存那两个数是 v1.2 加的;全为 0 时界面**不显示**那一列 ——
不是每家提供商都返回缓存信息,显示一个恒为 0 的"命中率"是误导。
"""
init()
conn = _connect()
rows = conn.execute(
'SELECT model, SUM(input) AS i, SUM(output) AS o FROM token_usage '
'SELECT model, SUM(input) AS i, SUM(output) AS o, '
'SUM(cache_hit) AS h, SUM(cache_miss) AS m FROM token_usage '
'WHERE agent_id = ? GROUP BY model ORDER BY (SUM(input) + SUM(output)) DESC',
(agent_id or '',),
).fetchall()
by_model = [
{'model': r['model'] or '(未知)', 'input': int(r['i'] or 0), 'output': int(r['o'] or 0)}
{
'model': r['model'] or '(未知)',
'input': int(r['i'] or 0),
'output': int(r['o'] or 0),
'cacheHit': int(r['h'] or 0),
'cacheMiss': int(r['m'] or 0),
}
for r in rows
]
return {
'total': {
'input': sum(m['input'] for m in by_model),
'output': sum(m['output'] for m in by_model),
'cacheHit': sum(m['cacheHit'] for m in by_model),
'cacheMiss': sum(m['cacheMiss'] for m in by_model),
},
'byModel': by_model,
}