A local call has no API price and pi records costUSD: 0, so local
conversations showed $0. The parser now prices each local call from its
duration: calibrated wall power per model (111 / 116 / 138 W, Tuya plug →
HA → Prometheus) × time at the dated EDF Tarif Bleu Base tariff (0.2001 €/kWh
since 2026-08-01), plus the box's amortisation (€2049 over 5 years, spread
over its ~613 busy hours a year).
- pricing.local_call + the dated tariff table in the price book (2026-11-01)
- an opencode step takes its content record's duration, not its usage
record's (written after its tools ran)
- summaries carry `local` {seconds, wh, electricity, hardware}; PARSER_VERSION
38 re-prices every stored conversation
- the plan meter's hourly bins leave local calls out
- project rollups split a local cost per token type by the box's time
- scripts/local-energy-calibration.py re-fits the watts and busy hours;
docs/local-energy.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
142 lines
5.8 KiB
Python
Executable File
142 lines
5.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""How much power does the EVOX2 draw while a local model works, and how many
|
|
hours a year is it busy? The two figures behind a local call's cost
|
|
(backend/conversations/pricing.py: ``LOCAL_WATTS``, ``EVOX2_BUSY_HOURS_PER_YEAR``).
|
|
|
|
Two inputs, both already on the box:
|
|
|
|
* **Wall power** — the Tuya plug under the EVOX2, through Home Assistant's
|
|
``sensor.evox2_wall_power`` (0 W while the plug is off), scraped by the lab's
|
|
Prometheus as ``homeassistant_sensor_power_w``. Prometheus keeps 30 days.
|
|
* **Calls** — every local-model API call in the pi and opencode transcripts,
|
|
timed the way the parser times it: from the record that unblocked the call
|
|
to its reply (an opencode step's first record — its usage comes later).
|
|
|
|
Per model: the time-weighted mean wall power over its calls' windows (only
|
|
windows holding at least one sample — the plug reports every ~30 s). Busy
|
|
hours: the share of samples above ``--busy-w`` (idle-awake is ~9 W), per year.
|
|
Print the figures; copy them into the price book by hand.
|
|
|
|
scripts/local-energy-calibration.py
|
|
scripts/local-energy-calibration.py --since 2026-10-15 --json out.json
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import bisect
|
|
import datetime as dt
|
|
import json
|
|
import pathlib
|
|
import statistics
|
|
import time
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
HOME = pathlib.Path.home()
|
|
TRANSCRIPTS = [HOME / ".pi-runner" / "transcripts", HOME / ".opencode-runner" / "transcripts"]
|
|
PI_MODELS = HOME / ".pi" / "agent" / "models.json"
|
|
SERIES = 'homeassistant_sensor_power_w{entity="sensor.evox2_wall_power"}'
|
|
CALL_CAP_S = 3600 # pricing.LOCAL_CALL_CAP_S
|
|
STEP_S = 30
|
|
|
|
|
|
def _ts(s: str) -> float:
|
|
return dt.datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp()
|
|
|
|
|
|
def local_models() -> set[str]:
|
|
"""pi's EVOX2 model ids, bare and as opencode's ``evox2/<id>`` twins."""
|
|
data = json.loads(PI_MODELS.read_text())
|
|
ids = {m["id"] for name, p in (data.get("providers") or {}).items()
|
|
if name.startswith("evox2") for m in p.get("models", [])}
|
|
return ids | {f"evox2/{i}" for i in ids}
|
|
|
|
|
|
def calls(since: float, models: set[str]) -> list[tuple[float, float, str]]:
|
|
"""(start, end, model) of every local call that ended after ``since``."""
|
|
out = []
|
|
for root in TRANSCRIPTS:
|
|
for f in root.rglob("*.jsonl"):
|
|
prev, seen = None, set()
|
|
for line in f.open(errors="replace"):
|
|
try:
|
|
o = json.loads(line)
|
|
except ValueError:
|
|
continue
|
|
t = o.get("timestamp")
|
|
if not t:
|
|
continue
|
|
t = _ts(t)
|
|
msg = o.get("message") or {}
|
|
mid = msg.get("id")
|
|
if (o.get("type") == "assistant" and msg.get("model") in models
|
|
and (not mid or mid not in seen) and prev is not None and t >= since):
|
|
seen.add(mid)
|
|
if 0 < t - prev <= CALL_CAP_S:
|
|
out.append((prev, t, msg["model"].removeprefix("evox2/")))
|
|
prev = t
|
|
return out
|
|
|
|
|
|
def power(prom: str, start: float, end: float) -> list[tuple[float, float]]:
|
|
"""(t, W) samples, fetched in 3-day chunks (Prometheus caps a range at 11k points)."""
|
|
out = []
|
|
for s in range(int(start), int(end), 3 * 86400):
|
|
e = min(int(end), s + 3 * 86400 - STEP_S)
|
|
q = urllib.parse.urlencode({"query": SERIES, "start": s, "end": e, "step": STEP_S})
|
|
with urllib.request.urlopen(f"{prom}/api/v1/query_range?{q}", timeout=30) as r:
|
|
res = json.load(r)["data"]["result"]
|
|
if res:
|
|
out += [(float(t), float(v)) for t, v in res[0]["values"]]
|
|
return out
|
|
|
|
|
|
def main() -> None:
|
|
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
|
ap.add_argument("--since", help="YYYY-MM-DD (default: Prometheus retention, 30 days)")
|
|
ap.add_argument("--prom", default="http://localhost:9090")
|
|
ap.add_argument("--busy-w", type=float, default=30.0,
|
|
help="wall power above which the box counts as busy")
|
|
ap.add_argument("--json", help="also write the figures to this file")
|
|
args = ap.parse_args()
|
|
|
|
end = time.time()
|
|
start = _ts(args.since + "T00:00:00Z") if args.since else end - 30 * 86400
|
|
samples = power(args.prom, start, end)
|
|
if not samples:
|
|
raise SystemExit("no wall-power samples in range")
|
|
start = samples[0][0]
|
|
t = [s[0] for s in samples]
|
|
|
|
per: dict[str, list[tuple[float, float]]] = {}
|
|
covered = 0
|
|
found = calls(start, local_models())
|
|
for a, b, m in found:
|
|
vals = [samples[k][1] for k in range(bisect.bisect_left(t, a), bisect.bisect_right(t, b))]
|
|
if vals:
|
|
covered += 1
|
|
per.setdefault(m, []).append((b - a, statistics.mean(vals)))
|
|
|
|
span_h = (samples[-1][0] - samples[0][0]) / 3600
|
|
busy_h = sum(STEP_S for _, w in samples if w > args.busy_w) / 3600
|
|
awake = [w for _, w in samples if w > 5]
|
|
report = {
|
|
"from": dt.datetime.fromtimestamp(start, dt.timezone.utc).isoformat(),
|
|
"days": round(span_h / 24, 1),
|
|
"calls": len(found), "callsWithSamples": covered,
|
|
"watts": {m: round(sum(d * w for d, w in v) / sum(d for d, _ in v), 1)
|
|
for m, v in sorted(per.items())},
|
|
"callHours": {m: round(sum(d for d, _ in v) / 3600, 2) for m, v in sorted(per.items())},
|
|
"idleAwakeW": round(statistics.median(awake), 1) if awake else None,
|
|
"busyHours": round(busy_h, 1),
|
|
"busyHoursPerYear": round(busy_h / span_h * 8760) if span_h else None,
|
|
"wallKwh": round(sum(STEP_S * w for _, w in samples) / 3.6e6, 2),
|
|
}
|
|
print(json.dumps(report, indent=2))
|
|
if args.json:
|
|
pathlib.Path(args.json).write_text(json.dumps(report, indent=2) + "\n")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|