- 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>
151 lines
6.8 KiB
Python
151 lines
6.8 KiB
Python
"""Aggregate Claude conversation spend per homelab project.
|
|
|
|
A conversation is attributed to a project when the project's directory name
|
|
appears in its inferred ``projectsAuto`` list (projects it created/edited files
|
|
in) *or* the manual ``projects`` list in the action-metadata sidecar — the exact
|
|
same union the viewer uses to decide which conversations to list on a project
|
|
page (``meta.projects``). Every
|
|
attributed conversation's real per-turn usage is rolled up into a per-project
|
|
total: dollar/token totals, mean/median per conversation, and a per-token-type
|
|
($ + tokens) breakdown. The project *detail* view additionally divides the total
|
|
by the project's lines of code (see ``projects.count_loc``).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from statistics import median
|
|
|
|
import projects as projects_mod
|
|
|
|
from conversations import pricing
|
|
from conversations import usage_cost, usage_tokens, usage_type_costs, zero_usage
|
|
|
|
# Token types we break spend down by, in display order. Each carries its own
|
|
# token count and dollar cost (priced with the conversation's model).
|
|
TYPES = ("input", "output", "cacheRead", "cacheWrite")
|
|
|
|
|
|
def _project_slugs(summary: dict, meta_all: dict,
|
|
fallback_for=None) -> set[str]:
|
|
"""The set of project dir-names a conversation is attributed to.
|
|
|
|
Conversations with no project of their own roll up into the root project
|
|
(see ``projects.attributed_projects``), exactly as in ``main._conv_meta`` —
|
|
so the lab's own spend is a card in the gallery instead of vanishing."""
|
|
slugs = set(summary.get("projectsAuto") or [])
|
|
sid = summary.get("sessionId") or ""
|
|
m = meta_all.get(sid) or {}
|
|
for p in (m.get("projects") or []):
|
|
if p:
|
|
slugs.add(p)
|
|
fallback = fallback_for(summary) if fallback_for else None
|
|
return set(projects_mod.attributed_projects(sorted(slugs), fallback))
|
|
|
|
|
|
def _type_costs(u: dict, model: str, cost: float | None = None) -> dict[str, dict]:
|
|
"""Split one usage block into per-token-type {tokens, cost}.
|
|
|
|
The shares come from ``conversations.usage_type_costs`` — the model's own
|
|
rates from its provider plugin's price book (Claude per version, OpenAI
|
|
with its ``-fast`` / ``-ultrafast`` multiple, Gemini, the OpenRouter
|
|
catalogue),
|
|
cache writes priced off their weighted *units* but counted in raw tokens —
|
|
and are rescaled to ``cost``, what the parser recorded for these tokens
|
|
call by call: Claude's fast mode, Haiku's and OpenAI's long-prompt tiers
|
|
and a pi run's provider-reported cost are in that figure and can't be
|
|
recomputed from a usage sum. A model its provider prices at nothing is
|
|
a local one: its cost is the box's time (``_local_type_costs``).
|
|
"""
|
|
if cost and not any(pricing.rates_for(model)):
|
|
return _local_type_costs(u, cost)
|
|
priced = usage_type_costs(u, model)
|
|
modelled = sum(priced.values())
|
|
k = cost / modelled if cost and modelled > 0 else 1.0
|
|
tokens = {"input": u["input"], "output": u["output"], "cacheRead": u["cacheRead"],
|
|
"cacheWrite": u["cacheWriteTokens"]}
|
|
return {t: {"tokens": tokens[t], "cost": priced[t] * k} for t in TYPES}
|
|
|
|
|
|
def _local_type_costs(u: dict, cost: float) -> dict[str, dict]:
|
|
"""A local (EVOX2) model's cost — the box's time, its tokens being free —
|
|
split per token type by the time each keeps the box busy (the
|
|
``provider-evox2`` pricing's ``outputWeight``, ``pricing.local_output_weight``)."""
|
|
w = {"input": u["input"], "output": u["output"] * pricing.local_output_weight(),
|
|
"cacheRead": 0, "cacheWrite": u["cacheWriteTokens"]}
|
|
total = sum(w.values()) or 1
|
|
tok = {"input": u["input"], "output": u["output"], "cacheRead": u["cacheRead"],
|
|
"cacheWrite": u["cacheWriteTokens"]}
|
|
return {t: {"tokens": tok[t], "cost": cost * w[t] / total} for t in TYPES}
|
|
|
|
|
|
def _aggregate(convs: list[dict]) -> dict:
|
|
"""Roll a project's attributed conversations into a spend summary."""
|
|
costs: list[float] = []
|
|
tokens: list[int] = []
|
|
total_cost = 0.0
|
|
total_tokens = 0
|
|
by_type = {t: {"tokens": 0, "cost": 0.0} for t in TYPES}
|
|
|
|
for s in convs:
|
|
model = s.get("model") or ""
|
|
u = {**zero_usage(), **(s.get("usage") or {})}
|
|
c = s.get("cost")
|
|
if c is None:
|
|
c = usage_cost(u, model)
|
|
tk = s.get("tokens")
|
|
if tk is None:
|
|
tk = usage_tokens(u)
|
|
costs.append(c)
|
|
tokens.append(tk)
|
|
total_cost += c
|
|
total_tokens += tk
|
|
# Split per token type at each model's own rates when the run carries
|
|
# its per-model breakdown (a mixed Opus/Fable run priced as one model
|
|
# would misplace the money); older summaries fall back to the primary.
|
|
parts = [(bm.get("usage") or zero_usage(), m, bm.get("cost") or 0.0)
|
|
for m, bm in (s.get("byModel") or {}).items()] or [(u, model, c)]
|
|
conv_type = {t: 0.0 for t in TYPES}
|
|
for pu, pm, pc in parts:
|
|
for t, v in _type_costs({**zero_usage(), **pu}, pm, pc).items():
|
|
by_type[t]["tokens"] += int(v["tokens"])
|
|
conv_type[t] += v["cost"]
|
|
# …and to the conversation's own total, so the split and the project's
|
|
# cost are one figure (a model entry recorded without its cost).
|
|
modelled = sum(conv_type.values())
|
|
k = c / modelled if c and modelled > 0 else 1.0
|
|
for t in TYPES:
|
|
by_type[t]["cost"] += conv_type[t] * k
|
|
|
|
n = len(convs)
|
|
return {
|
|
"conversations": n,
|
|
"cost": total_cost,
|
|
"tokens": total_tokens,
|
|
"meanCost": total_cost / n if n else 0.0,
|
|
"medianCost": float(median(costs)) if costs else 0.0,
|
|
"meanTokens": total_tokens / n if n else 0.0,
|
|
"medianTokens": float(median(tokens)) if tokens else 0.0,
|
|
"byType": by_type,
|
|
}
|
|
|
|
|
|
def costs_by_project(summaries: list[tuple[str, dict]], meta_all: dict,
|
|
fallback_for=None, attribute_for=None) -> dict[str, dict]:
|
|
"""{project dir-name -> spend aggregate} across all conversations.
|
|
|
|
``summaries`` is ``store.all_summaries()`` (``[(path, summary), …]``);
|
|
``meta_all`` is ``meta_store.all()``. ``fallback_for(summary)`` names the
|
|
project a project-less conversation falls back to instead of the root (see
|
|
``projects.attributed_projects``) — how a work session lands on its repo.
|
|
``attribute_for(summary)``, when given, is the whole rule instead
|
|
(``worker_projects.conversation_projects`` — what the cards show).
|
|
"""
|
|
buckets: dict[str, list[dict]] = {}
|
|
for _path, s in summaries:
|
|
if not s.get("messages"):
|
|
continue
|
|
slugs = (attribute_for(s) if attribute_for
|
|
else _project_slugs(s, meta_all, fallback_for))
|
|
for slug in slugs:
|
|
buckets.setdefault(slug, []).append(s)
|
|
return {slug: _aggregate(convs) for slug, convs in buckets.items()}
|