从 OpenClaw 会话记录估算 API token 费用。分析所有代理会话,计算按 token 计费与订阅方案的花费差异。
Token Cost Egestitor.是一项面向实际任务的技能,主要用于OpenClaw 会话记录数据中真实的API费用.;How It Works.;
从功能定位来看,该技能强调把分散的操作要求整理成清晰、可复用的处理流程,使用户能够围绕既定目标快速准备输入、选择执行方式并获得结构化结果。实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。
执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。该技能适合用于一次性任务,也可以接入自动化工作流,与其他技能或上层代理配合完成更完整的业务链路;在组合使用时,应明确每一步的输入输出关系,并避免不同步骤之间出现参数冲突。
基于 OpenClaw 会话记录数据,估算真实的 API 费用。
OpenClaw 将会话记录以 JSONL 格式存储在 ~/.openclaw/agents/ 路径下。每行代表一次对话轮次(turn),包含 role、content 字段,有时还包含 usage 数据。
运行以下 Python 脚本来分析所有 agent:
import json, glob, os
AGENTS_DIR = os.path.expanduser('~/.openclaw/agents')
# 每百万 token 的单价(请根据需要更新)
PRICING = {
'opus': {'input': 15, 'output': 75, 'cache_read': 1.875},
'sonnet': {'input': 3, 'output': 15, 'cache_read': 0.375},
}
agent_dirs = [d for d in os.listdir(AGENTS_DIR) if os.path.isdir(os.path.join(AGENTS_DIR, d))]
grand_in, grand_out = 0, 0
for agent in sorted(agent_dirs):
sess_dir = os.path.join(AGENTS_DIR, agent, 'sessions')
if not os.path.isdir(sess_dir):
continue
total_in, total_out, sessions = 0, 0, 0
for f in glob.glob(os.path.join(sess_dir, '*.jsonl')):
sessions += 1
turns = []
for line in open(f):
try:
obj = json.loads(line)
msg = obj.get('message', {})
if not isinstance(msg, dict): continue
role = msg.get('role', '')
raw = json.dumps(msg)
turns.append((role, len(raw)))
except: pass
# 考虑上下文重复发送
cumulative = 0
for role, chars in turns:
if role in ('user', 'system', 'tool'):
cumulative += chars
elif role == 'assistant':
total_in += cumulative // 4
total_out += chars // 4
print(f'{agent}: {sessions} 个会话,约 {total_in:,} 输入 token,约 {total_out:,} 输出 token')
grand_in += total_in
grand_out += total_out
print(f'\n总计输入:约 {grand_in:,},输出:约 {grand_out:,}')
for tier, rates in PRICING.items():
for cache_pct in [0.6, 0.9]:
cached = int(grand_in * cache_pct)
uncached = grand_in - cached
cost = (uncached/1e6)*rates['input'] + (cached/1e6)*rates['cache_read'] + (grand_out/1e6)*rates['output']
print(f'{tier}({int(cache_pct*100)}% 缓存命中率):${cost:,.2f}')
上下文重复发送:每次 API 调用均需将完整对话历史作为输入发送。例如一个 50 轮的对话,在每次新消息中都会重新发送此前全部轮次内容。这是成本的第一大驱动因素。
缓存命中:OpenClaw 对 prompt 前缀进行缓存。典型缓存命中率为 60–90%。缓存读取成本比全新输入低 87.5%。
会话记录未涵盖的内容:系统提示词(system prompts)、工具定义(tool definitions)以及内部重试过程并不总被记录。实际成本通常为会话记录估算值的 1.5–2 倍。
| 方案 | 月度费用 | 适用场景 |
|---|---|---|
| API(Opus) | 按用量计费 | 高频智能体(agentic)使用(等效月支出 > $200) |
| API(Sonnet) | 按用量计费 | 大多数智能体任务,成本约为 Opus 的 1/5 |
| Claude Max($100) | $100 固定月费 | 轻度至中度使用(通过 OAuth,若允许) |
| Claude Max($200) | $200 固定月费 | 重度使用(通过 OAuth,若允许) |
盈亏平衡点:若估算出的 API 成本超过订阅价格,则选择订阅更省钱。注意:Anthropic 已限制第三方工具中 OAuth token 的使用。