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:
@@ -30,8 +30,8 @@ android {
|
||||
* versionCode 每次发版 +1(Android 靠它判断"能不能覆盖安装",
|
||||
* 改小了会装不上)。
|
||||
*/
|
||||
versionCode = 256
|
||||
versionName = "2.0.56"
|
||||
versionCode = 257
|
||||
versionName = "2.0.57"
|
||||
|
||||
ndk {
|
||||
// Chaquopy 只支持这两个;Termux bootstrap 也只准备了这两份
|
||||
|
||||
@@ -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 '',
|
||||
'input': usage['total']['input'],
|
||||
'output': usage['total']['output'],
|
||||
# v1.2 缓存统计:两家都没给时是 0/0,界面据此不显示那一列
|
||||
'cacheHit': usage['total'].get('cacheHit', 0),
|
||||
'cacheMiss': usage['total'].get('cacheMiss', 0),
|
||||
'total': used,
|
||||
'byModel': usage['byModel'],
|
||||
'limit': limit,
|
||||
|
||||
@@ -40,7 +40,19 @@ from defaults import (
|
||||
)
|
||||
|
||||
# 模板里的段名(顺序就是渲染顺序)。加一段要同时改 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):
|
||||
@@ -309,11 +321,39 @@ def build_system_prompt(settings: dict, agent: dict) -> str:
|
||||
prompt = (agent.get('systemPrompt') or '').strip() or (settings.get('systemPrompt') or '')
|
||||
values = {
|
||||
'prompt': prompt,
|
||||
# ---- 稳定段:它们在提示词最前面,靠它们拿前缀缓存命中 ----
|
||||
'skills': build_skills(agent),
|
||||
'worldview': build_worldview(agent),
|
||||
'emotion': build_emotion(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),
|
||||
}
|
||||
template = (settings.get('promptTemplate') or '').strip() or DEFAULT_PROMPT_TEMPLATE
|
||||
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 ''
|
||||
|
||||
@@ -43,11 +43,64 @@ def add_usage(total, one) -> dict:
|
||||
v = one.get(src)
|
||||
if isinstance(v, (int, float)):
|
||||
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:
|
||||
out['total_tokens'] = int(out.get('prompt_tokens') or 0) + int(out.get('completion_tokens') or 0)
|
||||
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:
|
||||
"""从 usage 里取出 (输入, 输出)。给落库用 —— 字段名差异在这一处抹平"""
|
||||
u = usage if isinstance(usage, dict) else {}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。
|
||||
"""智能体系统的内置工具:记忆 / 情绪 / 用量(需求附录 B)。
|
||||
|
||||
## 为什么是"内置工具"而不是 `tools/*.py`
|
||||
|
||||
@@ -351,6 +351,9 @@ def get_token_usage(args: dict) -> dict:
|
||||
'used': used,
|
||||
'input': usage['total']['input'],
|
||||
'output': usage['total']['output'],
|
||||
# v1.2:缓存命中/未命中(0 = 这家没提供缓存信息)
|
||||
'cacheHit': usage['total'].get('cacheHit', 0),
|
||||
'cacheMiss': usage['total'].get('cacheMiss', 0),
|
||||
'byModel': usage['byModel'],
|
||||
'limit': limit,
|
||||
'remaining': (None if limit <= 0 else max(0, limit - used)),
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -1808,7 +1808,12 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
# 记失败不影响这一轮对话 —— 统计是附加价值,不能让它把回复搞崩。
|
||||
if agent_id and (in_tok or out_tok):
|
||||
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
|
||||
print(f'[usage] 记 Token 用量失败:{exc}', file=sys.stderr)
|
||||
conv = store.get_conversation(conversation_id) or {}
|
||||
|
||||
@@ -257,11 +257,32 @@ BUILTIN_SKILL = '\n'.join([
|
||||
'【用量】用户问"你还能说多少""用了多少 token"时,用 get_token_usage 查真实数字,别猜。',
|
||||
])
|
||||
|
||||
# system prompt 的注入模板(需求附录 C)。
|
||||
# system prompt 的注入模板(需求附录 C,v1.2 修订了段序)。
|
||||
#
|
||||
# 顺序是**固定**的:人设 → skills → worldview → emotion → memory → peer_emotions。
|
||||
# 可以整段替换(存全局设置 promptTemplate),但占位符名字别改 ——
|
||||
# agent_context.py 就是按这些名字找段落、空段整段删掉的。
|
||||
# ★★ **缓存友好排序**(附录 C 的 v1.2 修订):
|
||||
#
|
||||
# 主流模型的上下文缓存都是**前缀匹配** —— 从第一个 token 开始逐段比对,
|
||||
# 一旦有一处不同,**那之后的所有内容全部失效**(要么重算、要么按未命中计费)。
|
||||
#
|
||||
# 所以段序要按**稳定性**排:最稳的在前、最易变的在最后。
|
||||
#
|
||||
# 稳 → {prompt} 几乎不变(用户很少改人设)
|
||||
# <skills> 很少变
|
||||
# <worldview> 很少变
|
||||
# <memory> 偶尔加几条
|
||||
# ────────────────────────────────────── 上面是长前缀,尽量保持命中
|
||||
# <stats> 数值一变就变
|
||||
# <status> 每轮都可能变(轮数在减)
|
||||
# <emotion> 情绪一变就变
|
||||
# <peer_emotions> 别人的情绪,最不可控
|
||||
# 变 →
|
||||
#
|
||||
# 改之前 emotion 在 memory **前面** —— 情绪一变,后面整段(含最长的 memory)
|
||||
# 缓存全废。挪到最后之后,情绪变化只让最后那两个短段失效。
|
||||
#
|
||||
# 这是这个文件里性价比最高的一处改动:不改任何功能,只改顺序。
|
||||
#
|
||||
# 占位符名字别改 —— agent_context.py 就是按这些名字找段落、空段整段删掉的。
|
||||
DEFAULT_PROMPT_TEMPLATE = '\n'.join([
|
||||
'{prompt}',
|
||||
'',
|
||||
@@ -273,14 +294,23 @@ DEFAULT_PROMPT_TEMPLATE = '\n'.join([
|
||||
'{worldview}',
|
||||
'</worldview>',
|
||||
'',
|
||||
'<emotion>',
|
||||
'{emotion}',
|
||||
'</emotion>',
|
||||
'',
|
||||
'<memory>',
|
||||
'{memory}',
|
||||
'</memory>',
|
||||
'',
|
||||
# ---- 以下是易变段,放最后 ----
|
||||
'<stats>',
|
||||
'{stats}',
|
||||
'</stats>',
|
||||
'',
|
||||
'<status>',
|
||||
'{status}',
|
||||
'</status>',
|
||||
'',
|
||||
'<emotion>',
|
||||
'{emotion}',
|
||||
'</emotion>',
|
||||
'',
|
||||
'<peer_emotions>',
|
||||
'{peer_emotions}',
|
||||
'</peer_emotions>',
|
||||
|
||||
Reference in New Issue
Block a user