Token Cost Estimator

基于 OpenClaw 会话日志估算 API token 消耗与费用对比。

已扫描
适合谁
使用 OpenClaw 进行智能体开发的开发者、关注 API 费用控制的团队或个人
不适合谁
未使用 OpenClaw 的用户、无需分析成本的普通使用者
国内可用性
需网络配置。可能需要网络配置或第三方服务可访问。
安装难度
新手友好(★☆☆)。基于终端操作、依赖、API Key 和本地环境要求的初步判断。

安装与下载

openclaw skills install @npfaerber/token-cost-estimator

Skill 说明

命令、参数、文件名以原文为准

Token Cost 估算器

根据 OpenClaw 会话日志数据估算实际 API 成本。

工作原理

OpenClaw 将会话日志以 JSONL 格式存储在 ~/.openclaw/agents/<agent>/sessions/*.jsonl 目录中。每行代表一次对话轮次,包含角色(role)、内容(content),有时还包含使用量数据。

估算脚本

运行以下 Python 脚本以分析所有代理:

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 会对提示前缀进行缓存。典型的缓存命中率在 60% 到 90% 之间。缓存读取的成本比全新输入低 87.5%。

日志缺失的信息:系统提示、工具定义和内部重试操作并不总是被记录。因此,实际成本通常比日志估算值高出 1.5 到 2 倍。

计划对比

计划月度费用适用场景
API(Opus)变动高强度代理使用(超过 200 美元/月等价成本)
API(Sonnet)变动大多数代理任务,相比 Opus 便宜 5 倍
Claude Max(100 美元)固定 100 美元通过 OAuth 使用的轻中度场景(如允许)
Claude Max(200 美元)固定 200 美元通过 OAuth 使用的高强度场景(如允许)

盈亏平衡点:如果估算的 API 成本超过订阅价格,则订阅更划算。注意:Anthropic 已限制第三方工具中 OAuth token 的使用。

N
@npfaerber

已收录 1 个 Skill

相关推荐