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

@@ -30,8 +30,8 @@ android {
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装", * versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
* 改小了会装不上)。 * 改小了会装不上)。
*/ */
versionCode = 256 versionCode = 257
versionName = "2.0.56" versionName = "2.0.57"
ndk { ndk {
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份 // Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份

View File

@@ -1,4 +1,4 @@
"""智能体系统的 HTTP 接口(需求 v1.1)。 """智能体系统的 HTTP 接口(需求 v1.1)。
## 为什么单独一个模块 ## 为什么单独一个模块
@@ -844,6 +844,9 @@ def _usage_payload(agent: dict) -> dict:
'name': agent.get('name') or '', 'name': agent.get('name') or '',
'input': usage['total']['input'], 'input': usage['total']['input'],
'output': usage['total']['output'], 'output': usage['total']['output'],
# v1.2 缓存统计:两家都没给时是 0/0,界面据此不显示那一列
'cacheHit': usage['total'].get('cacheHit', 0),
'cacheMiss': usage['total'].get('cacheMiss', 0),
'total': used, 'total': used,
'byModel': usage['byModel'], 'byModel': usage['byModel'],
'limit': limit, 'limit': limit,

View File

@@ -40,7 +40,19 @@ from defaults import (
) )
# 模板里的段名(顺序就是渲染顺序)。加一段要同时改 defaults.DEFAULT_PROMPT_TEMPLATE。 # 模板里的段名(顺序就是渲染顺序)。加一段要同时改 defaults.DEFAULT_PROMPT_TEMPLATE。
SECTIONS = ('skills', 'worldview', 'emotion', 'memory', 'peer_emotions') #: 段落名,**顺序就是注入顺序**(需求附录 C,v1.2 按缓存友好重排)。
#:
#: ★★ 为什么顺序这么重要:主流模型的上下文缓存都是**前缀匹配** ——
#: 从第一个 token 开始逐段比对,一处不同则**其后全部失效**。
#: 所以最稳的排前面(prompt/skills/worldview/memory 组成长前缀),
#: 最易变的排最后(stats/status/emotion/peer_emotions)。
#:
#: 改之前 emotion 在 memory 前面 —— 情绪一变,连最长的 memory 段
#: 一起失效。挪到后面之后,情绪变化只影响末尾那几个短段。
#:
#: ★ 这个元组**同时决定** `render` 处理哪些段:不在里面的占位符不会被替换,
#: 会原样留在提示词里(带着 `{xxx}` 大括号)。加新段时两处一起改。
SECTIONS = ('skills', 'worldview', 'memory', 'stats', 'status', 'emotion', 'peer_emotions')
def _safe(fn, fallback): def _safe(fn, fallback):
@@ -309,11 +321,39 @@ def build_system_prompt(settings: dict, agent: dict) -> str:
prompt = (agent.get('systemPrompt') or '').strip() or (settings.get('systemPrompt') or '') prompt = (agent.get('systemPrompt') or '').strip() or (settings.get('systemPrompt') or '')
values = { values = {
'prompt': prompt, 'prompt': prompt,
# ---- 稳定段:它们在提示词最前面,靠它们拿前缀缓存命中 ----
'skills': build_skills(agent), 'skills': build_skills(agent),
'worldview': build_worldview(agent), 'worldview': build_worldview(agent),
'emotion': build_emotion(agent),
'memory': build_memory(agent), 'memory': build_memory(agent),
# ---- 易变段:放最后,变了也只让末尾失效 ----
# stats / status 是 v1.2 §3.10/3.11 的规则引擎段,实现见阶段 3;
# 现在返回空串 → `render` 会把整段删掉(不会留下空标签)
'stats': build_stats(agent),
'status': build_status(agent),
'emotion': build_emotion(agent),
'peer_emotions': build_peer_emotions(agent), 'peer_emotions': build_peer_emotions(agent),
} }
template = (settings.get('promptTemplate') or '').strip() or DEFAULT_PROMPT_TEMPLATE template = (settings.get('promptTemplate') or '').strip() or DEFAULT_PROMPT_TEMPLATE
return render(template, values) return render(template, values)
def build_stats(agent: dict) -> str:
"""
`<stats>` 段:数值系统(需求附录 C / §3.10)。
★ 占位函数,**阶段 3 实现**。现在返回空串 —— `render` 会把整段删掉,
所以提示词里不会出现一个空的 `<stats></stats>`。
先把它列进 `SECTIONS` 是为了让模板和渲染两边**一开始就一致**:
否则阶段 3 加段名时,会有一版"模板里有、渲染不管"的中间状态,
表现是提示词里原样留着 `{stats}` 大括号。
"""
return ''
def build_status(agent: dict) -> str:
"""
`<status>` 段:状态系统(需求附录 C / §3.11)。
★ 同样是**阶段 3 的占位**,见 `build_stats` 的说明。
"""
return ''

View File

@@ -43,11 +43,64 @@ def add_usage(total, one) -> dict:
v = one.get(src) v = one.get(src)
if isinstance(v, (int, float)): if isinstance(v, (int, float)):
out[dst] = int(out.get(dst) or 0) + int(v) out[dst] = int(out.get(dst) or 0) + int(v)
# 缓存命中也累加(需求 3.1 的 v1.2 新增)。
# ★ 累加的是**归一化之后**的两个数,不是原始字段:各家的名字不一样,
# 直接并进 out 的话,换了模型那个 key 就消失了。
hit, miss = cache_pair(one)
if hit or miss:
out['cache_hit'] = int(out.get('cache_hit') or 0) + hit
out['cache_miss'] = int(out.get('cache_miss') or 0) + miss
if 'total_tokens' not in out: if 'total_tokens' not in out:
out['total_tokens'] = int(out.get('prompt_tokens') or 0) + int(out.get('completion_tokens') or 0) out['total_tokens'] = int(out.get('prompt_tokens') or 0) + int(out.get('completion_tokens') or 0)
return out return out
#: 各家的「缓存命中」字段名。**加新提供商只改这一处**,不要在调用点写 if。
#:
#: DeepSeek prompt_cache_hit_tokens / prompt_cache_miss_tokens(两个都给)
#: Claude cache_read_input_tokens(只给命中)
#: OpenAI prompt_tokens_details.cached_tokens(嵌套,也只给命中)
_CACHE_HIT_KEYS = ('prompt_cache_hit_tokens', 'cache_read_input_tokens', 'cached_tokens')
def cache_pair(usage) -> tuple:
"""
从 usage 里取出 `(cache_hit, cache_miss)`(需求 3.1 的 v1.2 新增)。
★ 为什么必须归一化:三家的字段名完全不同,不归一化的话,
界面上那个"缓存命中率"会因为换了个模型就**静默变成 0**
(而不是报错 —— 静默的 0 最难发现,用户会以为"缓存没生效")。
★ 两家只给命中、不给未命中(Claude / OpenAI),所以未命中要**自己推**:
`prompt_tokens - hit`。推不出来时返回 0,界面据此**不显示那一列** ——
显示一个假的 0% 是误导。
"""
u = usage if isinstance(usage, dict) else {}
hit = 0
for key in _CACHE_HIT_KEYS:
v = u.get(key)
if isinstance(v, (int, float)) and v > 0:
hit = int(v)
break
if not hit:
# OpenAI 把它塞在嵌套对象里
details = u.get('prompt_tokens_details')
if isinstance(details, dict):
v = details.get('cached_tokens')
if isinstance(v, (int, float)) and v > 0:
hit = int(v)
miss = 0
v = u.get('prompt_cache_miss_tokens')
if isinstance(v, (int, float)) and v > 0:
miss = int(v)
if hit and not miss:
total = u.get('prompt_tokens') or u.get('input_tokens')
if isinstance(total, (int, float)) and total >= hit:
miss = int(total) - hit
return hit, miss
def usage_pair(usage) -> tuple: def usage_pair(usage) -> tuple:
"""从 usage 里取出 (输入, 输出)。给落库用 —— 字段名差异在这一处抹平""" """从 usage 里取出 (输入, 输出)。给落库用 —— 字段名差异在这一处抹平"""
u = usage if isinstance(usage, dict) else {} u = usage if isinstance(usage, dict) else {}

View File

@@ -1,4 +1,4 @@
"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。 """智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。
## 为什么是"内置工具"而不是 `tools/*.py` ## 为什么是"内置工具"而不是 `tools/*.py`
@@ -351,6 +351,9 @@ def get_token_usage(args: dict) -> dict:
'used': used, 'used': used,
'input': usage['total']['input'], 'input': usage['total']['input'],
'output': usage['total']['output'], 'output': usage['total']['output'],
# v1.2:缓存命中/未命中(0 = 这家没提供缓存信息)
'cacheHit': usage['total'].get('cacheHit', 0),
'cacheMiss': usage['total'].get('cacheMiss', 0),
'byModel': usage['byModel'], 'byModel': usage['byModel'],
'limit': limit, 'limit': limit,
'remaining': (None if limit <= 0 else max(0, limit - used)), 'remaining': (None if limit <= 0 else max(0, limit - used)),

View File

@@ -109,6 +109,12 @@ CREATE TABLE IF NOT EXISTS token_usage (
model TEXT NOT NULL DEFAULT '', model TEXT NOT NULL DEFAULT '',
input INTEGER NOT NULL DEFAULT 0, input INTEGER NOT NULL DEFAULT 0,
output 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 created_at TEXT NOT NULL
); );
CREATE INDEX IF NOT EXISTS idx_token_agent ON token_usage(agent_id); CREATE INDEX IF NOT EXISTS idx_token_agent ON token_usage(agent_id);
@@ -159,6 +165,14 @@ def _migrate(conn) -> None:
# 老数据的自由文本 → text;preset 全是默认的「平常」 # 老数据的自由文本 → text;preset 全是默认的「平常」
conn.execute('UPDATE emotions SET text = emotion') 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)。 #: v1.2 情绪的五档枚举(需求 3.5)。
#: #:
@@ -475,20 +489,26 @@ def peer_emotions(worldview_id: str, exclude_agent: str, agent_ids: list) -> lis
# Token 统计 # 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),而且按**模型**分桶 —— ★ 输入 / 输出**分开记**(需求 3.1),而且按**模型**分桶 ——
"按模型"是靠每行带 model 名做到的:桶是查询时 group by 出来的, "按模型"是靠每行带 model 名做到的:桶是查询时 group by 出来的,
不是提前建好的。这样换模型不会有"桶没建好"的问题。 不是提前建好的。这样换模型不会有"桶没建好"的问题。
★ v1.2 多两个参数:缓存命中 / 未命中。**默认 0** 是有意的 ——
`agent_loop.cache_pair()` 归一化之后如果两家都没给,就是 0/0,
界面据此不显示那一列(显示假的 0% 是误导)。
""" """
init() init()
conn = _connect() conn = _connect()
conn.execute( conn.execute(
'INSERT INTO token_usage (agent_id, model, input, output, created_at) ' 'INSERT INTO token_usage (agent_id, model, input, output, cache_hit, cache_miss, created_at) '
'VALUES (?, ?, ?, ?, ?)', 'VALUES (?, ?, ?, ?, ?, ?, ?)',
(agent_id or '', model or '', int(input_tokens or 0), int(output_tokens or 0), now_iso()), (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() 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() init()
conn = _connect() conn = _connect()
rows = conn.execute( 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', 'WHERE agent_id = ? GROUP BY model ORDER BY (SUM(input) + SUM(output)) DESC',
(agent_id or '',), (agent_id or '',),
).fetchall() ).fetchall()
by_model = [ 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 for r in rows
] ]
return { return {
'total': { 'total': {
'input': sum(m['input'] for m in by_model), 'input': sum(m['input'] for m in by_model),
'output': sum(m['output'] 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, 'byModel': by_model,
} }

View File

@@ -1808,7 +1808,12 @@ class KernelHandler(BaseHTTPRequestHandler):
# 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。 # 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。
if agent_id and (in_tok or out_tok): if agent_id and (in_tok or out_tok):
try: try:
agentdb.token_add(agent_id, model_name, in_tok, out_tok) # ★ v1.2:缓存命中 / 未命中一起落库。
# `cache_pair` 已经把三家的字段名归一化过
# (DeepSeek 两个都给、Claude/OpenAI 只给命中要自己推);
# 两家都没给就是 0/0,界面据此**不显示**那一列。
hit, miss = agent_loop.cache_pair(result.get('usage'))
agentdb.token_add(agent_id, model_name, in_tok, out_tok, hit, miss)
except Exception as exc: # noqa: BLE001 except Exception as exc: # noqa: BLE001
print(f'[usage] 记 Token 用量失败:{exc}', file=sys.stderr) print(f'[usage] 记 Token 用量失败:{exc}', file=sys.stderr)
conv = store.get_conversation(conversation_id) or {} conv = store.get_conversation(conversation_id) or {}

View File

@@ -257,11 +257,32 @@ BUILTIN_SKILL = '\n'.join([
'【用量】用户问"你还能说多少""用了多少 token"时,用 get_token_usage 查真实数字,别猜。', '【用量】用户问"你还能说多少""用了多少 token"时,用 get_token_usage 查真实数字,别猜。',
]) ])
# system prompt 的注入模板(需求附录 C)。 # system prompt 的注入模板(需求附录 C,v1.2 修订了段序)。
# #
# 顺序是**固定**的:人设 → skills → worldview → emotion → memory → peer_emotions。 # ★★ **缓存友好排序**(附录 C 的 v1.2 修订):
# 可以整段替换(存全局设置 promptTemplate),但占位符名字别改 —— #
# agent_context.py 就是按这些名字找段落、空段整段删掉的。 # 主流模型的上下文缓存都是**前缀匹配** —— 从第一个 token 开始逐段比对,
# 一旦有一处不同,**那之后的所有内容全部失效**(要么重算、要么按未命中计费)。
#
# 所以段序要按**稳定性**排:最稳的在前、最易变的在最后。
#
# 稳 → {prompt} 几乎不变(用户很少改人设)
# <skills> 很少变
# <worldview> 很少变
# <memory> 偶尔加几条
# ────────────────────────────────────── 上面是长前缀,尽量保持命中
# <stats> 数值一变就变
# <status> 每轮都可能变(轮数在减)
# <emotion> 情绪一变就变
# <peer_emotions> 别人的情绪,最不可控
# 变 →
#
# 改之前 emotion 在 memory **前面** —— 情绪一变,后面整段(含最长的 memory)
# 缓存全废。挪到最后之后,情绪变化只让最后那两个短段失效。
#
# 这是这个文件里性价比最高的一处改动:不改任何功能,只改顺序。
#
# 占位符名字别改 —— agent_context.py 就是按这些名字找段落、空段整段删掉的。
DEFAULT_PROMPT_TEMPLATE = '\n'.join([ DEFAULT_PROMPT_TEMPLATE = '\n'.join([
'{prompt}', '{prompt}',
'', '',
@@ -273,14 +294,23 @@ DEFAULT_PROMPT_TEMPLATE = '\n'.join([
'{worldview}', '{worldview}',
'</worldview>', '</worldview>',
'', '',
'<emotion>',
'{emotion}',
'</emotion>',
'',
'<memory>', '<memory>',
'{memory}', '{memory}',
'</memory>', '</memory>',
'', '',
# ---- 以下是易变段,放最后 ----
'<stats>',
'{stats}',
'</stats>',
'',
'<status>',
'{status}',
'</status>',
'',
'<emotion>',
'{emotion}',
'</emotion>',
'',
'<peer_emotions>', '<peer_emotions>',
'{peer_emotions}', '{peer_emotions}',
'</peer_emotions>', '</peer_emotions>',

View File

@@ -64,6 +64,7 @@ def section(title):
import agent_context # noqa: E402 import agent_context # noqa: E402
import agent_tools # noqa: E402 import agent_tools # noqa: E402
import agentdb # noqa: E402 import agentdb # noqa: E402
import defaults # noqa: E402
import store # noqa: E402 import store # noqa: E402
@@ -236,8 +237,11 @@ def main():
check("共享记忆带作者署名", "(你记的)" in prompt, prompt[-300:]) check("共享记忆带作者署名", "(你记的)" in prompt, prompt[-300:])
check("自定义 Skill 进去了", "写东西要先列大纲" in prompt) check("自定义 Skill 进去了", "写东西要先列大纲" in prompt)
check("顺序:skills 在 worldview 前", prompt.index("<skills>") < prompt.index("<worldview>")) check("顺序:skills 在 worldview 前", prompt.index("<skills>") < prompt.index("<worldview>"))
check("顺序:worldview 在 emotion 前", prompt.index("<worldview>") < prompt.index("<emotion>")) check("顺序:worldview 在 memory 前", prompt.index("<worldview>") < prompt.index("<memory>"))
check("顺序:emotion 在 memory 前", prompt.index("<emotion>") < prompt.index("<memory>")) # ★ v1.2 把 emotion 挪到 memory **后面**了(缓存友好排序,详见第 20 节)。
# 这条断言原来记的是旧顺序 —— 顺序一改它就红了,这正是它该干的活。
check("顺序:memory 在 emotion 前(v1.2 缓存友好)",
prompt.index("<memory>") < prompt.index("<emotion>"))
# ★ 情绪感知关着时**仍然给成员名单**(复查报告 5):共享记忆是共用的, # ★ 情绪感知关着时**仍然给成员名单**(复查报告 5):共享记忆是共用的,
# AI 不知道有别人,就会把别人写的条目当成自己的经历 # AI 不知道有别人,就会把别人写的条目当成自己的经历
check("没开感知也有成员名单", "<peer_emotions>" in prompt and "仙辰" in prompt, prompt[-300:]) check("没开感知也有成员名单", "<peer_emotions>" in prompt and "仙辰" in prompt, prompt[-300:])
@@ -603,6 +607,77 @@ def main():
check("自定义档位也能被选中", portrait_of(custom, "醉") == sad) check("自定义档位也能被选中", portrait_of(custom, "醉") == sad)
shutil.rmtree(pic_dir, ignore_errors=True) shutil.rmtree(pic_dir, ignore_errors=True)
# ---------------------------------------------------------------- 20
section("20. v1.2 缓存友好段序(附录 C 修订,**改动最小、省的钱最多**)")
#
# 主流模型的上下文缓存是**前缀匹配**:一处不同则其后全部失效。
# 所以稳定段必须在前面、易变段必须在后面。
order = list(agent_context.SECTIONS)
check("稳定段在最前(skills 先于 memory)",
order.index('skills') < order.index('memory'), str(order))
check("worldview 也在易变段之前",
order.index('worldview') < order.index('emotion'), str(order))
# ★ 这一条就是 v1.2 改的东西:以前 emotion 在 memory 前面,
# 情绪一变连最长的 memory 段一起失效
check("**emotion 在 memory 之后**(v1.2 改的就是这条)",
order.index('emotion') > order.index('memory'), str(order))
check("数值/状态两个易变段也在 memory 之后",
order.index('stats') > order.index('memory')
and order.index('status') > order.index('memory'), str(order))
check("peer_emotions 排最后(最不可控)", order[-1] == 'peer_emotions', str(order))
# 模板里的顺序必须和 SECTIONS 一致,否则一个说东一个说西
tmpl = defaults.DEFAULT_PROMPT_TEMPLATE
tmpl_order = [m for m in __import__('re').findall(r'<(\w+)>', tmpl) if m in order]
check("模板里的段序和 SECTIONS 一致", tmpl_order == [n for n in order if n in tmpl_order], str(tmpl_order))
# 空的段不能留下 `{stats}` 这种裸占位符
p_bare = agent_context.build_system_prompt(store.read_settings(), store.get_agent(a1["id"]))
check("空段(stats/status)整段删掉,不留裸占位符", '{stats}' not in p_bare and '{status}' not in p_bare)
section("21. v1.2 缓存统计归一化(三家字段名完全不同)")
import agent_loop as _loop
cases = [
("DeepSeek(命中+未命中都给)",
{"prompt_tokens": 1000, "prompt_cache_hit_tokens": 800, "prompt_cache_miss_tokens": 200}, (800, 200)),
("Claude(只给命中,未命中要自己推)",
{"input_tokens": 1000, "cache_read_input_tokens": 600}, (600, 400)),
("OpenAI(嵌套在 details 里)",
{"prompt_tokens": 1000, "prompt_tokens_details": {"cached_tokens": 400}}, (400, 600)),
("这家不返回缓存字段", {"prompt_tokens": 1000}, (0, 0)),
("空 usage", None, (0, 0)),
]
for label, usage, want in cases:
got = _loop.cache_pair(usage)
check(f"{label} → {want}", got == want, f"实际 {got}")
# 累加要累加**归一化之后**的数,不是原始字段(换模型就不会丢)
acc = _loop.add_usage({}, {"prompt_tokens": 1000, "prompt_cache_hit_tokens": 800,
"prompt_cache_miss_tokens": 200})
acc = _loop.add_usage(acc, {"input_tokens": 500, "cache_read_input_tokens": 400})
check("跨提供商累加命中数", acc.get("cache_hit") == 1200, str(acc.get("cache_hit")))
check("跨提供商累加未命中数", acc.get("cache_miss") == 300, str(acc.get("cache_miss")))
# 落库 → 查出来
ca = store.create_agent({"name": "缓存测试"})
agentdb.token_add(ca["id"], "doubao-pro", 1000, 50, 800, 200)
agentdb.token_add(ca["id"], "deepseek-r1", 500, 20, 400, 100)
u = agentdb.token_usage(ca["id"])
check("total 里有缓存数", u["total"].get("cacheHit") == 1200 and u["total"].get("cacheMiss") == 300,
str(u["total"]))
check("按模型分桶里也有",
all("cacheHit" in m for m in u["byModel"]), str(u["byModel"]))
# 老库(没有这两列)要能迁移上来
conn_old_tu = sqlite3.connect(":memory:")
conn_old_tu.row_factory = sqlite3.Row
conn_old_tu.executescript(
"CREATE TABLE emotions (agent_id TEXT PRIMARY KEY, emotion TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL);"
"CREATE TABLE token_usage (id INTEGER PRIMARY KEY AUTOINCREMENT, agent_id TEXT NOT NULL,"
" model TEXT NOT NULL DEFAULT '', input INTEGER NOT NULL DEFAULT 0,"
" output INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL);"
)
agentdb._migrate(conn_old_tu)
tcols = {r["name"] for r in conn_old_tu.execute("PRAGMA table_info(token_usage)").fetchall()}
check("老库的 token_usage 能加上缓存两列", {"cache_hit", "cache_miss"} <= tcols, str(sorted(tcols)))
conn_old_tu.close()
# ---------------------------------------------------------------- 汇总 # ---------------------------------------------------------------- 汇总
print() print()
if fails: if fails: