"""Build the uplinkswitch/llm-api-pricing dataset files from the public catalogs. Usage: python build.py 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 /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 and 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"(.*?)", re.S) MODEL_LINK = re.compile(r"\]\(https://uplinkswitch\.(?:ai|com)/models/([\w.-]+)\)") SIZES = [(1_000, "n<1K"), (10_000, "1K '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"{new}" 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 1 else os.path.join(HERE, "repo"))