- conversations/pricing.py holds no table any more (MODEL_PRICES, FAMILY_FALLBACK,
FAST_MULT, HAIKU_LONG, OPENAI_*, GEMINI_*, OTHER_PRICES, LOCAL_WATTS,
ELECTRICITY_EUR_PER_KWH, EVOX2_*, PLAN_METER_AS, PLAN_FABLE_WEIGHT gone): a
facade over the provider plugins' registry, same names and signatures;
PRICE_BOOK / USD_PER_EUR / LOCAL_* derived lazily from the plugins;
book_key() replaces openai_model / gemini_model; price_call() exposed.
- plugins/seed_registry.py: effective() = the bound store's registry when it
has ever known a provider (strict plugin-only), else the default plugins
read from PLUGINS_SEED_DIR / the plugins checkout / fixtures — offline
parses, scripts and unit tests price with zero setup, no network.
- parser: each API call priced once through ProviderRegistry.price_call
(UsageMeter.price) — list cost, cache share and the EVOX2's time from the
CallCost, plan units passed apart into the meter; priceBook = price_book().
- projects/costs.py: rates + local outputWeight from provider-evox2's pricing.
- usage/service.remote_snapshots: one loop over the providers with a
usageReader, GET /usage/{vendor} on the lab and online workers, the legacy
/claude|opencode|agy/usage only on a 404 (or the lab not answering);
per-vendor merge policies keep the exact old results.
- providers.py: per-id memo of the claiming pricer and the token-table key
(fixed per registry) — the parse prices at the old speed.
- plugins/metering.py reads USD_PER_EUR at use time.
A/B: scripts/ab/pricing-dump.py --base 1e431f52 → identical (10104 lines);
scripts/ab/parse-ab.py --base 1e431f52 --chunked → 499 files × 2 modes,
0 differing; chunked == one-shot.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
434 lines
22 KiB
Python
434 lines
22 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 and saving, 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,
|
||
rates_for,
|
||
usage_cost,
|
||
usage_tokens,
|
||
zero_usage,
|
||
)
|
||
from .errors import _real_model
|
||
from .records import _ms
|
||
|
||
|
||
# The reply box treats a cache as expired this long before its TTL (frontend
|
||
# lib/freshContext.ts EXPIRY_MARGIN_MS): the TTL counts from the request.
|
||
FRESH_EXPIRY_MARGIN_MS = 2 * 60_000
|
||
|
||
# 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
|
||
# composer's fresh-context nudge reads both: 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
|
||
# What a `/compact` (the reply box's Fresh context, or one typed in a
|
||
# terminal) has saved so far, on its divider: each later call replays
|
||
# ``drop`` = pre-compaction context − the first call's prompt fewer
|
||
# tokens than continuing would have — at the cache-write rate on a
|
||
# turn's first call back to an expired cache, the read rate otherwise —
|
||
# up to the next compaction, less the compaction itself.
|
||
self._gain = None
|
||
self._gain_cold = False # the pending turn came back to a cold cache
|
||
# 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, a ``/compact``'s saving, 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
|
||
if tokens:
|
||
self.gain_call(nu, model, fallback_model)
|
||
# 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, pre = md.get("postTokens"), md.get("preTokens")
|
||
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}
|
||
# Only a `/compact` has a "continue" to compare with: an automatic one
|
||
# happens because the thread no longer fits.
|
||
self._gain = ({"item": item, "pre": pre, "drop": None, "gross": 0.0}
|
||
if item is not None and md.get("trigger") == "manual"
|
||
and isinstance(pre, int) and pre > 0 else None)
|
||
|
||
def gain_prompt(self, ts) -> None:
|
||
"""A typed prompt: does its first call come back to an expired cache
|
||
(the TTL, less the margin the reply box allows — the TTL counts from
|
||
the request, the transcript stamps the reply)?"""
|
||
a, b = _ms(self.last_call_at), _ms(ts)
|
||
ttl_ms = (self.cache_ttl or 3600) * 1000 - FRESH_EXPIRY_MARGIN_MS
|
||
self._gain_cold = a is not None and b is not None and b - a > ttl_ms
|
||
|
||
def gain_call(self, nu: dict, model, fallback_model) -> None:
|
||
"""One priced call after a `/compact`: add what continuing would
|
||
have paid on top, and restate the divider's net saving."""
|
||
cold, self._gain_cold = self._gain_cold, False
|
||
g = self._gain
|
||
if g is None:
|
||
return
|
||
prompt = int(nu["input"] + nu["cacheRead"] + nu["cacheWriteTokens"])
|
||
if g["drop"] is None:
|
||
g["drop"] = max(0, g["pre"] - prompt)
|
||
inp, _, read = rates_for(model or fallback_model or "")
|
||
write = inp * (1.25 if self.cache_ttl == 300 else 2.0)
|
||
g["gross"] += g["drop"] * (write if cold else read) / 1e6
|
||
item = g["item"]
|
||
item["compact"]["saved"] = round(g["gross"] - (item.get("turnCost") or 0.0), 4)
|
||
|
||
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
|