File size: 12,997 Bytes
7dc4009 f140a09 7dc4009 f140a09 7dc4009 f140a09 7dc4009 f140a09 7dc4009 6b6587e 7dc4009 55c4739 7dc4009 55c4739 7dc4009 55c4739 7dc4009 55c4739 7dc4009 55c4739 7dc4009 f140a09 6b6587e f140a09 7dc4009 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | """Build the uplinkswitch/llm-api-pricing dataset files from the public catalogs.
Usage: python build.py <out_dir>
Reads https://api.uplinkswitch.com/v1/catalog and /v1/catalog/media (no key needed),
writes data/*.csv and raw/*.json, and appends today's prices to data/chat_price_history.csv.
Earlier snapshots in ../price-snapshots/*.json are folded into the history on first run.
If <out_dir>/README.md exists, the figures in it are rewritten from the new CSVs (see write_card).
"""
import collections
import csv
import glob
import json
import os
import re
import statistics
import sys
import textwrap
import urllib.request
API = "https://api.uplinkswitch.com/v1"
SITE = "https://uplinkswitch.ai"
HERE = os.path.dirname(os.path.abspath(__file__))
# Catalog id -> official open-weight repo on the Hugging Face Hub.
WEIGHTS = {
"deepseek-v4-pro": "deepseek-ai/DeepSeek-V4-Pro",
"deepseek-v4-flash": "deepseek-ai/DeepSeek-V4-Flash",
"deepseek-v4-flash-0731": "deepseek-ai/DeepSeek-V4-Flash-0731",
"deepseek-v4-flash-vision-exp": "deepseek-ai/DeepSeek-V4-Flash-Vision-Exp",
"deepseek-v4.1-flash": "deepseek-ai/DeepSeek-V4.1-Flash",
"deepseek-v4.1-flash-1017": "deepseek-ai/DeepSeek-V4.1-Flash-1017",
"glm-5.1": "zai-org/GLM-5.1",
"glm-5.2": "zai-org/GLM-5.2",
"glm-5.3": "zai-org/GLM-5.3",
"glm-5.3-flash": "zai-org/GLM-5.3-Flash",
"kimi-k2.5": "moonshotai/Kimi-K2.5",
"kimi-k2.6": "moonshotai/Kimi-K2.6",
"kimi-k3": "moonshotai/Kimi-K3",
"qwen3.6-27b": "Qwen/Qwen3.6-27B",
"minimax-m2.5": "MiniMaxAI/MiniMax-M2.5",
"minimax-m2.7": "MiniMaxAI/MiniMax-M2.7",
"mimo-v2.5": "XiaomiMiMo/MiMo-V2.5",
"diffusiongemma-26b-a4b-it": "google/diffusiongemma-26B-A4B-it",
"llama-3.2-11b-vision-instruct": "meta-llama/Llama-3.2-11B-Vision-Instruct",
}
def get(path):
req = urllib.request.Request(API + path, headers={"User-Agent": "uplinkswitch-dataset-build/1.0"})
with urllib.request.urlopen(req, timeout=60) as r:
return json.load(r)
def pct_under(price, lst):
if price is None or not lst:
return None
return round(100 * (1 - price / lst), 1)
def write_csv(path, fields, rows):
with open(path, "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
w.writerows(rows)
CHAT_FIELDS = [
"model_id", "display_name", "developer", "wire_formats",
"list_input_usd_per_1m", "list_cache_read_usd_per_1m", "list_output_usd_per_1m",
"price_input_usd_per_1m", "price_cache_read_usd_per_1m", "price_output_usd_per_1m",
"pct_under_list_input", "pct_under_list_output", "model_url", "weights_repo", "snapshot_at",
]
MEDIA_FIELDS = [
"model_id", "display_name", "developer", "kind", "unit", "variant",
"price_usd", "list_usd", "pct_under_list", "endpoints", "model_url", "snapshot_at",
]
HISTORY_FIELDS = [
"snapshot_date", "model_id", "display_name",
"list_input_usd_per_1m", "list_output_usd_per_1m",
"price_input_usd_per_1m", "price_output_usd_per_1m",
]
def num(v):
return None if v is None else float(v)
def main(out):
os.makedirs(os.path.join(out, "data"), exist_ok=True)
os.makedirs(os.path.join(out, "raw"), exist_ok=True)
chat = get("/catalog")
media = get("/catalog/media")
at = chat["generated_at"]
day = at[:10]
json.dump(chat, open(os.path.join(out, "raw", "catalog.json"), "w"), indent=1)
json.dump(media, open(os.path.join(out, "raw", "catalog_media.json"), "w"), indent=1)
rows = []
for m in chat["data"]:
p, l = m.get("pricing") or {}, m.get("list_pricing") or {}
rows.append({
"model_id": m["id"], "display_name": m["display_name"], "developer": m["developer"],
"wire_formats": "|".join(m.get("wire_formats") or []),
"list_input_usd_per_1m": l.get("input"), "list_cache_read_usd_per_1m": l.get("cache_read"),
"list_output_usd_per_1m": l.get("output"),
"price_input_usd_per_1m": p.get("input"), "price_cache_read_usd_per_1m": p.get("cache_read"),
"price_output_usd_per_1m": p.get("output"),
"pct_under_list_input": pct_under(p.get("input"), l.get("input")),
"pct_under_list_output": pct_under(p.get("output"), l.get("output")),
"model_url": f"{SITE}/models/{m['id']}",
"weights_repo": f"https://huggingface.co/{WEIGHTS[m['id']]}" if m["id"] in WEIGHTS else None,
"snapshot_at": at,
})
rows.sort(key=lambda r: (r["developer"], r["model_id"]))
write_csv(os.path.join(out, "data", "chat_models.csv"), CHAT_FIELDS, rows)
mrows = []
for m in media["data"]:
for v in m.get("pricing") or []:
price, lst = num(v.get("price_usd")), num(v.get("list_usd"))
mrows.append({
"model_id": m["id"], "display_name": m["display_name"], "developer": m["developer"],
"kind": m["kind"], "unit": m["unit"],
"variant": ", ".join(f"{k}={val}" for k, val in (v.get("when") or {}).items()) or "default",
"price_usd": price, "list_usd": lst, "pct_under_list": pct_under(price, lst),
"endpoints": "|".join(m.get("endpoints") or []),
"model_url": f"{SITE}/models/media/{m['id']}", "snapshot_at": at,
})
mrows.sort(key=lambda r: (r["kind"], r["developer"], r["model_id"], r["variant"]))
write_csv(os.path.join(out, "data", "media_models.csv"), MEDIA_FIELDS, mrows)
# Price history: existing file (if any) + saved snapshots + today, one row per (date, model).
hist_path = os.path.join(out, "data", "chat_price_history.csv")
hist = {}
if os.path.exists(hist_path):
for r in csv.DictReader(open(hist_path)):
hist[(r["snapshot_date"], r["model_id"])] = r
for snap in sorted(glob.glob(os.path.join(HERE, "..", "price-snapshots", "*.json"))):
s = json.load(open(snap))
d = s["taken_at"][:10]
for mid, m in s["models"].items():
l, p = m.get("list") or {}, m.get("pricing") or {}
hist.setdefault((d, mid), {
"snapshot_date": d, "model_id": mid, "display_name": m.get("name"),
"list_input_usd_per_1m": l.get("input"), "list_output_usd_per_1m": l.get("output"),
"price_input_usd_per_1m": p.get("input"), "price_output_usd_per_1m": p.get("output"),
})
for r in rows:
hist[(day, r["model_id"])] = {
"snapshot_date": day, "model_id": r["model_id"], "display_name": r["display_name"],
"list_input_usd_per_1m": r["list_input_usd_per_1m"], "list_output_usd_per_1m": r["list_output_usd_per_1m"],
"price_input_usd_per_1m": r["price_input_usd_per_1m"], "price_output_usd_per_1m": r["price_output_usd_per_1m"],
}
write_csv(hist_path, HISTORY_FIELDS, [hist[k] for k in sorted(hist)])
print(f"{len(rows)} chat models, {len(mrows)} media price rows ({len(media['data'])} models), "
f"{len(hist)} history rows, snapshot {at}")
write_card(out)
# The card's changing figures sit between <!-- name --> and <!-- /name --> comments, which the Hub renders
# invisibly. Block markers (stats, examples, open_weights) go on their own lines with blank lines around them.
MARK = re.compile(r"<!-- (\w+) -->(.*?)<!-- /\1 -->", re.S)
MODEL_LINK = re.compile(r"\]\(https://uplinkswitch\.(?:ai|com)/models/([\w.-]+)\)")
SIZES = [(1_000, "n<1K"), (10_000, "1K<n<10K"), (100_000, "10K<n<100K"), (1_000_000, "100K<n<1M")]
WORDS = "zero one two three four five six seven eight nine".split()
def money(v, places=0):
"""A catalog price with every digit it has, padded to `places` decimals: 4 -> '4', 2.1 -> '2.10'."""
whole, _, frac = f"{float(v):.6f}".partition(".")
frac = frac.rstrip("0").ljust(places, "0")
return f"{whole}.{frac}" if frac else whole
def read_rows(out, name):
with open(os.path.join(out, "data", name), newline="") as f:
return list(csv.DictReader(f))
def write_card(out):
"""Rewrite README.md's figures from the CSVs in out/data. A marker missing from the card is reported and its
figure left as it was; the data files are already written either way."""
path = os.path.join(out, "README.md")
if not os.path.exists(path):
return
chat = read_rows(out, "chat_models.csv")
media = read_rows(out, "media_models.csv")
hist = read_rows(out, "chat_price_history.csv")
by_id = {r["model_id"]: r for r in chat}
listed = [r for r in chat if r["list_input_usd_per_1m"] or r["list_output_usd_per_1m"]]
under = [float(r["pct_under_list_output"]) for r in chat if r["pct_under_list_output"]]
cache = sorted(r["model_id"] for r in chat if r["list_cache_read_usd_per_1m"] and r["price_cache_read_usd_per_1m"]
and float(r["price_cache_read_usd_per_1m"]) > float(r["list_cache_read_usd_per_1m"]))
stats = f"In this snapshot, {len(listed)} of the {len(chat)} chat models have a published list price."
if under:
stats += f" The median UplinkSwitch output price is {money(statistics.median(under))}% under list."
if cache:
n = WORDS[len(cache)] if len(cache) < 10 else str(len(cache))
stats += (f" Cached input costs more than list on {n} model{'s' if len(cache) > 1 else ''} ("
+ ", ".join(f"`{m}`" for m in cache) + "), so check the cache column if your workload is cache-heavy.")
devs = collections.Counter(r["developer"] for r in media)
values = {
"chat_models": str(len(chat)),
"media_models": str(len({r["model_id"] for r in media})),
"media_rows": str(len(media)),
"history_rows": str(len(hist)),
"history_since": min(r["snapshot_date"] for r in hist),
"snapshot_date": chat[0]["snapshot_at"][:10],
"media_developers": ", ".join(sorted(devs, key=lambda d: (-devs[d], d))),
"stats": textwrap.fill(stats, 118, break_long_words=False, break_on_hyphens=False),
}
def pair(r, key, places):
a, b = r[f"{key}_input_usd_per_1m"], r[f"{key}_output_usd_per_1m"]
return f"{money(a, places)} / {money(b, places)}" if a and b else "—"
def table(name, block):
"""Example rows keep their pick and wording and get today's prices; open-weight rows follow the catalog."""
lines, seen, last = [], set(), 0
for line in block.split("\n"):
link = MODEL_LINK.search(line) if line.startswith("|") else None
if not link:
lines.append(line)
last = len(lines) if line.startswith("|") else last
continue
mid, cells = link.group(1), line.split("|")
r = by_id.get(mid)
if r is None or (name == "open_weights" and not r["weights_repo"]):
print(f"card: dropped the {name} row for {mid}, which the catalog no longer lists")
continue
if name == "examples":
cells[2], cells[3] = f" {pair(r, 'list', 0)} ", f" {pair(r, 'price', 2)} "
else:
cells[2] = f" [{r['weights_repo'].removeprefix('https://huggingface.co/')}]({r['weights_repo']}) "
seen.add(mid)
lines.append("|".join(cells))
last = len(lines)
if name == "open_weights":
lines[last:last] = [
f"| {r['display_name']} | [{r['weights_repo'].removeprefix('https://huggingface.co/')}]"
f"({r['weights_repo']}) | [{r['model_id']}]({r['model_url']}) |"
for r in chat if r["weights_repo"] and r["model_id"] not in seen]
return "\n".join(lines)
found = set()
def fill(m):
name, inner = m.group(1), m.group(2)
if name in ("examples", "open_weights"):
new = table(name, inner)
elif name in values:
lead, _, trail = re.fullmatch(r"(\s*)(.*?)(\s*)", inner, re.S).groups()
new = lead + values[name] + trail
else:
return m.group(0)
found.add(name)
return f"<!-- {name} -->{new}<!-- /{name} -->"
with open(path, newline="", encoding="utf-8") as f:
old = f.read()
text = MARK.sub(fill, old)
total = len(chat) + len(media) + len(hist)
size = next((label for limit, label in SIZES if total < limit), "1M<n<10M")
text = re.sub(r"(?m)^(size_categories:\r?\n\s+- )([^\r\n]+)", lambda m: m.group(1) + size, text, count=1)
missing = sorted((set(values) | {"examples", "open_weights"}) - found)
if missing:
print(f"card: no marker for {', '.join(missing)} in README.md; those figures were left as they were")
if text != old:
with open(path, "w", newline="", encoding="utf-8") as f:
f.write(text)
print(f"card: {len(found)} figure groups refreshed, {'changed' if text != old else 'unchanged'}")
if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "repo"))
|