Files

153 lines
6.2 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(s) for the table of TOKENS.md, with the hours as the last cell.
Helper agents (subagents) are part of the work: their tokens are added to the row. The row is made
per model, because the price differs per model: when helper agents ran on another model than the
session, there is one row for each, and the hours are on the first row only.
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 shown separately and also counted in the row. 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"))
# The advisor (another, stronger model) runs inside an answer: its tokens are in the
# iterations of that answer and are not part of the usage of the answer itself.
for number, iteration in enumerate(message["usage"].get("iterations") or []):
if iteration.get("type") == "advisor_message":
found[f'{message["id"]}:advisor:{number}'] = (iteration, entry.get("timestamp", ""), iteration.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 same per model."""
row = [0, 0, 0, 0, 0]
per_model = {}
for usage, moment, model in found.values():
if (since and moment[:16] < since) or (until and moment[:16] >= until):
continue
# Entries the client made itself (model "<synthetic>") hold no tokens and no work.
if model and model.startswith("<"):
continue
add = [
1,
usage.get("output_tokens", 0),
usage.get("input_tokens", 0),
usage.get("cache_creation_input_tokens", 0),
usage.get("cache_read_input_tokens", 0),
]
model = model or "?"
mine = per_model.setdefault(model, [0, 0, 0, 0, 0])
for index, value in enumerate(add):
row[index] += value
mine[index] += value
return row, per_model
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__)
session = answers(paths[0])
row, _ = total(session, since, until)
show("session", row)
worked_hours = hours(paths[0], since, until)
print(f"hours worked: {worked_hours:.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"):
# Session and helper agents together, one row per model.
everything = {**session, **{"helper:" + key: value for key, value in helpers.items()}}
_, per_model = total(everything, since, until)
if not per_model:
per_model = {"?": [0, 0, 0, 0, 0]}
day = (since or "")[:10] or "JJJJ-MM-DD"
# The model with the most steps first; the hours go on that row only.
for position, model in enumerate(sorted(per_model, key=lambda name: -per_model[name][0])):
worked = f"{worked_hours:.2f}" if position == 0 else "0.00"
cells = [day, option("--row"), option("--version") or "", model] + [number(value) for value in per_model[model]] + [worked.replace(".", ",")]
print("| " + " | ".join(cells) + " |")
if __name__ == "__main__":
main()