Files
laravel-manager-packagist/dev/token-usage.py
T

130 lines
4.8 KiB
Python
Executable File

#!/usr/bin/env python3
"""Adds up the tokens of a Claude Code session log, for TOKENS.md.
Usage: dev/token-usage.py LOG.jsonl [--since 2026-12-02T07:00] [--until 2026-12-02T12:00]
[--row "Wat er is gemaakt" [--version v0.2.0]]
With --row it also prints the line for the table of TOKENS.md, with the hours as its last cell.
The hours are the time that was worked in the period: from one entry of the log to the next,
the time between an answer and the next request included, pauses of more than half an hour
left out.
LOG.jsonl is the log of the session (~/.claude/projects/<folder>/<session>.jsonl); the logs of
helper agents in the folder `<session>/subagents` next to it are counted separately. The moments
are UTC, as in the log. An answer of the model can be in the log more than once; it is counted
once, by its message id.
Standard library only.
"""
import glob
import json
import os
import sys
def answers(path):
"""The usage of every answer in a log, by message id, with its moment."""
found = {}
with open(path, encoding="utf-8") as log:
for line in log:
try:
entry = json.loads(line)
except ValueError:
continue
message = entry.get("message") or {}
if entry.get("type") == "assistant" and message.get("usage") and message.get("id"):
found[message["id"]] = (message["usage"], entry.get("timestamp", ""), message.get("model"))
return found
PAUSE = 30 * 60
def hours(path, since, until):
"""The hours worked in the period, by the moments in the main log; pauses longer than PAUSE are left out."""
from datetime import datetime
moments = []
with open(path, encoding="utf-8", errors="replace") as log:
for line in log:
try:
entry = json.loads(line)
except ValueError:
continue
if entry.get("isSidechain") or entry.get("type") not in ("user", "assistant") or not entry.get("timestamp"):
continue
moments.append(entry["timestamp"])
moments.sort()
seconds = 0.0
for start, end in zip(moments, moments[1:]):
# A step counts for the period it starts in.
if (since and start[:16] < since) or (until and start[:16] >= until):
continue
gap = (datetime.fromisoformat(end.replace("Z", "+00:00")) - datetime.fromisoformat(start.replace("Z", "+00:00"))).total_seconds()
if gap <= PAUSE:
seconds += gap
return seconds / 3600
def total(found, since, until):
"""Steps, output, input, written to the cache, read from the cache; and the models seen."""
row = [0, 0, 0, 0, 0]
models = {}
for usage, moment, model in found.values():
if (since and moment[:16] < since) or (until and moment[:16] >= until):
continue
row[0] += 1
row[1] += usage.get("output_tokens", 0)
row[2] += usage.get("input_tokens", 0)
row[3] += usage.get("cache_creation_input_tokens", 0)
row[4] += usage.get("cache_read_input_tokens", 0)
if model and not model.startswith("<"):
models[model] = models.get(model, 0) + 1
return row, models
def number(value):
return f"{value:,}".replace(",", ".")
def show(name, row):
steps, out, new, written, read = row
print(f"{name}: {steps} steps | output {number(out)} | input {number(new)} | cache written {number(written)} | cache read {number(read)} | together {number(out + new + written + read)}")
def main():
args = sys.argv[1:]
names = ("--since", "--until", "--row", "--version")
option = lambda name: args[args.index(name) + 1] if name in args else None
since, until = option("--since"), option("--until")
paths = [arg for index, arg in enumerate(args) if arg not in names and (index == 0 or args[index - 1] not in names)]
if len(paths) != 1:
sys.exit(__doc__)
row, models = total(answers(paths[0]), since, until)
show("session", row)
print(f"hours worked: {hours(paths[0], since, until):.2f}")
helpers = {}
for path in glob.glob(os.path.join(os.path.splitext(paths[0])[0], "subagents", "*.jsonl")):
helpers.update(answers(path))
if helpers:
show("helper agents", total(helpers, since, until)[0])
if option("--row"):
if len(models) > 1:
print("More than one model in this period: make a row per model (--since/--until).", file=sys.stderr)
model = max(models, key=models.get) if models else "?"
day = (since or "")[:10] or "JJJJ-MM-DD"
worked = f"{hours(paths[0], since, until):.2f}".replace(".", ",")
cells = [day, option("--row"), option("--version") or "", model] + [number(value) for value in row] + [worked]
print("| " + " | ".join(cells) + " |")
if __name__ == "__main__":
main()