compactlab 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- compactlab/__init__.py +3 -0
- compactlab/adapters/__init__.py +2 -0
- compactlab/adapters/base.py +212 -0
- compactlab/adapters/cache.py +396 -0
- compactlab/adapters/claude_code.py +226 -0
- compactlab/adapters/codex.py +298 -0
- compactlab/adapters/dsh.py +287 -0
- compactlab/adapters/gemini_cli.py +259 -0
- compactlab/adapters/opencode.py +375 -0
- compactlab/apply/__init__.py +582 -0
- compactlab/cli/__init__.py +5 -0
- compactlab/cli/main.py +2436 -0
- compactlab/data/config_knobs.json +158 -0
- compactlab/data/harness_defaults.json +72 -0
- compactlab/data/harness_formats.json +300 -0
- compactlab/data/pricing.json +51 -0
- compactlab/engine/__init__.py +138 -0
- compactlab/engine/live.py +306 -0
- compactlab/engine/settings.py +175 -0
- compactlab/engine/watch.py +82 -0
- compactlab/eval/__init__.py +1 -0
- compactlab/eval/deep.py +390 -0
- compactlab/eval/executors.py +84 -0
- compactlab/eval/factcheck.py +75 -0
- compactlab/lens.py +80 -0
- compactlab/model/__init__.py +285 -0
- compactlab/pricing/__init__.py +211 -0
- compactlab/pricing/auto.py +118 -0
- compactlab/pricing/ids.py +148 -0
- compactlab/pricing/refresh.py +299 -0
- compactlab/publish.py +125 -0
- compactlab/py.typed +0 -0
- compactlab/recommend/__init__.py +201 -0
- compactlab/recommend/claude_code.py +172 -0
- compactlab/recommend/codex.py +104 -0
- compactlab/recommend/dsh.py +89 -0
- compactlab/recommend/gemini_cli.py +85 -0
- compactlab/recommend/opencode.py +117 -0
- compactlab/recommend/units.py +63 -0
- compactlab/report/__init__.py +3 -0
- compactlab/report/html.py +27 -0
- compactlab/report/template.html +1189 -0
- compactlab/service/__init__.py +1 -0
- compactlab/service/core.py +220 -0
- compactlab/service/http.py +133 -0
- compactlab/service/lock.py +92 -0
- compactlab/service/policy.py +258 -0
- compactlab/service/schedule.py +212 -0
- compactlab/share.py +553 -0
- compactlab/sim/__init__.py +1 -0
- compactlab/sim/baseline.py +214 -0
- compactlab/sim/calibrate.py +108 -0
- compactlab/sim/engine.py +1130 -0
- compactlab/sim/select.py +238 -0
- compactlab/sim/timing.py +134 -0
- compactlab/synth.py +416 -0
- compactlab/term/__init__.py +0 -0
- compactlab/term/style.py +134 -0
- compactlab/term/top.py +531 -0
- compactlab/term/views.py +598 -0
- compactlab/term/widgets.py +238 -0
- compactlab/verify.py +462 -0
- compactlab-0.2.0.dist-info/METADATA +243 -0
- compactlab-0.2.0.dist-info/RECORD +67 -0
- compactlab-0.2.0.dist-info/WHEEL +4 -0
- compactlab-0.2.0.dist-info/entry_points.txt +2 -0
- compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Opt-in refresh of model prices and windows when the logs show a model compactlab has no row for.
|
|
2
|
+
|
|
3
|
+
Off until `compactlab pricing auto on`. Only background runs (`serve`, `recalibrate`, a schedule) use it; `simulate`
|
|
4
|
+
and the rest stay offline and only say which models need it. A refresh downloads the whole public dataset (models.dev,
|
|
5
|
+
then LiteLLM if that fails), so nothing about the user or their models is sent. It runs when a model has no price row
|
|
6
|
+
of its own (at most once a day, or once an hour when a model appears that the last attempt did not cover), and once a
|
|
7
|
+
week anyway, because vendors change prices and context windows of models already in the table. Every change it
|
|
8
|
+
brings is logged (`pricing-changes.json`).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
from collections.abc import Callable, Iterable
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from . import DEFAULT_REFRESHED, PricingTable
|
|
20
|
+
from .refresh import fetch, refresh
|
|
21
|
+
|
|
22
|
+
AUTO_FILE = Path("~/.compactlab/pricing-auto.json")
|
|
23
|
+
RETRY_S = 24 * 3600
|
|
24
|
+
NEW_MODEL_RETRY_S = 3600
|
|
25
|
+
STALE_S = 7 * 86400 # refresh known models' prices and windows this often
|
|
26
|
+
GIVE_UP = 5 # attempts after which a model the public data never lists stops triggering refreshes of its own
|
|
27
|
+
ORDER = ("models.dev", "litellm")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def load_state(path: Path = AUTO_FILE) -> dict[str, Any]:
|
|
31
|
+
p = path.expanduser()
|
|
32
|
+
try:
|
|
33
|
+
d = json.loads(p.read_text()) if p.exists() else {}
|
|
34
|
+
except (OSError, ValueError):
|
|
35
|
+
d = {}
|
|
36
|
+
return d if isinstance(d, dict) else {}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def save_state(state: dict[str, Any], path: Path = AUTO_FILE) -> None:
|
|
40
|
+
p = path.expanduser()
|
|
41
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
tmp = p.with_name(p.name + ".tmp")
|
|
43
|
+
tmp.write_text(json.dumps(state, indent=1, sort_keys=True))
|
|
44
|
+
os.replace(tmp, p)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def set_enabled(on: bool, path: Path = AUTO_FILE) -> dict[str, Any]:
|
|
48
|
+
st = load_state(path)
|
|
49
|
+
st["enabled"] = on
|
|
50
|
+
save_state(st, path)
|
|
51
|
+
return st
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def unpriced(table: PricingTable, models: Iterable[tuple[str, str | None]]) -> list[str]:
|
|
55
|
+
"""Models (as logged) whose price is not their own row: borrowed, the fallback, or a platform priced at the
|
|
56
|
+
vendor's list price."""
|
|
57
|
+
out = set()
|
|
58
|
+
for model, platform in models:
|
|
59
|
+
if model in ("unknown", "<synthetic>", ""):
|
|
60
|
+
continue
|
|
61
|
+
if table.lookup(model, platform).kind != "exact":
|
|
62
|
+
out.add(model if not platform else f"{model} @ {platform}")
|
|
63
|
+
return sorted(out)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def maybe_refresh(
|
|
67
|
+
table: PricingTable,
|
|
68
|
+
models: Iterable[tuple[str, str | None]],
|
|
69
|
+
now: float,
|
|
70
|
+
reload: Callable[[], PricingTable],
|
|
71
|
+
path: Path = AUTO_FILE,
|
|
72
|
+
out: Path = DEFAULT_REFRESHED,
|
|
73
|
+
fetcher: Callable[[str], dict[str, Any]] | None = None,
|
|
74
|
+
) -> tuple[PricingTable, dict[str, Any] | None]:
|
|
75
|
+
"""Refresh when auto refresh is on, some model is unpriced and a retry is due; return the (re)loaded table and
|
|
76
|
+
what happened (None when nothing was attempted)."""
|
|
77
|
+
st = load_state(path)
|
|
78
|
+
if not st.get("enabled"):
|
|
79
|
+
return table, None
|
|
80
|
+
models = list(models)
|
|
81
|
+
missing = unpriced(table, models)
|
|
82
|
+
attempts: dict[str, int] = dict(st.get("attempts") or {})
|
|
83
|
+
wanted = [m for m in missing if attempts.get(m, 0) < GIVE_UP] # e.g. a private profile ARN is never listed
|
|
84
|
+
p = out.expanduser()
|
|
85
|
+
fresh_at = max(float(st.get("last_ok") or 0), p.stat().st_mtime if p.exists() else 0.0)
|
|
86
|
+
stale = now - fresh_at >= STALE_S
|
|
87
|
+
if not wanted and not stale:
|
|
88
|
+
return table, None
|
|
89
|
+
last = st.get("last_attempt")
|
|
90
|
+
new = set(wanted) - set(st.get("missing") or [])
|
|
91
|
+
if last is not None and now - last < RETRY_S and not (new and now - last >= NEW_MODEL_RETRY_S):
|
|
92
|
+
return table, None
|
|
93
|
+
st.update(last_attempt=now, missing=missing)
|
|
94
|
+
errors: list[str] = []
|
|
95
|
+
moved: list[dict[str, Any]] = []
|
|
96
|
+
for source in ORDER:
|
|
97
|
+
try:
|
|
98
|
+
n = refresh(source, out, None, fetcher or fetch, moved)
|
|
99
|
+
except Exception as e: # network or parse failure: keep the previous file, try the next source
|
|
100
|
+
errors.append(f"{source}: {type(e).__name__}: {e}"[:300])
|
|
101
|
+
continue
|
|
102
|
+
st.update(last_ok=now, last_source=source, last_rows=n)
|
|
103
|
+
break
|
|
104
|
+
st["last_error"] = "; ".join(errors) or None
|
|
105
|
+
fresh = reload() if st.get("last_ok") == now else table
|
|
106
|
+
st["still_missing"] = unpriced(fresh, models)
|
|
107
|
+
st["attempts"] = {m: attempts.get(m, 0) + 1 for m in st["still_missing"]}
|
|
108
|
+
save_state(st, path)
|
|
109
|
+
used = {fresh.lookup(m, p).key for m, p in models} # the rows your models are priced from
|
|
110
|
+
return fresh, {
|
|
111
|
+
"reason": "new model" if wanted else "weekly",
|
|
112
|
+
"changes": [c for c in moved if c["model"] in used],
|
|
113
|
+
"refreshed": st.get("last_ok") == now,
|
|
114
|
+
"source": st.get("last_source") if st.get("last_ok") == now else None,
|
|
115
|
+
"missing": missing,
|
|
116
|
+
"still_missing": st["still_missing"],
|
|
117
|
+
"error": st["last_error"],
|
|
118
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Model IDs as harnesses and platforms write them, reduced to the vendor's own ID plus the platform they point at.
|
|
2
|
+
|
|
3
|
+
us.anthropic.claude-fable-5-2-v1:0 -> claude-fable-5-2, Amazon Bedrock, region us
|
|
4
|
+
claude-opus-5-5@20260922 -> claude-opus-5-5, Vertex AI
|
|
5
|
+
anthropic/claude-fable-5.2 -> claude-fable-5-2, OpenRouter
|
|
6
|
+
claude-opus-5-5-20261001 -> claude-opus-5-5 (dated snapshot)
|
|
7
|
+
claude-opus-4-6[1m] -> claude-opus-4-6, 1M-context variant
|
|
8
|
+
|
|
9
|
+
Platform names are models.dev provider IDs, so refreshed rows and lookups use the same keys.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
|
|
17
|
+
# the vendor's own API (models.dev provider ID) by ID prefix; earlier entries win
|
|
18
|
+
FIRST_PARTY: tuple[tuple[str, tuple[str, ...]], ...] = (
|
|
19
|
+
("anthropic", ("claude-",)),
|
|
20
|
+
("openai", ("gpt-", "o1", "o3", "o4", "codex-", "chatgpt-")),
|
|
21
|
+
("deepseek", ("deepseek-",)),
|
|
22
|
+
("moonshotai", ("kimi-", "moonshot-")),
|
|
23
|
+
("zai", ("glm-",)),
|
|
24
|
+
("alibaba", ("qwen", "qwq-", "qvq-")),
|
|
25
|
+
("google", ("gemini-", "gemma-")),
|
|
26
|
+
("xai", ("grok-",)),
|
|
27
|
+
("mistral", ("mistral-", "devstral-", "codestral-", "ministral-", "magistral-")),
|
|
28
|
+
("minimax", ("minimax-",)),
|
|
29
|
+
)
|
|
30
|
+
# platforms that resell other vendors' models at their own prices
|
|
31
|
+
PLATFORMS = ("amazon-bedrock", "google-vertex-anthropic", "google-vertex", "azure", "openrouter")
|
|
32
|
+
# what harness configs call a platform -> models.dev provider ID (Codex `model_provider`, LiteLLM `litellm_provider`)
|
|
33
|
+
PLATFORM_ALIASES = {
|
|
34
|
+
"bedrock": "amazon-bedrock",
|
|
35
|
+
"bedrock_converse": "amazon-bedrock",
|
|
36
|
+
"amazon-bedrock": "amazon-bedrock",
|
|
37
|
+
"vertex": "google-vertex-anthropic",
|
|
38
|
+
"vertex_ai": "google-vertex-anthropic",
|
|
39
|
+
"vertex_ai-anthropic_models": "google-vertex-anthropic",
|
|
40
|
+
"azure": "azure",
|
|
41
|
+
"azure_ai": "azure",
|
|
42
|
+
"openrouter": "openrouter",
|
|
43
|
+
}
|
|
44
|
+
BEDROCK = re.compile(
|
|
45
|
+
r"^(?:(us-gov|global|us|eu|apac|au|jp|ca|in)\.)?"
|
|
46
|
+
r"(anthropic|openai|meta|amazon|mistral|deepseek|qwen|moonshot|moonshotai|minimax|google|zai|cohere|writer)\.(.+)$"
|
|
47
|
+
)
|
|
48
|
+
DATE = re.compile(r"-(?:20\d{6}|20\d{2}-\d{2}-\d{2})$")
|
|
49
|
+
# Bedrock model versions: -v1:0, -v1:0:200k (a context variant), -v1, -1:0
|
|
50
|
+
BEDROCK_VERSION = re.compile(r"-v?\d+:\d+(?::\d+[km])?$|-v\d+$")
|
|
51
|
+
# OpenRouter names models `<vendor>/<model>`; these vendor prefixes mean OpenRouter (or a router using its names)
|
|
52
|
+
ROUTER_VENDORS = {"anthropic", "openai", "google", "deepseek", "x-ai", "mistralai", "moonshotai", "qwen", "z-ai",
|
|
53
|
+
"meta-llama", "minimax"} # fmt: skip
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class ModelId:
|
|
58
|
+
id: str # the vendor's own ID: lower case, no platform prefix, date, version or [1m] suffix
|
|
59
|
+
platform: str | None # the platform the ID's shape points at, or None
|
|
60
|
+
region: str | None # Bedrock cross-region prefix (us, eu, global, ...)
|
|
61
|
+
one_m: bool # the [1m] (1M-context) variant
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def first_party(mid: str) -> str | None:
|
|
65
|
+
"""The vendor's own platform for a vendor ID, or None when the ID matches no known vendor."""
|
|
66
|
+
return next((p for p, prefixes in FIRST_PARTY if mid.startswith(prefixes)), None)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def platform_name(name: str | None) -> str | None:
|
|
70
|
+
"""A harness's or dataset's platform name as a models.dev provider ID (None for first-party or unknown)."""
|
|
71
|
+
if not name:
|
|
72
|
+
return None
|
|
73
|
+
n = name.strip().lower()
|
|
74
|
+
return PLATFORM_ALIASES.get(n, n if n in PLATFORMS else None)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def parse(raw: str) -> ModelId:
|
|
78
|
+
s = (raw or "").strip().lower()
|
|
79
|
+
one_m = s.endswith("[1m]")
|
|
80
|
+
s = s.removesuffix("[1m]")
|
|
81
|
+
platform: str | None = None
|
|
82
|
+
region: str | None = None
|
|
83
|
+
if "/" in s: # OpenRouter `anthropic/claude-...`, LiteLLM `bedrock/...`, ARNs, Vertex resource paths
|
|
84
|
+
head = s.split("/", 1)[0]
|
|
85
|
+
if s.startswith("arn:aws:bedrock"):
|
|
86
|
+
platform = "amazon-bedrock"
|
|
87
|
+
elif head in ("publishers", "projects", "vertex_ai"):
|
|
88
|
+
platform = "vertex"
|
|
89
|
+
elif head in ROUTER_VENDORS or head == "openrouter":
|
|
90
|
+
platform = "openrouter"
|
|
91
|
+
else: # azure/..., bedrock/...; anything else (ollama/..., a proxy alias) names no platform we price
|
|
92
|
+
platform = PLATFORM_ALIASES.get(head)
|
|
93
|
+
s = s.rsplit("/", 1)[-1]
|
|
94
|
+
m = BEDROCK.match(s)
|
|
95
|
+
if m:
|
|
96
|
+
platform, region, s = "amazon-bedrock", m.group(1), m.group(3)
|
|
97
|
+
if platform == "amazon-bedrock" or re.search(r"-v?\d+:\d+", s):
|
|
98
|
+
s = BEDROCK_VERSION.sub("", s)
|
|
99
|
+
if "@" in s: # Vertex: claude-opus-5-5@20260922 or @default
|
|
100
|
+
s = s.split("@", 1)[0]
|
|
101
|
+
platform = platform or "vertex"
|
|
102
|
+
s = s.split(":", 1)[0] # OpenRouter variants (:batch, :free, :thinking)
|
|
103
|
+
s = DATE.sub("", s).removesuffix("-latest")
|
|
104
|
+
if s.startswith("claude-"): # Anthropic writes versions with hyphens; OpenRouter and others with dots
|
|
105
|
+
s = re.sub(r"(?<=\d)\.(?=\d)", "-", s)
|
|
106
|
+
if platform == "vertex": # Anthropic's models on Vertex are their own models.dev provider
|
|
107
|
+
platform = "google-vertex-anthropic" if s.startswith("claude-") else "google-vertex"
|
|
108
|
+
return ModelId(s, platform, region, one_m)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def claude_settings_key(model: str) -> str:
|
|
112
|
+
"""Claude Code's modelSettings key for a logged model ID: the canonical Claude name, which also matches its alias,
|
|
113
|
+
date-suffixed, [1m] and Bedrock / Vertex IDs; any other ID as logged."""
|
|
114
|
+
m = parse(model)
|
|
115
|
+
if not m.id.startswith("claude-"):
|
|
116
|
+
return model
|
|
117
|
+
return m.id + "[1m]" if m.one_m else m.id # the 1M variant has a setting of its own
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def platform_key(platform: str, mid: ModelId) -> str:
|
|
121
|
+
"""Key of a platform's own price row: `amazon-bedrock:us.claude-fable-5-2`, `openrouter:claude-fable-5-2`."""
|
|
122
|
+
return f"{platform}:{mid.region}.{mid.id}" if mid.region else f"{platform}:{mid.id}"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def family(mid: str) -> tuple[str, tuple[int, ...]]:
|
|
126
|
+
"""(family, version): `claude-fable-5-2` -> (`claude-fable`, (5, 2)); `gpt-6.1-sol` -> (`gpt-sol`, (6, 1))."""
|
|
127
|
+
version = tuple(int(x) for x in re.findall(r"\d+", mid))
|
|
128
|
+
return re.sub(r"[-._]+", "-", re.sub(r"\d+", "", mid)).strip("-"), version
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def nearest(target: tuple[int, ...], versions: list[tuple[int, ...]]) -> tuple[int, ...] | None:
|
|
132
|
+
"""The closest known version: the longest shared leading part, then the newest not newer than `target`, else the
|
|
133
|
+
oldest newer one. `fable-5-3` borrows from 5-2, `haiku-5` from 5-5, `opus-4-1` from 4-5."""
|
|
134
|
+
|
|
135
|
+
def shared(v: tuple[int, ...]) -> int:
|
|
136
|
+
n = 0
|
|
137
|
+
for a, b in zip(v, target, strict=False):
|
|
138
|
+
if a != b:
|
|
139
|
+
break
|
|
140
|
+
n += 1
|
|
141
|
+
return n
|
|
142
|
+
|
|
143
|
+
if not versions:
|
|
144
|
+
return None
|
|
145
|
+
best = max(shared(v) for v in versions)
|
|
146
|
+
pool = [v for v in versions if shared(v) == best]
|
|
147
|
+
older = [v for v in pool if v <= target]
|
|
148
|
+
return max(older) if older else min(pool)
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
"""Refresh prices from a public dataset. This is the only module that performs network I/O on its own: when the user
|
|
2
|
+
runs `compactlab pricing refresh`, or from background runs once they turn on `compactlab pricing auto` (see
|
|
3
|
+
`pricing.auto`). Everything else works from the bundled file and the last refresh.
|
|
4
|
+
|
|
5
|
+
Supported sources:
|
|
6
|
+
models.dev https://models.dev/api.json {provider: {models: {id: {cost: {input, output, cache_read,
|
|
7
|
+
cache_write, tiers?|context_over_200k?}, limit: {context}}}}} (USD per 1M tokens)
|
|
8
|
+
litellm model_prices_and_context_window.json {id: {input_cost_per_token, output_cost_per_token,
|
|
9
|
+
cache_read_input_token_cost, cache_creation_input_token_cost, max_input_tokens, litellm_provider}}
|
|
10
|
+
(per token)
|
|
11
|
+
|
|
12
|
+
Rows are kept for every model of a known vendor (see `ids.FIRST_PARTY`) under the vendor's own ID, the vendor's own
|
|
13
|
+
price winning over resellers', and for the platforms in `ids.PLATFORMS` (Bedrock, Vertex, Azure, OpenRouter) under
|
|
14
|
+
`<platform>:<id>` with that platform's price. The download is the whole public file: nothing about the user is sent.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
import os
|
|
22
|
+
import urllib.request
|
|
23
|
+
from collections.abc import Callable
|
|
24
|
+
from datetime import date
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from .ids import FIRST_PARTY, PLATFORMS, family, first_party, parse, platform_key, platform_name
|
|
29
|
+
|
|
30
|
+
SOURCES = {
|
|
31
|
+
"models.dev": "https://models.dev/api.json",
|
|
32
|
+
"litellm": "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json",
|
|
33
|
+
}
|
|
34
|
+
VENDORS = [p for p, _ in FIRST_PARTY]
|
|
35
|
+
# LiteLLM's names for the vendors' own APIs (rows without a provider count as the vendor's too)
|
|
36
|
+
LITELLM_VENDORS = {"anthropic", "openai", "text-completion-openai", "deepseek", "moonshot", "zai", "dashscope",
|
|
37
|
+
"gemini", "xai", "mistral", "minimax", ""} # fmt: skip
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _sane(row: dict[str, Any]) -> bool:
|
|
41
|
+
"""Every rate finite and non-negative, every window a positive integer."""
|
|
42
|
+
rates = [v for k, v in row.items() if k not in ("max_window", "long_context", "source")]
|
|
43
|
+
lc = row.get("long_context") or {}
|
|
44
|
+
rates += [v for k, v in lc.items() if k != "above_tokens"]
|
|
45
|
+
windows = [w for w in (row.get("max_window"), lc.get("above_tokens")) if w is not None]
|
|
46
|
+
return all(isinstance(v, float) and math.isfinite(v) and v >= 0 for v in rates) and all(
|
|
47
|
+
isinstance(w, int) and w > 0 for w in windows
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _row(cost: dict[str, Any], context: Any) -> dict[str, Any] | None:
|
|
52
|
+
if "input" not in cost or "output" not in cost:
|
|
53
|
+
return None
|
|
54
|
+
row: dict[str, Any] = {
|
|
55
|
+
"input": float(cost["input"]),
|
|
56
|
+
"output": float(cost["output"]),
|
|
57
|
+
"cache_write": float(cost.get("cache_write", cost["input"])),
|
|
58
|
+
"cache_read": float(cost.get("cache_read", cost["input"])),
|
|
59
|
+
}
|
|
60
|
+
if context:
|
|
61
|
+
row["max_window"] = int(context)
|
|
62
|
+
tiers = cost.get("tiers") or []
|
|
63
|
+
if tiers and isinstance(tiers[0], dict) and (tiers[0].get("tier") or {}).get("type") == "context":
|
|
64
|
+
t = tiers[0]
|
|
65
|
+
row["long_context"] = {
|
|
66
|
+
"above_tokens": int(t["tier"]["size"]),
|
|
67
|
+
"input": float(t.get("input", row["input"])),
|
|
68
|
+
"output": float(t.get("output", row["output"])),
|
|
69
|
+
"cache_write": float(t.get("cache_write", row["cache_write"])),
|
|
70
|
+
"cache_read": float(t.get("cache_read", row["cache_read"])),
|
|
71
|
+
}
|
|
72
|
+
elif isinstance(cost.get("context_over_200k"), dict):
|
|
73
|
+
t = cost["context_over_200k"]
|
|
74
|
+
row["long_context"] = {
|
|
75
|
+
"above_tokens": 200_000,
|
|
76
|
+
**{k: float(t.get(k, row[k])) for k in ("input", "output", "cache_write", "cache_read")},
|
|
77
|
+
}
|
|
78
|
+
return row
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _key(mid: str, provider: str | None) -> str | None:
|
|
82
|
+
"""Where a dataset row is stored: the vendor's ID for vendor models, `<platform>:<id>` for a platform's own price,
|
|
83
|
+
None for anything else (unknown vendors, platform variants such as OpenRouter's :batch)."""
|
|
84
|
+
m = parse(mid)
|
|
85
|
+
plat = platform_name(provider) or (provider if provider in PLATFORMS else None)
|
|
86
|
+
if plat:
|
|
87
|
+
if plat == "openrouter" and ":" in mid:
|
|
88
|
+
return None
|
|
89
|
+
return platform_key(plat, m) if first_party(m.id) or plat == "amazon-bedrock" else None
|
|
90
|
+
return m.id if first_party(m.id) and m.platform is None else None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _order(provider: str | None) -> int:
|
|
94
|
+
"""Vendors first (their own price wins for their IDs), then everyone else."""
|
|
95
|
+
return VENDORS.index(provider) if provider in VENDORS else len(VENDORS)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def parse_models_dev(data: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
|
99
|
+
out: dict[str, dict[str, Any]] = {}
|
|
100
|
+
providers: list[tuple[str | None, dict[str, Any]]] = (
|
|
101
|
+
sorted(((pid, v) for pid, v in data.items()), key=lambda x: _order(x[0]))
|
|
102
|
+
if all(isinstance(v, dict) and "models" in v for v in data.values())
|
|
103
|
+
else [(None, {"models": data})]
|
|
104
|
+
)
|
|
105
|
+
vendor_models: set[tuple[str, tuple[int, ...]]] = set() # (family, version) of every model a vendor lists
|
|
106
|
+
for pid, prov in providers:
|
|
107
|
+
plat = pid if pid in PLATFORMS else None
|
|
108
|
+
for mid, m in (prov.get("models") or {}).items():
|
|
109
|
+
if not isinstance(m, dict):
|
|
110
|
+
continue
|
|
111
|
+
key = _key(mid, plat)
|
|
112
|
+
if key is None or key in out:
|
|
113
|
+
continue
|
|
114
|
+
if plat is None and first_party(key) != pid and family(key) in vendor_models:
|
|
115
|
+
continue # a reseller's copy of a model its vendor lists (often re-spelled and marked up)
|
|
116
|
+
try:
|
|
117
|
+
row = _row(m.get("cost") or {}, (m.get("limit") or {}).get("context"))
|
|
118
|
+
except (TypeError, ValueError, KeyError, OverflowError):
|
|
119
|
+
continue
|
|
120
|
+
if row and _sane(row):
|
|
121
|
+
if pid:
|
|
122
|
+
row["provider"] = pid
|
|
123
|
+
if plat is None and first_party(key) == pid:
|
|
124
|
+
vendor_models.add(family(key))
|
|
125
|
+
out[key] = row
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _m(x: float) -> float:
|
|
130
|
+
return round(x * 1e6, 6)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _litellm_row(m: dict[str, Any]) -> dict[str, Any] | None:
|
|
134
|
+
cost = {"input": _m(m["input_cost_per_token"]), "output": _m(m["output_cost_per_token"])}
|
|
135
|
+
if m.get("cache_read_input_token_cost") is not None:
|
|
136
|
+
cost["cache_read"] = _m(m["cache_read_input_token_cost"])
|
|
137
|
+
if m.get("cache_creation_input_token_cost") is not None:
|
|
138
|
+
cost["cache_write"] = _m(m["cache_creation_input_token_cost"])
|
|
139
|
+
row = _row(cost, m.get("max_input_tokens"))
|
|
140
|
+
if row and m.get("input_cost_per_token_above_200k_tokens") is not None:
|
|
141
|
+
row["long_context"] = {
|
|
142
|
+
"above_tokens": 200_000,
|
|
143
|
+
"input": _m(m["input_cost_per_token_above_200k_tokens"]),
|
|
144
|
+
"output": float((m.get("output_cost_per_token_above_200k_tokens") or m["output_cost_per_token"]) * 1e6),
|
|
145
|
+
"cache_write": float(
|
|
146
|
+
(
|
|
147
|
+
m.get("cache_creation_input_token_cost_above_200k_tokens")
|
|
148
|
+
or m.get("cache_creation_input_token_cost")
|
|
149
|
+
or m["input_cost_per_token"]
|
|
150
|
+
)
|
|
151
|
+
* 1e6
|
|
152
|
+
),
|
|
153
|
+
"cache_read": float(
|
|
154
|
+
(
|
|
155
|
+
m.get("cache_read_input_token_cost_above_200k_tokens")
|
|
156
|
+
or m.get("cache_read_input_token_cost")
|
|
157
|
+
or m["input_cost_per_token"]
|
|
158
|
+
)
|
|
159
|
+
* 1e6
|
|
160
|
+
),
|
|
161
|
+
}
|
|
162
|
+
return row
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def parse_litellm(data: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
|
166
|
+
out: dict[str, dict[str, Any]] = {}
|
|
167
|
+
# bare vendor IDs first, then by depth: `azure/gpt-x` wins over a data-zone copy such as `azure/eu/gpt-x`
|
|
168
|
+
items = sorted(data.items(), key=lambda kv: kv[0].count("/"))
|
|
169
|
+
for mid, m in items:
|
|
170
|
+
if not isinstance(m, dict):
|
|
171
|
+
continue
|
|
172
|
+
if m.get("input_cost_per_token") is None or m.get("output_cost_per_token") is None:
|
|
173
|
+
continue
|
|
174
|
+
prov = str(m.get("litellm_provider") or "")
|
|
175
|
+
plat = (
|
|
176
|
+
"google-vertex-anthropic"
|
|
177
|
+
if prov == "vertex_ai-anthropic_models"
|
|
178
|
+
else "google-vertex"
|
|
179
|
+
if prov.startswith("vertex_ai")
|
|
180
|
+
else platform_name(prov)
|
|
181
|
+
)
|
|
182
|
+
if plat is None:
|
|
183
|
+
if prov not in LITELLM_VENDORS:
|
|
184
|
+
continue # another router's or reseller's copy: not the vendor's list price
|
|
185
|
+
mid = mid.rsplit("/", 1)[-1] # the vendor's own API under LiteLLM's prefix: deepseek/deepseek-v4-pro
|
|
186
|
+
key = _key(mid, plat)
|
|
187
|
+
if key is None or key in out:
|
|
188
|
+
continue
|
|
189
|
+
try:
|
|
190
|
+
row = _litellm_row(m)
|
|
191
|
+
except (TypeError, ValueError, KeyError, OverflowError):
|
|
192
|
+
continue
|
|
193
|
+
if row and _sane(row):
|
|
194
|
+
out[key] = row
|
|
195
|
+
return out
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
PARSERS: dict[str, Callable[[dict[str, Any]], dict[str, dict[str, Any]]]] = {
|
|
199
|
+
"models.dev": parse_models_dev,
|
|
200
|
+
"litellm": parse_litellm,
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def fetch(url: str, timeout: float = 20.0) -> dict[str, Any]:
|
|
205
|
+
if not url.startswith("https://"):
|
|
206
|
+
raise ValueError("pricing refresh only fetches https URLs")
|
|
207
|
+
req = urllib.request.Request(url, headers={"User-Agent": "compactlab-pricing-refresh"})
|
|
208
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
209
|
+
data: dict[str, Any] = json.loads(r.read())
|
|
210
|
+
return data
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
CHANGE_FIELDS = ("input", "output", "cache_write", "cache_read", "max_window")
|
|
214
|
+
MAX_CHANGES = 500
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def changes_path(out: Path) -> Path:
|
|
218
|
+
return out.expanduser().with_name("pricing-changes.json")
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _previous_rows(out: Path) -> dict[str, dict[str, Any]]:
|
|
222
|
+
"""The rows a refresh replaces: the last refreshed file, else the bundled snapshot."""
|
|
223
|
+
try:
|
|
224
|
+
if out.exists():
|
|
225
|
+
return dict(json.loads(out.read_text()).get("models") or {})
|
|
226
|
+
except (OSError, ValueError):
|
|
227
|
+
pass
|
|
228
|
+
from . import PricingTable
|
|
229
|
+
|
|
230
|
+
return dict(PricingTable.bundled()["models"])
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def log_changes(out: Path, rows: dict[str, dict[str, Any]]) -> list[dict[str, Any]]:
|
|
234
|
+
"""Append every price or window that differs from the previous rows to `pricing-changes.json` (newest last, at
|
|
235
|
+
most MAX_CHANGES kept), and return the new entries. A row absent before is not a change."""
|
|
236
|
+
prev = _previous_rows(out)
|
|
237
|
+
today = date.today().isoformat()
|
|
238
|
+
new = []
|
|
239
|
+
for k, row in sorted(rows.items()):
|
|
240
|
+
old = prev.get(k)
|
|
241
|
+
if not old:
|
|
242
|
+
continue
|
|
243
|
+
for f in CHANGE_FIELDS:
|
|
244
|
+
a, b = old.get(f), row.get(f)
|
|
245
|
+
if a is not None and b is not None and float(a) != float(b):
|
|
246
|
+
new.append({"date": today, "model": k, "field": f, "old": a, "new": b, "source": row.get("source")})
|
|
247
|
+
if new:
|
|
248
|
+
path = changes_path(out)
|
|
249
|
+
try:
|
|
250
|
+
log = json.loads(path.read_text()) if path.exists() else []
|
|
251
|
+
except (OSError, ValueError):
|
|
252
|
+
log = []
|
|
253
|
+
log = [*(log if isinstance(log, list) else []), *new][-MAX_CHANGES:]
|
|
254
|
+
tmp = path.with_name(path.name + ".tmp")
|
|
255
|
+
tmp.write_text(json.dumps(log, indent=1))
|
|
256
|
+
os.replace(tmp, path)
|
|
257
|
+
return new
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def recent_changes(out: Path, models: set[str] | None = None, limit: int = 20) -> list[dict[str, Any]]:
|
|
261
|
+
try:
|
|
262
|
+
log = json.loads(changes_path(out).read_text())
|
|
263
|
+
except (OSError, ValueError):
|
|
264
|
+
return []
|
|
265
|
+
log = [c for c in log if isinstance(c, dict) and (models is None or c.get("model") in models)]
|
|
266
|
+
return log[-limit:]
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def refresh(
|
|
270
|
+
source: str,
|
|
271
|
+
out: Path,
|
|
272
|
+
url: str | None = None,
|
|
273
|
+
fetcher: Callable[[str], dict[str, Any]] = fetch,
|
|
274
|
+
changes: list[dict[str, Any]] | None = None,
|
|
275
|
+
) -> int:
|
|
276
|
+
"""Fetch, parse and store `source` as the refreshed layer; prices and windows that moved are logged (and appended
|
|
277
|
+
to `changes` when given). Returns the number of rows stored."""
|
|
278
|
+
url = url or SOURCES[source]
|
|
279
|
+
rows = PARSERS[source](fetcher(url))
|
|
280
|
+
if not rows:
|
|
281
|
+
raise ValueError(f"no usable rows from {url}; keeping the existing pricing")
|
|
282
|
+
for r in rows.values():
|
|
283
|
+
via = r.pop("provider", None)
|
|
284
|
+
r["source"] = f"{source}{f' ({via})' if via else ''} {date.today().isoformat()}"
|
|
285
|
+
out = out.expanduser()
|
|
286
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
287
|
+
moved = log_changes(out, rows)
|
|
288
|
+
if changes is not None:
|
|
289
|
+
changes.extend(moved)
|
|
290
|
+
body = json.dumps(
|
|
291
|
+
{"version": 2, "retrieved": date.today().isoformat(), "source_url": url, "models": rows},
|
|
292
|
+
indent=1,
|
|
293
|
+
sort_keys=True,
|
|
294
|
+
allow_nan=False,
|
|
295
|
+
)
|
|
296
|
+
tmp = out.with_name(out.name + ".tmp")
|
|
297
|
+
tmp.write_text(body)
|
|
298
|
+
os.replace(tmp, out) # the previous file stays intact until the new one is complete
|
|
299
|
+
return len(rows)
|