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:
@@ -64,6 +64,7 @@ def section(title):
|
||||
import agent_context # noqa: E402
|
||||
import agent_tools # noqa: E402
|
||||
import agentdb # noqa: E402
|
||||
import defaults # noqa: E402
|
||||
import store # noqa: E402
|
||||
|
||||
|
||||
@@ -236,8 +237,11 @@ def main():
|
||||
check("共享记忆带作者署名", "(你记的)" in prompt, prompt[-300:])
|
||||
check("自定义 Skill 进去了", "写东西要先列大纲" in prompt)
|
||||
check("顺序:skills 在 worldview 前", prompt.index("<skills>") < prompt.index("<worldview>"))
|
||||
check("顺序:worldview 在 emotion 前", prompt.index("<worldview>") < prompt.index("<emotion>"))
|
||||
check("顺序:emotion 在 memory 前", prompt.index("<emotion>") < prompt.index("<memory>"))
|
||||
check("顺序:worldview 在 memory 前", prompt.index("<worldview>") < prompt.index("<memory>"))
|
||||
# ★ v1.2 把 emotion 挪到 memory **后面**了(缓存友好排序,详见第 20 节)。
|
||||
# 这条断言原来记的是旧顺序 —— 顺序一改它就红了,这正是它该干的活。
|
||||
check("顺序:memory 在 emotion 前(v1.2 缓存友好)",
|
||||
prompt.index("<memory>") < prompt.index("<emotion>"))
|
||||
# ★ 情绪感知关着时**仍然给成员名单**(复查报告 5):共享记忆是共用的,
|
||||
# AI 不知道有别人,就会把别人写的条目当成自己的经历
|
||||
check("没开感知也有成员名单", "<peer_emotions>" in prompt and "仙辰" in prompt, prompt[-300:])
|
||||
@@ -603,6 +607,77 @@ def main():
|
||||
check("自定义档位也能被选中", portrait_of(custom, "醉") == sad)
|
||||
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()
|
||||
if fails:
|
||||
|
||||
Reference in New Issue
Block a user