Files

390 lines
20 KiB
Python

"""What a conversation's API calls used and cost: ``UsageMeter`` (owned by
``ParserState`` as ``state.usage``) — totals, the per-model / per-effort split,
plan units, hour bins, the EVOX2's share, the context size and cache TTL, a
``/compact``'s cost, the first call's context split and the
by-activity breakdown — plus its helpers (per-turn deltas, the first-call
estimate, the CLI's cumulative ``cost-state`` records)."""
import models
from ..pricing import (
add_usage,
norm_usage,
plan_units,
price_call,
usage_cost,
usage_tokens,
zero_usage,
)
from .errors import _real_model
from .records import _ms
# Per-turn delta fields a thread item carries for the call that produced it.
_DELTA_KEYS = ("turnTokens", "turnCost", "turnCacheTokens", "turnCacheCost",
"turnBucket", "turnContextCost", "turnContextTokens")
def _sub_usage(a: dict, b: dict) -> dict:
return {k: a[k] - b[k] for k in a}
# The session's first API call pays for far more than the user's typed message:
# the harness front-loads the system prompt, tool definitions, CLAUDE.md files,
# memories and other <system-reminder> context into it. The API reports only the
# combined total, so we estimate the actual message's share from its length and
# attribute the rest of that first input side to context loading.
EST_CHARS_PER_TOKEN = 4
def _est_tokens(text: str | None) -> int:
"""Rough token estimate for a text (~4 chars/token), 0 for empty."""
return max(1, len(text) // EST_CHARS_PER_TOKEN) if text else 0
_COST_STATE_KEYS = {"input": "inputTokens", "output": "outputTokens",
"cacheRead": "cacheReadInputTokens",
"c5": "cacheCreationEphemeral5mInputTokens",
"c1": "cacheCreationEphemeral1hInputTokens",
"flat": "cacheCreationInputTokens"}
def _cost_state_delta(cur: dict, prev: dict, seen: dict | None) -> dict | None:
"""One model's usage between two ``cost-state`` records, less what the
transcript's own calls already account for — as a ``norm_usage`` dict, or
None when nothing is left."""
d = {k: max(0, int(cur.get(f) or 0) - int(prev.get(f) or 0))
for k, f in _COST_STATE_KEYS.items()}
nu = norm_usage({"input_tokens": d["input"], "output_tokens": d["output"],
"cache_read_input_tokens": d["cacheRead"],
"cache_creation_input_tokens": d["flat"],
"cache_creation": {"ephemeral_5m_input_tokens": d["c5"],
"ephemeral_1h_input_tokens": d["c1"]}})
if seen:
nu = {k: max(0, nu[k] - seen.get(k, 0)) for k in nu}
return nu if usage_tokens(nu) > 0 else None
def norm(ev: dict) -> dict:
"""A ``usage`` event → the parser's usage dict (``pricing.norm_usage``'s
shape and arithmetic: a TTL split, when there is one, wins over the
unsplit ``cacheWrite``)."""
c5 = ev.get("cacheWrite5m", 0) or 0
c1 = ev.get("cacheWrite1h", 0) or 0
flat = ev.get("cacheWrite", 0) or 0
split = c5 + c1
return {
"input": ev.get("input", 0) or 0,
"output": ev.get("output", 0) or 0,
"cacheRead": ev.get("cacheRead", 0) or 0,
"cacheWriteTokens": split if split else flat,
"cacheWriteUnits": (c5 * 1.25 + c1 * 2.0) if split else flat * 1.25,
}
_COST_DELTA_KEYS = ("input", "output", "cacheRead", "cacheWrite5m", "cacheWrite1h",
"cacheWrite")
def _cost_delta(cur: dict, prev: dict, seen: dict | None) -> dict | None:
"""``_cost_state_delta`` over a ``cost_state`` event's neutral counts."""
d = {k: max(0, int(cur.get(k) or 0) - int(prev.get(k) or 0))
for k in _COST_DELTA_KEYS}
nu = norm(d)
if seen:
nu = {k: max(0, nu[k] - seen.get(k, 0)) for k in nu}
return nu if usage_tokens(nu) > 0 else None
class UsageMeter:
"""The money side of one transcript. ``ParserState`` decides which records
are API calls and what they drove (bucket, sub-label, thread items); this
accumulates what they used and cost. Every field is a running total that
``ParserState.summary()`` reads; nothing here reads the thread."""
def __init__(self):
self.agg = zero_usage()
# What the subscription's usage limits count for these calls (see
# pricing.plan_units), the per-model / per-effort split of every
# figure, and hour-bin meters (epoch hour -> [list $, plan units]) the
# plan-usage calibration bins against the official /usage %.
self.plan_units = 0.0
self.by_model: dict[str, dict] = {}
self.meter_bins: dict[int, list[float]] = {}
self.fast_calls = 0
# Total cost, accumulated per assistant record: the record's own
# `costUSD` (pi harness — the runner mirrors pi's real provider cost)
# when present, else the price table estimate for that turn's model; a
# call on the EVOX2 is priced from its duration instead (`local`).
# Summing per-turn also prices mixed-model sessions correctly (the old
# aggregate used one model).
self.cost_total = 0.0
# The EVOX2's share: busy seconds, Wh drawn, and the cost (USD) split
# into electricity and hardware amortisation (the EVOX2 provider's
# local_energy pricing, ``CallCost.local``).
self.local = {"seconds": 0.0, "wh": 0.0, "electricity": 0.0, "hardware": 0.0}
# The conversation's current context size: the *last* assistant API
# call's full prompt+reply — how full the context window is now.
self.context_tokens = 0
self.context_model = None
# When that last call was made, and how long the prompt cache it wrote
# lives (the TTL tier of the session's latest cache write: 3600 s for
# the 1-hour tier Claude Code uses, 300 s for the 5-minute one). The
# fresh-context plugin reads both (through hub feeds): past the TTL, the next
# turn re-writes the whole context instead of reading it from cache.
self.last_call_at = None
self.cache_ttl = None
# Compactions (`/compact`, or the CLI's own at the context limit): the
# `compact_boundary` record resets what the next call replays. The
# compaction's own API call is not an assistant record, so its cost is
# read off the CLI's cumulative `cost-state` (see `_cost_state`).
self.compactions = 0
self._cost_state = None # the last cost-state's per-model usage
self._since_cost_state: dict[str, dict] = {} # transcript usage since it
self._compact_pending = None # a boundary whose cost is still to come
# First-turn split: the first API call's input side divided into the
# injected context (system prompt, CLAUDE.md, memories, …) and the
# user's actual first message (estimated from its length). Filled once,
# on the first usage-bearing assistant record.
self.first_context_tokens = None
self.first_message_tokens = None
self._first_split_done = False
self.by_tool: dict[str, dict] = {} # bucket -> accumulated usage
# …and its cost, accumulated per turn at *that turn's* model. Pricing the
# summed usage with one model at the end (what this used to do) overcharges
# a session that switched models mid-thread, so the breakdown no longer
# added up to `cost_total`. Same reason `cost_total` accumulates per turn.
self.by_tool_cost: dict[str, float] = {}
# Second-level breakdown: bucket -> sub-label -> usage (bash by program,
# read/edit by file extension, msg by prompt/replies).
self.by_tool_sub: dict[str, dict[str, dict]] = {}
self.by_tool_sub_cost: dict[str, dict[str, float]] = {}
def price(self, ts, model, speed, nu: dict, u: dict, elapsed_ms):
"""One API call's money, from its provider
(``ProviderRegistry.price_call``): the theoretical list ``cost`` (the
record's own ``cost.usd`` when the harness reported one — pi's runner
—, the box's time on the EVOX2, whose share is added to ``local``),
the replayed cache's share of it, and — apart — the ``plan_units`` it
weighs on the subscription's limits. Returns the ``CallCost``."""
cc = price_call(model, nu, speed=speed, record=u, elapsed_ms=elapsed_ms, at=ts)
if cc.local is not None:
for k, v in cc.local.items():
self.local[k] += v
return cc
def priced_call(self, ts, model, effort, speed, u: dict, nu: dict,
cost: float, tokens: int, fallback_model,
units: float | None = None) -> None:
"""One priced API call the transcript shows (``nu`` = its normalised
usage, ``u`` its ``usage`` event, ``tokens`` = usage_tokens(nu),
``units`` its ``CallCost.plan_units``): meters, context size + cache
TTL, cost-state bookkeeping."""
self.meter(ts, model, effort, speed, nu, cost, units)
if tokens:
self.context_tokens = tokens
self.context_model = model
self.last_call_at = ts or self.last_call_at
if u.get("cacheWrite1h"):
self.cache_ttl = 3600
elif u.get("cacheWrite5m"):
self.cache_ttl = 300
# A call the transcript shows — not the compaction's hidden one.
self._compact_pending = None
if model:
seen = self._since_cost_state.get(model, zero_usage())
self._since_cost_state[model] = add_usage(seen, nu)
def first_split(self, nu: dict, first_user) -> tuple[dict | None, int] | None:
"""The session's first API call (the first usage-bearing record): split
its input side into injected context vs the user's actual message (see
EST_CHARS_PER_TOKEN). Returns ``(first_ctx_u, in_side)`` — the context
share as a usage dict (None when there is none), peeled off this turn's
bucket attribution — or None after the first call."""
if self._first_split_done:
return None
first_ctx_u = None
self._first_split_done = True
in_side = nu["input"] + nu["cacheRead"] + nu["cacheWriteTokens"]
msg_tok = min(_est_tokens(first_user), in_side)
self.first_message_tokens = msg_tok
self.first_context_tokens = in_side - msg_tok
if in_side > 0 and self.first_context_tokens > 0:
f = self.first_context_tokens / in_side
first_ctx_u = {
"input": round(nu["input"] * f),
"output": 0,
"cacheRead": round(nu["cacheRead"] * f),
"cacheWriteTokens": round(nu["cacheWriteTokens"] * f),
"cacheWriteUnits": nu["cacheWriteUnits"] * f,
}
return first_ctx_u, in_side
def charge(self, bucket: str, subkey, nu: dict, first_ctx_u: dict | None,
model, turn_cost: float):
"""Charge one priced call to its activity ``bucket`` (and sub-label).
Returns ``(turn_u, ctx_cost, own_cost, reply_cost)``: the usage and
cost the bucket got (the first call's context share goes to
``context``), and — for a plain message (``msg``) — the reply's share
of the cost (None otherwise)."""
turn_u = nu
# This turn's cost, split the same way its usage is. Accumulating
# the cost here — at this turn's model, and from `turn_cost` (which
# a pi record's real `costUSD` may have overridden) — is what keeps
# the breakdown summing to `cost_total`.
ctx_cost = 0.0
if first_ctx_u is not None:
# First turn: the injected-context share goes to its own
# top-level "context" bucket; only the remainder (the actual
# message + this turn's output) is attributed as usual.
turn_u = {k: nu[k] - first_ctx_u[k] for k in nu}
self.by_tool["context"] = add_usage(
self.by_tool.get("context", zero_usage()), first_ctx_u)
est = usage_cost(nu, model)
share = (usage_cost(first_ctx_u, model) / est) if est > 0 else 0.0
ctx_cost = turn_cost * share
self.by_tool_cost["context"] = \
self.by_tool_cost.get("context", 0.0) + ctx_cost
self.by_tool[bucket] = add_usage(self.by_tool.get(bucket, zero_usage()), turn_u)
own_cost = turn_cost - ctx_cost
self.by_tool_cost[bucket] = \
self.by_tool_cost.get(bucket, 0.0) + own_cost
subs = self.by_tool_sub.setdefault(bucket, {})
sub_costs = self.by_tool_sub_cost.setdefault(bucket, {})
reply_cost = None
if bucket == "msg":
# A plain messaging turn: split its usage into the prompt side
# (everything fed in) and the reply (what the model produced) —
# and its cost the same way, so the subs sum to their bucket.
prompt_u = {**turn_u, "output": 0}
reply_u = {**zero_usage(), "output": turn_u["output"]}
subs["prompt"] = add_usage(subs.get("prompt", zero_usage()),
prompt_u)
subs["replies"] = add_usage(subs.get("replies", zero_usage()),
reply_u)
est = usage_cost(turn_u, model)
reply_share = (usage_cost(reply_u, model) / est) if est > 0 else 0.0
reply_cost = own_cost * reply_share
sub_costs["replies"] = sub_costs.get("replies", 0.0) + reply_cost
sub_costs["prompt"] = \
sub_costs.get("prompt", 0.0) + (own_cost - reply_cost)
else:
sk = subkey or "?"
subs[sk] = add_usage(subs.get(sk, zero_usage()), turn_u)
sub_costs[sk] = sub_costs.get(sk, 0.0) + own_cost
return turn_u, ctx_cost, own_cost, reply_cost
def move_charge(self, call: dict, bucket, subkey) -> None:
"""A later record of an already-priced call carries its tool: when the
call was charged to ``msg``, move the charge to that tool's bucket
(``ParserState._rehome`` moves the delta badge)."""
if bucket and call["bucket"] == "msg":
u, c = call["u"], call["cost"]
self.by_tool["msg"] = _sub_usage(self.by_tool.get("msg", zero_usage()), u)
self.by_tool_cost["msg"] = self.by_tool_cost.get("msg", 0.0) - c
subs = self.by_tool_sub.setdefault("msg", {})
sub_costs = self.by_tool_sub_cost.setdefault("msg", {})
prompt_u = {**u, "output": 0}
reply_u = {**zero_usage(), "output": u["output"]}
rc = call.get("reply_cost", 0.0)
subs["prompt"] = _sub_usage(subs.get("prompt", zero_usage()), prompt_u)
subs["replies"] = _sub_usage(subs.get("replies", zero_usage()), reply_u)
sub_costs["prompt"] = sub_costs.get("prompt", 0.0) - (c - rc)
sub_costs["replies"] = sub_costs.get("replies", 0.0) - rc
if usage_tokens(self.by_tool["msg"]) <= 0:
for d in (self.by_tool, self.by_tool_cost, self.by_tool_sub,
self.by_tool_sub_cost):
d.pop("msg", None)
sk = subkey or "?"
self.by_tool[bucket] = add_usage(self.by_tool.get(bucket, zero_usage()), u)
self.by_tool_cost[bucket] = self.by_tool_cost.get(bucket, 0.0) + c
tsubs = self.by_tool_sub.setdefault(bucket, {})
tcosts = self.by_tool_sub_cost.setdefault(bucket, {})
tsubs[sk] = add_usage(tsubs.get(sk, zero_usage()), u)
tcosts[sk] = tcosts.get(sk, 0.0) + c
call["bucket"], call["subkey"] = bucket, sk
call.pop("reply_cost", None)
if call["item"] is not None:
call["item"]["turnBucket"] = bucket
def compaction(self, md: dict, item: dict | None, ts) -> None:
"""A ``compact_boundary`` (``md`` = its compactMetadata, ``item`` its
divider in full mode): the context the next call replays is now the
summary (``postTokens``) on top of the injected context; the
compaction's cost comes with the next cost-state record."""
post = md.get("postTokens")
self.compactions += 1
if isinstance(post, int) and post > 0:
self.context_tokens = (self.first_context_tokens or 0) + post
self._compact_pending = {"item": item, "ts": ts}
def cost_state(self, mu: dict) -> None:
"""The CLI's cumulative per-model spend, written as a process exits (a
``meta`` event of kind ``cost_state``: model → neutral token counts).
Right after a compaction (nothing billed in between), what it grew by
beyond the calls the transcript shows is the compaction's own call —
charged to the "context" bucket and onto the divider."""
prev, since = self._cost_state, self._since_cost_state
self._cost_state, self._since_cost_state = mu, {}
pending, self._compact_pending = self._compact_pending, None
if pending is None or prev is None:
return
total_u, total_cost, top = zero_usage(), 0.0, None
for model, cur in mu.items():
if not isinstance(cur, dict):
continue
nu = _cost_delta(cur, prev.get(model) or {}, since.get(model))
if nu is None:
continue
cost = usage_cost(nu, model)
total_u, total_cost = add_usage(total_u, nu), total_cost + cost
self.meter(pending["ts"], model, None, None, nu, cost)
if top is None or cost > top[1]:
top = (model, cost)
if top is None:
return
self.agg = add_usage(self.agg, total_u)
self.cost_total += total_cost
self.by_tool["context"] = add_usage(self.by_tool.get("context", zero_usage()), total_u)
self.by_tool_cost["context"] = self.by_tool_cost.get("context", 0.0) + total_cost
item = pending["item"]
if item is not None:
item["model"] = top[0]
item["turnTokens"] = usage_tokens(total_u)
item["turnCost"] = total_cost
item["turnBucket"] = "context"
def meter(self, ts, model, effort, speed, nu: dict, cost: float,
units: float | None = None) -> None:
"""Account one priced API call: plan units (``units`` when its
``CallCost`` carries them, else the provider's plan meter), the
per-model / per-effort split, and the hour-bin meter the plan-usage
calibration reads."""
if units is None:
units = plan_units(nu, model, speed)
self.plan_units += units
if speed == "fast":
self.fast_calls += 1
if _real_model(model):
bm = self.by_model.setdefault(model, {
"turns": 0, "usage": zero_usage(), "cost": 0.0, "planUnits": 0.0,
"efforts": {}})
bm["turns"] += 1
bm["usage"] = add_usage(bm["usage"], nu)
bm["cost"] += cost
bm["planUnits"] += units
eff = effort.strip().lower() if isinstance(effort, str) and effort.strip() else "none"
be = bm["efforts"].setdefault(eff, {"turns": 0, "tokens": 0, "output": 0,
"cost": 0.0, "planUnits": 0.0})
be["turns"] += 1
be["tokens"] += usage_tokens(nu)
be["output"] += nu["output"]
be["cost"] += cost
be["planUnits"] += units
ms = _ms(ts)
# The plan meter's $ is list price; the EVOX2's time is no plan's.
if ms is not None and not models.is_local(model):
hb = self.meter_bins.setdefault(int(ms // 3_600_000), [0.0, 0.0])
hb[0] += cost
hb[1] += units