Files
ai-agent/scripts/ab/pricing-dump.py

217 lines
11 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Dump the price book as text: every model × speed × usage shape.
For every model id seen in the transcript corpus, every catalogue model
(``models.list_models()`` with the network off) and a fixed list of edge-case
ids, × every speed (none, standard, fast, plus any seen in the corpus), × a
fixed set of usage shapes: ``rates_for``, ``usage_cost``, ``usage_cache_cost``,
``plan_units``; and per model ``local_call`` over a few durations and dates,
``models.is_local`` and ``models.context_window``. Floats are printed with
``repr`` — any change in a figure is a changed line.
scripts/ab/pricing-dump.py # print the working tree's dump
scripts/ab/pricing-dump.py --base HEAD # diff base ref vs working tree
Exit codes: 0 = identical (or plain dump), 1 = a difference, 2 = setup error.
"""
import argparse
import json
import pathlib
import re
import sys
HERE = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import _common as ab # noqa: E402
# Ids that exercise each rung of the rate ladder whether or not the corpus
# still holds a run on them (hand-kept; add, never remove).
EXTRA_MODELS = [
# Claude: book keys, dated ids, Bedrock spellings, unknown releases
"claude-fable-5-1", "claude-mythos-5-1", "claude-fable-5", "claude-mythos-5",
"claude-opus-5-5", "claude-opus-5", "claude-opus-4-8", "claude-opus-4-7",
"claude-opus-4-6", "claude-opus-4-5", "claude-opus-4-1", "claude-opus-4",
"claude-sonnet-5-5", "claude-sonnet-5", "claude-sonnet-4-6", "claude-sonnet-4-5",
"claude-sonnet-4", "claude-haiku-5-5", "claude-haiku-4-5",
"claude-haiku-4-5-20251001", "claude-opus-4-8-20260101", "claude-fable-5-2",
"claude-opus-9", "claude-sonnet-9-9", "claude-haiku-9", "claude-mythos-9",
"us.anthropic.claude-opus-4-8", "anthropic.claude-sonnet-5", "CLAUDE-OPUS-4-8",
"opus", "sonnet", "haiku", "fable", "claude-opus-4-8[1m]", "claude-unknown-1",
# OpenAI (opencode): book keys, tiers, line fallbacks, unknown
"gpt-6.1-sol", "gpt-6.1-sol-fast", "gpt-6.1-sol-ultrafast", "gpt-6-astra",
"gpt-6-astra-fast", "gpt-6-astra-ultrafast", "gpt-6-sol", "gpt-6-sol-fast",
"gpt-6-luna", "gpt-6-luna-fast", "gpt-5.6", "gpt-5.6-sol", "gpt-5.6-sol-fast",
"gpt-5.6-terra", "gpt-5.6-terra-fast", "gpt-5.6-luna", "gpt-5.6-luna-fast",
"gpt-5.5", "gpt-5.5-fast", "gpt-5.5-ultrafast", "gpt-5.4", "gpt-5.4-mini",
"gpt-5.3-codex", "gpt-5.3-codex-spark", "gpt-5.2-codex", "gpt-5.2",
"gpt-5.1-codex-max", "gpt-5.1-codex", "gpt-5.1-codex-mini", "gpt-5.1",
"gpt-5-codex", "gpt-5", "gpt-5-mini", "gpt-7-sol", "gpt-7-astra-fast",
"gpt-7-terra", "gpt-7-luna", "gpt-7-codex", "gpt-7-spark", "gpt-9",
"openai/gpt-5.5", "GPT-5.5",
# Gemini (agy): book keys, effort-suffixed ids, unknown
"gemini-4-carbon", "gemini-4-argon", "gemini-4-neon", "gemini-4-hydrogen",
"gemini-3.8-flash", "gemini-4-neon-high", "gemini-4-neon-xhigh",
"gemini-4-hydrogen-low", "gemini-4-argon-medium", "gemini-3.8-flash-high",
"gemini-4-neon-preview", "gemini-9-ultra", "gemini-9-ultra-max",
"google/gemini-4-neon",
# Local (EVOX2) ids, their opencode twins, retired local ids
"inkling-2-mini", "qwen3.6-35b-a3b", "ggml-org/qwen3.8-27b",
"qwen3.8-flash-next-coder", "evox2/inkling-2-mini", "evox2/qwen3.6-35b-a3b",
"evox2/ggml-org/qwen3.8-27b", "evox2-inkling/inkling-2-mini",
"evox2-low/inkling-2-mini", "evox2-high/ggml-org/qwen3.8-27b",
"qwen3-coder-30b", "qwen-old-local",
# OpenRouter (pi): catalogue ids, unknown vendor-prefixed ids
"qwen/qwen3-coder", "qwen/qwen3.6-plus", "anthropic/claude-opus-4.8",
"anthropic/claude-sonnet-5", "openai/gpt-6-sol", "deepseek/deepseek-chat",
"moonshotai/kimi-k2", "x-ai/grok-code-fast-1", "nobody/unknown-model",
"qwen/unknown-qwen",
# not a model at all
"", "<synthetic>", "unknown", "llama-3", "mistral-large",
]
# Raw API usage blocks, as the transcripts carry them (norm_usage's input).
SHAPES: list[tuple[str, dict]] = [
("zero", {}),
("small", {"input_tokens": 1200, "output_tokens": 350}),
("small-cache-flat", {"input_tokens": 12, "output_tokens": 800,
"cache_read_input_tokens": 40_000,
"cache_creation_input_tokens": 3_000}),
("cache-heavy-5m", {"input_tokens": 3, "output_tokens": 1_500,
"cache_read_input_tokens": 95_000,
"cache_creation_input_tokens": 4_000,
"cache_creation": {"ephemeral_5m_input_tokens": 4_000,
"ephemeral_1h_input_tokens": 0}}),
("cache-heavy-1h", {"input_tokens": 3, "output_tokens": 1_500,
"cache_read_input_tokens": 60_000,
"cache_creation_input_tokens": 30_000,
"cache_creation": {"ephemeral_5m_input_tokens": 0,
"ephemeral_1h_input_tokens": 30_000}}),
("cache-mixed", {"input_tokens": 50, "output_tokens": 2_000,
"cache_read_input_tokens": 20_000,
"cache_creation": {"ephemeral_5m_input_tokens": 1_000,
"ephemeral_1h_input_tokens": 9_000}}),
("prompt-100k-exact", {"input_tokens": 100_000, "output_tokens": 10}),
("prompt-over-100k", {"input_tokens": 1_000, "output_tokens": 900,
"cache_read_input_tokens": 99_500,
"cache_creation_input_tokens": 500}),
("prompt-over-200k", {"input_tokens": 5_000, "output_tokens": 4_000,
"cache_read_input_tokens": 190_000,
"cache_creation_input_tokens": 6_000}),
("prompt-272k-exact", {"input_tokens": 272_000, "output_tokens": 10}),
("prompt-over-272k", {"input_tokens": 2_000, "output_tokens": 8_000,
"cache_read_input_tokens": 280_000,
"cache_creation_input_tokens": 10_000}),
("prompt-900k", {"input_tokens": 100_000, "output_tokens": 30_000,
"cache_read_input_tokens": 800_000}),
# a reasoning-heavy step: the mirrors fold reasoning into output_tokens and
# keep the detail beside it, which pricing must ignore
("reasoning", {"input_tokens": 4_000, "output_tokens": 26_000,
"cache_read_input_tokens": 12_000,
"output_tokens_details": {"reasoning_tokens": 24_000},
"reasoning_tokens": 24_000}),
("output-only", {"output_tokens": 64_000}),
("nulls", {"input_tokens": None, "output_tokens": None,
"cache_read_input_tokens": None, "cache_creation_input_tokens": None,
"cache_creation": None}),
]
SPEEDS = [None, "standard", "fast"]
LOCAL_MS = [None, 0, -5, 1_500, 60_000, 3_600_000, 9_000_000]
LOCAL_TS = [None, "2026-01-15T10:00:00.000Z", "2026-02-01T00:00:00Z",
"2026-07-31T23:59:59Z", "2026-09-01T12:00:00Z"]
_MODEL_RE = re.compile(rb'"model":\s?"([^"\\]{1,120})"')
_SPEED_RE = re.compile(rb'"speed":\s?"([^"\\]{1,40})"')
def scan_corpus(files: list[dict]) -> dict:
"""Every model id and usage speed the corpus names (a byte regex — the
superset is harmless: more ids only means more lines on both sides)."""
models, speeds = set(), set()
for f in files:
try:
data = pathlib.Path(f["path"]).read_bytes()
except OSError:
continue
models.update(m.decode("utf-8", "replace") for m in _MODEL_RE.findall(data))
speeds.update(s.decode("utf-8", "replace") for s in _SPEED_RE.findall(data))
return {"models": sorted(models), "speeds": sorted(speeds)}
def dump(tree: pathlib.Path, seen: dict) -> None:
sys.path.insert(0, str(tree / "backend"))
import conversations as c # noqa: E402 (this tree's price book)
import models # noqa: E402
catalogue = [m["id"] for m in models.list_models()]
ids = sorted(set(seen.get("models", [])) | set(catalogue) | set(EXTRA_MODELS))
speeds = SPEEDS + [s for s in seen.get("speeds", []) if s not in SPEEDS]
out = sys.stdout
out.write(f"# models: {len(ids)} ({len(seen.get('models', []))} from the corpus, "
f"{len(catalogue)} from the catalogue, {len(EXTRA_MODELS)} fixed)\n")
out.write(f"# speeds: {speeds!r}\n# shapes: {[n for n, _ in SHAPES]!r}\n")
for name, raw in SHAPES:
out.write(f"norm_usage {name}: {json.dumps(c.norm_usage(raw), sort_keys=True)}\n")
def call(fn, *a):
try:
return repr(fn(*a))
except Exception as e: # noqa: BLE001 — a crash is part of the behaviour
return f"!{type(e).__name__}: {e}"
for mid in ids:
tag = repr(mid) # on every line, so a text diff lines up model by model
out.write(f"\n{tag} rates_for={call(c.rates_for, mid)} "
f"is_local={call(models.is_local, mid)} "
f"context_window={call(models.context_window, mid)}\n")
for name, raw in SHAPES:
nu = c.norm_usage(raw)
for sp in speeds:
out.write(f"{tag} {name:<18} speed={str(sp):<9} "
f"cost={call(c.usage_cost, nu, mid, sp)} "
f"cache={call(c.usage_cache_cost, nu, mid, sp)} "
f"plan={call(c.plan_units, nu, mid, sp)}\n")
for ms in LOCAL_MS:
for ts in LOCAL_TS:
try:
lc = json.dumps(c.local_call(mid, ms, ts), sort_keys=True)
except Exception as e: # noqa: BLE001
lc = f"!{type(e).__name__}: {e}"
out.write(f"{tag} local_call ms={ms} ts={ts}: {lc}\n")
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--base", metavar="REF", help="diff this git ref against the working tree")
ap.add_argument("--no-corpus", action="store_true",
help="catalogue + fixed ids only (no transcript scan)")
ab.add_corpus_args(ap)
ap.add_argument("--keep", action="store_true", help="keep the scratch dir")
ap.add_argument("--tree", type=pathlib.Path, help=argparse.SUPPRESS)
ap.add_argument("--seen", type=pathlib.Path, help=argparse.SUPPRESS)
args = ap.parse_args()
if args.tree: # internal: one tree's dump
dump(args.tree, json.loads(args.seen.read_text()) if args.seen else {})
return 0
with ab.workdir(args.keep) as work:
seen = {"models": [], "speeds": []}
if not args.no_corpus:
files = ab.corpus_from_args(args)
seen = scan_corpus(files)
print(f"corpus: {len(files)} file(s) → {len(seen['models'])} model id(s), "
f"speeds {seen['speeds']}", file=sys.stderr)
seen_file = work / "seen.json"
seen_file.write_text(json.dumps(seen))
extra = ["--seen", str(seen_file)]
if args.base:
return ab.dump_ab(pathlib.Path(__file__).resolve(), args.base, extra, keep=args.keep)
ab.run_pool([([sys.executable, __file__, "--tree", str(ab.REPO), *extra],
ab.frozen_env(work), None)], 1)
return 0
if __name__ == "__main__":
sys.exit(main())