Files
deverenz/.claude/scripts/ticket-cost.py
T
kasun eb49c71937
CI / checks (pull_request) Successful in 13s
fix: parse transcripts with pydantic models in ticket-cost script
json.loads returned untyped data, which failed strict type checking. pyright never reported it because it skips the .claude/ folder.
2026-11-15 21:44:33 +01:00

171 lines
6.6 KiB
Python
Executable File

#!/usr/bin/env -S uv run --quiet
"""Token usage and API-equivalent cost of the agent's work in a time window, for the dev log.
Not part of the Deverenz product. Reads Claude Code's session transcripts for this
project and sums the token usage of every model response between --since and --until.
Cost is what the same usage would cost at Anthropic API list prices, converted to EUR
with the ECB reference rate; on a subscription it is not what was actually paid.
Usage (from the repo root, so uv uses the project environment with pydantic):
.claude/scripts/ticket-cost.py --since 2026-11-15T10:00:00Z [--until 2026-11-15T14:00:00Z]
.claude/scripts/ticket-cost.py --since ... --usd-eur 0.86 # skip the ECB lookup
"""
# pyright: strict
import argparse
import re
import sys
import urllib.request
from datetime import UTC, datetime
from pathlib import Path
from pydantic import BaseModel
# USD per million tokens: input, output, cache read, cache write 5m, cache write 1h.
# Source: Anthropic pricing as of 2026-11-03. Update when prices change.
PRICES: dict[str, tuple[float, float, float, float, float]] = {
"claude-opus-5-5": (4.00, 20.00, 0.20, 5.00, 8.00),
"claude-sonnet-5-5": (2.00, 10.00, 0.10, 2.50, 4.00),
"claude-haiku-5-5": (0.10, 0.50, 0.01, 0.125, 0.20), # prompts <= 100K tokens
"claude-fable-5-2": (8.00, 40.00, 0.20, 10.00, 16.00),
}
FAST_MODE_FACTOR = 2.0
ECB_URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
def transcript_dir() -> Path:
repo = Path(__file__).resolve().parents[2]
return Path.home() / ".claude" / "projects" / re.sub(r"[^A-Za-z0-9]", "-", str(repo))
def parse_time(value: str) -> datetime:
parsed = datetime.fromisoformat(value)
return parsed if parsed.tzinfo else parsed.astimezone() # naive input = local time
def usd_to_eur() -> float:
with urllib.request.urlopen(ECB_URL, timeout=10) as response:
xml = response.read().decode()
match = re.search(r"currency='USD' rate='([0-9.]+)'", xml)
if not match:
raise RuntimeError("USD rate not found in ECB feed")
return 1 / float(match.group(1)) # ECB quotes USD per EUR
# Only the transcript fields we read; pydantic ignores the rest. Fields that some
# lines lack (user messages have no id or usage) are optional.
class CacheCreation(BaseModel):
ephemeral_5m_input_tokens: int = 0
ephemeral_1h_input_tokens: int = 0
class Usage(BaseModel):
input_tokens: int = 0
output_tokens: int = 0
cache_read_input_tokens: int = 0
cache_creation_input_tokens: int = 0
cache_creation: CacheCreation | None = None # missing in older entries
speed: str | None = None
def counts(self) -> tuple[int, int, int, int, int]:
"""Token counts in the same order as PRICES."""
if self.cache_creation is None:
write_5m, write_1h = self.cache_creation_input_tokens, 0
else:
write_5m = self.cache_creation.ephemeral_5m_input_tokens
write_1h = self.cache_creation.ephemeral_1h_input_tokens
return self.input_tokens, self.output_tokens, self.cache_read_input_tokens, write_5m, write_1h
def cost_usd(self, model: str) -> float | None:
"""API list price of this response, or None if the model has no price."""
if model not in PRICES:
return None
factor = FAST_MODE_FACTOR if self.speed == "fast" else 1.0
return factor * sum(n * p for n, p in zip(self.counts(), PRICES[model], strict=True)) / 1e6
class Message(BaseModel):
id: str | None = None
model: str = ""
usage: Usage | None = None
class TranscriptLine(BaseModel):
type: str = ""
timestamp: datetime | None = None
message: Message | None = None
class Response(BaseModel):
"""One model response, as counted."""
id: str
model: str
time: datetime
usage: Usage
def parse_response(line: str) -> Response | None:
"""The model response in one transcript line, or None for any other line."""
entry = TranscriptLine.model_validate_json(line)
message = entry.message
if entry.type != "assistant" or message is None or entry.timestamp is None:
return None
if message.id is None or message.usage is None:
return None
return Response(id=message.id, model=message.model, time=entry.timestamp, usage=message.usage)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--since", required=True, help="ISO time, e.g. 2026-11-15T10:00:00Z")
parser.add_argument("--until", help="ISO time (default: now)")
parser.add_argument("--usd-eur", type=float, help="fixed USD->EUR rate instead of the ECB lookup")
args = parser.parse_args()
since = parse_time(args.since)
until = parse_time(args.until) if args.until else datetime.now(UTC)
seen: set[str] = set()
tokens = {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0}
cost_usd = 0.0
sessions: set[str] = set()
unpriced: set[str] = set()
# Subagent transcripts live in subdirectories, hence rglob.
for path in sorted(transcript_dir().rglob("*.jsonl")):
for line in path.open(encoding="utf-8"):
response = parse_response(line)
# One response is split over several lines that repeat the same usage.
if response is None or response.id in seen or not since <= response.time <= until:
continue
seen.add(response.id)
sessions.add(path.stem)
counts = response.usage.counts()
tokens["input"] += counts[0]
tokens["output"] += counts[1]
tokens["cache_read"] += counts[2]
tokens["cache_write"] += counts[3] + counts[4]
cost = response.usage.cost_usd(response.model)
if cost is not None:
cost_usd += cost
elif sum(counts):
unpriced.add(response.model)
rate = args.usd_eur if args.usd_eur is not None else usd_to_eur()
total = sum(tokens.values())
print(f"Window: {since.isoformat()} .. {until.isoformat()}")
print(f"Sessions: {len(sessions)}, responses: {len(seen)}")
print(
f"Tokens: {total:,} (input {tokens['input']:,}, output {tokens['output']:,}, "
f"cache read {tokens['cache_read']:,}, cache write {tokens['cache_write']:,})"
)
print(f"Cost: ~EUR {cost_usd * rate:.2f} API-equivalent (USD {cost_usd:.2f} at {rate:.4f} EUR/USD)")
if unpriced:
print(f"Warning: no price for {', '.join(sorted(unpriced))}; not included in cost", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())