fix: parse transcripts with pydantic models in ticket-cost script
CI / checks (pull_request) Successful in 13s
CI / checks (pull_request) Successful in 13s
json.loads returned untyped data, which failed strict type checking. pyright never reported it because it skips the .claude/ folder.
This commit is contained in:
1 parent
e91d05497d
commit
eb49c71937
4 files changed
+220
-35
No files matched your search
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
#!/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
|
||||
@@ -6,20 +6,21 @@ project and sums the token usage of every model response between --since and --u
|
||||
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:
|
||||
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 json
|
||||
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]] = {
|
||||
@@ -51,32 +52,68 @@ def usd_to_eur() -> float:
|
||||
return 1 / float(match.group(1)) # ECB quotes USD per EUR
|
||||
|
||||
|
||||
Counts = tuple[int, int, int, int, int] # same order as PRICES
|
||||
# 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
|
||||
|
||||
|
||||
def parse_response(line: str) -> tuple[str, str, datetime, Counts, bool] | None:
|
||||
"""(response id, model, time, token counts, fast mode) of one transcript line, or None."""
|
||||
entry = json.loads(line)
|
||||
message = entry.get("message")
|
||||
if entry.get("type") != "assistant" or not isinstance(message, dict):
|
||||
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
|
||||
usage = message.get("usage")
|
||||
if not message.get("id") or not usage or not entry.get("timestamp"):
|
||||
if message.id is None or message.usage is None:
|
||||
return None
|
||||
cache_write = usage.get("cache_creation") or {}
|
||||
write_5m = cache_write.get("ephemeral_5m_input_tokens", 0)
|
||||
write_1h = cache_write.get("ephemeral_1h_input_tokens", 0)
|
||||
if not cache_write: # older entries without the TTL breakdown
|
||||
write_5m = usage.get("cache_creation_input_tokens", 0)
|
||||
counts: Counts = (
|
||||
usage.get("input_tokens", 0),
|
||||
usage.get("output_tokens", 0),
|
||||
usage.get("cache_read_input_tokens", 0),
|
||||
write_5m,
|
||||
write_1h,
|
||||
)
|
||||
time = parse_time(entry["timestamp"])
|
||||
return message["id"], message.get("model", ""), time, counts, usage.get("speed") == "fast"
|
||||
return Response(id=message.id, model=message.model, time=entry.timestamp, usage=message.usage)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
@@ -98,22 +135,22 @@ def main() -> int:
|
||||
# Subagent transcripts live in subdirectories, hence rglob.
|
||||
for path in sorted(transcript_dir().rglob("*.jsonl")):
|
||||
for line in path.open(encoding="utf-8"):
|
||||
parsed = parse_response(line)
|
||||
response = parse_response(line)
|
||||
# One response is split over several lines that repeat the same usage.
|
||||
if parsed is None or parsed[0] in seen or not since <= parsed[2] <= until:
|
||||
if response is None or response.id in seen or not since <= response.time <= until:
|
||||
continue
|
||||
msg_id, model, _, counts, fast = parsed
|
||||
seen.add(msg_id)
|
||||
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]
|
||||
if model in PRICES:
|
||||
factor = FAST_MODE_FACTOR if fast else 1.0
|
||||
cost_usd += factor * sum(n * p for n, p in zip(counts, PRICES[model], strict=True)) / 1e6
|
||||
cost = response.usage.cost_usd(response.model)
|
||||
if cost is not None:
|
||||
cost_usd += cost
|
||||
elif sum(counts):
|
||||
unpriced.add(model)
|
||||
unpriced.add(response.model)
|
||||
|
||||
rate = args.usd_eur if args.usd_eur is not None else usd_to_eur()
|
||||
total = sum(tokens.values())
|
||||
|
||||
Reference in new issue
Block a user