"""Dollars a chunk's messages cost, by project, subagent type, rung and tool: each model's recorded cost split across its messages by their list prices.""" import collections import dataclasses import typing from claude_code.entries import messages as claude_messages, CostState, Entry, ToolCall from model_routing.prices import listed DIMENSIONS = ("project", "subagent type", "rung", "tool") # Each of DIMENSIONS to its labels' dollars. Dollars = dict[str, collections.defaultdict[str, float]] # The tool label of a message that follows no tool call, such as the first message after a prompt. PROMPT = "prompt" # The subagent type the judge's runs are counted under; the judge is no subagent, and has no tools, so its dollars count towards PROMPT. JUDGE = "judge" @dataclasses.dataclass(frozen=True) class Message: """An assistant message, counted once: when it was written, the tools whose results it took in, the model that wrote it and what its usage costs at list prices.""" at: str tools: list[str] model: str list_price: float class Spent(typing.NamedTuple): """A message with the subagent type that wrote it, or `worker`, and the rung it ran on.""" kind: str rung: str message: Message def messages(entries: list[Entry]) -> list[Message]: """The assistant messages, counted once each, each with the tools whose results it took in, or `prompt` where it took none in.""" counted = [] before = [PROMPT] for turns in claude_messages(entries): turn = turns[0] counted.append(Message(turn.timestamp, before, turn.model, listed(turn.model, turn.usage))) before = [part.name for each in turns for part in each.parts if isinstance(part, ToolCall)] or [PROMPT] return counted def recorded_costs(worker: list[Entry]) -> dict[str, float]: """The cost the worker transcript's last cost-state entry records for each model.""" return next((entry.costs for entry in reversed(worker) if isinstance(entry, CostState)), {}) def costed(spent: list[Spent], judged: list[tuple[str, float]], project: str, recorded: dict[str, float]) -> tuple[Dollars, float]: """Each message's dollars by DIMENSIONS, with each judge run's cost in judged, by the judge's rung, under the subagent type JUDGE and the tool PROMPT; and the recorded cost left over, that of a recorded model with no priced message. A model's recorded cost is split across its messages in proportion to their list prices, so the calls no message records, such as compactions, are counted. A subagent transcript the archive lacks puts its cost on the archived messages of the model that ran it, in the same proportion. A model the record omits keeps its list prices.""" listed_by_model: collections.defaultdict[str, float] = collections.defaultdict(float) for _, _, message in spent: listed_by_model[message.model] += message.list_price scale = {model: recorded[model] / total for model, total in listed_by_model.items() if total and model in recorded} dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS} for kind, rung, message in spent: cost = message.list_price * scale.get(message.model, 1.0) dollars["project"][project] += cost dollars["subagent type"][kind] += cost dollars["rung"][rung] += cost for tool in message.tools: dollars["tool"][tool] += cost / len(message.tools) for rung, cost in judged: dollars["project"][project] += cost dollars["subagent type"][JUDGE] += cost dollars["rung"][rung] += cost dollars["tool"][PROMPT] += cost return dollars, sum(cost for model, cost in recorded.items() if not listed_by_model[model])