- frontend: drop the dead Conversations dashboard code (costAnalysis, DashboardFilters, ConversationsDashboard), the unused analytics / footprint / pricing helpers, the orphan api.ts comment and the dead mocks (perf dashboard, storage dashboard, telemetry hub/usage, usage daily/history/calibration); their French strings - backend: drop look.parse_action (the conversation-labels plugin has its own) and UsersStore.emails() (no caller) - routes: drop GET /api/usage/daily|history|calibration, GET /api/telemetry/usage, GET /api/goals, POST /api/goal-work — the plugin bridges call daily_usage, calibrate.history, views.usage, goals_list and goal_work directly; authz table + golden matrix updated; openapi.json re-dumped, src/generated regenerated - FALLBACK_ACCOUNTS: one neutral Claude seat instead of a stale copy of the providers' profiles (the full list moves to mock/accounts.ts) - notify CLI: no local PRICES estimate — the line is "Claude Code · 78k tokens · 8m" and the hub's restate_cost puts the run's exact list price in (an older CLI's $ line is still restated) - CLAUDE.md / docs / docstrings: scheduled/, templates/, sidecar *_usage.py, the clarifier (now the plugin's agents[] + prefs), runs/extras.py, sidecar/routes_chrome.py Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
242 lines
10 KiB
Python
242 lines
10 KiB
Python
"""Per-model pricing and the usage arithmetic every cost figure is built on.
|
||
|
||
The prices are no longer here: every rate, tier, plan meter and the EVOX2's
|
||
energy figures belong to the ``provider-*`` plugins (``provider-anthropic``,
|
||
``-openai``, ``-google``, ``-openrouter``, ``-evox2``) and are read through
|
||
``plugins.providers.ProviderRegistry``. This module is the facade the parser,
|
||
the rollups and the dashboards have always called — same names, same
|
||
signatures, same floats (``scripts/ab/pricing-dump.py`` holds it to the last
|
||
bit). Which registry answers is ``plugins.seed_registry.effective()``: the
|
||
running hub's own plugins (strict — a provider disabled later prices its
|
||
history from the registry's snapshot), or, in a process with no plugin store
|
||
(a standalone parse, a script, a unit test), the default plugins read from
|
||
the seed dir.
|
||
|
||
Two currencies come out of it, kept apart:
|
||
|
||
* **cost** — the API list price of the tokens, at the exact model version (and
|
||
speed) that produced them (``usage_cost`` / ``ProviderRegistry.price_call``).
|
||
A model on the EVOX2 has no API: its cost is the box's electricity and
|
||
amortisation for the time it worked (``local_call``).
|
||
* **plan units** — what the subscription's usage limits appear to count
|
||
(``plan_units``, the provider's ``planMeter``): a Claude model is metered
|
||
at its predecessor's price, a Fable token weighs ~1.75×; an OpenAI or
|
||
Gemini model at its list price; anything else (OpenRouter, the EVOX2) 0.
|
||
``plan_pct`` turns units into "% of the 5h / week window" with a
|
||
per-account calibration (docs/usage-calibration.md).
|
||
"""
|
||
|
||
from plugins import seed_registry
|
||
|
||
# ── the registry that answers ────────────────────────────────────────────────
|
||
|
||
|
||
def registry():
|
||
"""The ``ProviderRegistry`` every figure below comes from."""
|
||
return seed_registry.effective()
|
||
|
||
|
||
def _local_pricer(model: str | None = None):
|
||
"""The ``local_energy`` pricer (the EVOX2's), the one running ``model``
|
||
first; None when no such provider is known."""
|
||
reg = registry()
|
||
pool = reg._pricers + reg._stale_pricers
|
||
if model is not None:
|
||
hit = next((p for p in pool if p.kind == "local_energy" and p.is_local(model)), None)
|
||
if hit is not None:
|
||
return hit
|
||
return next((p for p in pool if p.kind == "local_energy"), None)
|
||
|
||
|
||
def price_book() -> str:
|
||
"""The newest ``bookDate`` of the active providers' pricing — stamped on
|
||
every parsed summary (``priceBook``) so a figure can be traced to the
|
||
book that made it."""
|
||
dates = [(p.pricing or {}).get("bookDate") for p in registry().providers.values()]
|
||
return max((d for d in dates if d), default="")
|
||
|
||
|
||
# Constants kept for their readers, now derived from the plugins (read lazily:
|
||
# the registry isn't bound when this module is imported).
|
||
_LAZY = {
|
||
"PRICE_BOOK": price_book,
|
||
"USD_PER_EUR": lambda: (_local_pricer() or _NoLocal).p["usdPerEur"],
|
||
"LOCAL_CALL_CAP_S": lambda: (_local_pricer() or _NoLocal).p["callCapSeconds"],
|
||
"LOCAL_WATTS_DEFAULT": lambda: (_local_pricer() or _NoLocal).p["defaultWatts"],
|
||
"LOCAL_OUTPUT_WEIGHT": lambda: local_output_weight(),
|
||
}
|
||
|
||
|
||
class _NoLocal:
|
||
p = {"usdPerEur": 1 / 0.92, "callCapSeconds": 3600, "defaultWatts": 0.0,
|
||
"outputWeight": 1}
|
||
|
||
|
||
def __getattr__(name: str):
|
||
fn = _LAZY.get(name)
|
||
if fn is None:
|
||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||
return fn()
|
||
|
||
|
||
# ── the EVOX2 ────────────────────────────────────────────────────────────────
|
||
|
||
|
||
def local_watts(model: str | None) -> float:
|
||
"""Calibrated wall power of the EVOX2 running `model` (pi id, or its
|
||
opencode twin ``evox2…/<pi id>``)."""
|
||
pr = _local_pricer(model)
|
||
if pr is None:
|
||
return 0.0
|
||
base = pr.local_base(model) or model or ""
|
||
return pr.watts.get(base, pr.p["defaultWatts"])
|
||
|
||
|
||
def electricity_eur_per_kwh(ts: str | None) -> float:
|
||
"""The tariff in force on an ISO timestamp's date (the oldest one before
|
||
the table starts, the latest one without a date)."""
|
||
pr = _local_pricer()
|
||
if pr is None:
|
||
return 0.0
|
||
tariffs = pr.p["electricityTariffs"]
|
||
day = (ts or "9999")[:10]
|
||
price = tariffs[0][1]
|
||
for since, p in tariffs:
|
||
if day >= since:
|
||
price = p
|
||
return price
|
||
|
||
|
||
def hardware_eur_per_hour() -> float:
|
||
"""The EVOX2's amortisation per busy hour."""
|
||
pr = _local_pricer()
|
||
if pr is None:
|
||
return 0.0
|
||
p = pr.p
|
||
return p["hardwarePriceEur"] / (p["lifetimeYears"] * p["busyHoursPerYear"])
|
||
|
||
|
||
def local_output_weight() -> float:
|
||
"""How much longer an output token keeps the box busy than a prompt one —
|
||
a local run's cost split per token type follows the box's time
|
||
(``projects/costs.py``)."""
|
||
pr = _local_pricer()
|
||
return (pr.p.get("outputWeight") if pr is not None else None) or 1
|
||
|
||
|
||
def local_call(model: str | None, ms: float | None, ts: str | None) -> dict:
|
||
"""One local call's energy and cost: ``{seconds, wh, electricity,
|
||
hardware}`` (costs in USD). A call with no measurable duration is free."""
|
||
return registry().local_call(model, ms, ts)
|
||
|
||
|
||
def is_local(model: str | None) -> bool:
|
||
"""A model the EVOX2 runs (its tokens are free; its time is the cost)."""
|
||
return registry().is_local(model)
|
||
|
||
|
||
# ── rates ────────────────────────────────────────────────────────────────────
|
||
|
||
|
||
def rates_for(model: str) -> tuple[float, float, float]:
|
||
"""(input, output, cache-read) price in USD / million tokens for a model:
|
||
the provider whose pricing claims the id (an OpenAI or Gemini id, an
|
||
EVOX2-local one — free —, a vendor-prefixed OpenRouter id from its
|
||
catalogue, a Claude id by version or family), else the catch-all's."""
|
||
return registry().rates_for(model)
|
||
|
||
|
||
def book_key(model: str | None) -> tuple[str, str, str | None] | None:
|
||
"""``(vendor, book key, mode)`` for an id a ``token_table`` provider
|
||
prices (``gpt-6.2-sol-fast`` → ``("openai", "gpt-6.1-sol", "fast")``,
|
||
``gemini-4-neon-high`` → ``("google", "gemini-4-neon", None)``), else None
|
||
(a vendor-prefixed OpenRouter id, an EVOX2 model, an unknown id)."""
|
||
reg = registry()
|
||
pr = reg._pricer_for(model)
|
||
if pr is None or pr.kind != "token_table":
|
||
return None
|
||
hit = pr._token_key(model or "")
|
||
return (pr.vendor, hit[0], hit[1]) if hit else None
|
||
|
||
|
||
def price_for(model: str) -> tuple[float, float]:
|
||
"""(input, output) $/Mtok — `rates_for` without the cache-read rate."""
|
||
pi, po, _ = rates_for(model)
|
||
return pi, po
|
||
|
||
|
||
# ── usage arithmetic ─────────────────────────────────────────────────────────
|
||
|
||
|
||
def norm_usage(u: dict) -> dict:
|
||
cc = u.get("cache_creation") or {}
|
||
c5 = cc.get("ephemeral_5m_input_tokens", 0) or 0
|
||
c1 = cc.get("ephemeral_1h_input_tokens", 0) or 0
|
||
flat = u.get("cache_creation_input_tokens", 0) or 0
|
||
split = c5 + c1
|
||
return {
|
||
"input": u.get("input_tokens", 0) or 0,
|
||
"output": u.get("output_tokens", 0) or 0,
|
||
"cacheRead": u.get("cache_read_input_tokens", 0) or 0,
|
||
"cacheWriteTokens": split if split else flat,
|
||
"cacheWriteUnits": (c5 * 1.25 + c1 * 2.0) if split else flat * 1.25,
|
||
}
|
||
|
||
|
||
def add_usage(a: dict, b: dict) -> dict:
|
||
return {k: a[k] + b[k] for k in a}
|
||
|
||
|
||
def zero_usage() -> dict:
|
||
return {"input": 0, "output": 0, "cacheRead": 0,
|
||
"cacheWriteTokens": 0, "cacheWriteUnits": 0.0}
|
||
|
||
|
||
def usage_tokens(u: dict) -> int:
|
||
return int(u["input"] + u["cacheWriteTokens"] + u["cacheRead"] + u["output"])
|
||
|
||
|
||
def usage_type_costs(u: dict, model: str) -> dict[str, float]:
|
||
"""The list price kept apart per token type (``input`` / ``output`` /
|
||
``cacheRead`` / ``cacheWrite``), at `model`'s base rates: an OpenAI id's
|
||
``-fast`` / ``-ultrafast`` multiple is in (it is part of the id), the
|
||
per-call tiers are not — Claude's fast mode, Haiku's and OpenAI's long
|
||
prompt need each call's speed and prompt size, which a usage *sum* has
|
||
lost. A caller holding the recorded cost rescales these shares to it
|
||
(``projects/costs.py``; the frontend's ``splitByType`` does the same)."""
|
||
pi, po, pc = (r / 1e6 for r in rates_for(model))
|
||
return {"input": u["input"] * pi, "output": u["output"] * po,
|
||
"cacheRead": u["cacheRead"] * pc, "cacheWrite": u["cacheWriteUnits"] * pi}
|
||
|
||
|
||
def usage_cost(u: dict, model: str, speed: str | None = None) -> float:
|
||
"""List price of one usage block at `model` (and `speed`). Exact per API
|
||
call; on a usage *sum* the long-prompt tier can't apply (prompt sizes are
|
||
gone), which is why the parser prices every call on its own."""
|
||
return registry().usage_cost(model, u, speed)
|
||
|
||
|
||
def usage_cache_cost(u: dict, model: str, speed: str | None = None) -> float:
|
||
"""The share of a turn's cost that is replayed cached prompt (billed at the
|
||
model's own cache-read rate). The rest is fresh tokens the model actually
|
||
had to read or write this turn."""
|
||
return registry().usage_cache_cost(model, u, speed)
|
||
|
||
|
||
def plan_units(u: dict, model: str, speed: str | None = None) -> float:
|
||
"""What a usage block weighs on the subscription's usage limits — the
|
||
provider's ``planMeter``, apart from the list price: a Claude model's
|
||
tokens priced as the model they are metered as, Fable/Mythos weighted;
|
||
an OpenAI or Gemini model at its plain list price (the per-account
|
||
calibration fits $ per 1 % of the week directly — usage/calibrate.py);
|
||
0 for a model no plan meters (OpenRouter, the EVOX2)."""
|
||
return registry().plan_units(model, u, speed=speed)
|
||
|
||
|
||
def price_call(model: str, usage: dict, *, speed: str | None = None,
|
||
record: dict | None = None, elapsed_ms: float | None = None,
|
||
at: str | None = None):
|
||
"""One API call's ``CallCost`` (``ProviderRegistry.price_call``)."""
|
||
return registry().price_call(model, usage, speed=speed, record=record,
|
||
elapsed_ms=elapsed_ms, at=at)
|