nekolas note

毎日書くことを目指しているけど全然達成できてないブログ

2.7 KB Raw
#!/usr/bin/env python3
"""作業ディレクトリのセッション記録からトークン数を合計する(会話の中身は出さず、数だけ出す)。
使い方: measure.py <作業ディレクトリ> [--price in,out,cache_write,cache_read]  (単価は $/MTok)
記録は ~/.claude/projects/<パスの / を - に替えた名前>/*.jsonl(権限 600。数の集計だけに使い、中身は表示しない)。"""
import collections, glob, json, os, sys

def main():
    a = sys.argv[1:]
    if not a: sys.exit(__doc__)
    price = None
    if "--price" in a:
        i = a.index("--price"); price = [float(x) for x in a[i+1].split(",")]; del a[i:i+2]
    d = os.path.realpath(os.path.expanduser(a[0]))
    proj = os.path.expanduser("~/.claude/projects/" + d.replace("/", "-").replace(".", "-"))
    seen, tot, models = {}, dict(input=0, output=0, cache_write=0, cache_read=0), set()
    tools, tool_ids = collections.Counter(), set()
    for f in glob.glob(proj + "/*.jsonl"):
        for line in open(f):
            try: r = json.loads(line)
            except ValueError: continue
            m = r.get("message") or {}
            u = m.get("usage")
            if r.get("type") != "assistant" or not u: continue
            for b in (m.get("content") if isinstance(m.get("content"), list) else []):
                if b.get("type") == "tool_use" and b.get("id") not in tool_ids:
                    tool_ids.add(b.get("id")); tools[b["name"]] += 1   # 1 つの応答の中身が複数行に分かれて記録されるので、ID で重複を除く
            seen[m.get("id") or r.get("uuid")] = u   # 同じ応答の重複記録は最後の値だけ数える
            if m.get("model"): models.add(m["model"])
    for u in seen.values():
        tot["input"] += u.get("input_tokens", 0); tot["output"] += u.get("output_tokens", 0)
        tot["cache_write"] += u.get("cache_creation_input_tokens", 0); tot["cache_read"] += u.get("cache_read_input_tokens", 0)
    print("応答数:", len(seen), " モデル:", ",".join(sorted(models)) or "不明")
    for k, v in tot.items(): print(f"{k}: {v:,}")
    print(f"合計: {sum(tot.values()):,}")
    print("ツール呼び出し:", ", ".join(f"{k}={v}" for k, v in tools.most_common()) or "なし")
    print("Code Mode の使用:", f"あり(REPL {tools['REPL']} 回)" if tools.get("REPL") else "なし(REPL の呼び出しが 0 回。通常モードで動いた可能性が高い)")
    if price:
        c = sum(tot[k] * p for k, p in zip(("input", "output", "cache_write", "cache_read"), price)) / 1e6
        print(f"金額(指定単価 {price}): ${c:.4f}")
    else:
        print("金額: 単価未指定(--price か /cost で確認)")

main()