Repository navigation
feat(ci): add the cost map sync bot for openrouter and vercel_ai_gateway - #39845
mateo-berri wants to merge 16 commits into
Conversation
Greptile SummaryThis PR replaces the retired weekly model-price updater with a guarded cost-map synchronization workflow for OpenRouter and Vercel AI Gateway.
Confidence Score: 5/5The PR appears safe to merge; no actionable findings remain outstanding. No changes were made after the previous review. The previously outstanding schema issue is fixed because price_varies_by_provider is now classified by the production schema generator, and all other previous findings were resolved or withdrawn.
|
| Filename | Overview |
|---|---|
| scripts/sync_cost_map.py | Implements catalog conversion, guarded map updates, trait inheritance, warning reporting, and deterministic serialization; no new issue was introduced since the previous review. |
| .github/workflows/cost-map-sync.yml | Adds scheduled GitHub App synchronization, trusted PR reconciliation, no-op caching, and guarded merge behavior. |
| .github/workflows/guard-main-branch.yml | Limits the cost-map branch exception to PRs authored by the configured synchronization App. |
| ci_cd/generate_model_prices_schema.py | Classifies price_varies_by_provider as a supported boolean key, resolving the previously outstanding schema-generator failure. |
| tests/test_litellm/test_sync_cost_map.py | Covers catalog transformations, safety holds, inheritance, tier handling, and generated reporting. |
| tests/test_litellm/test_utils.py | Allows cost-map tier breakpoints generated from current catalog data while retaining schema validation. |
Reviews (16): Last reviewed commit: "fix(cost-map-schema): classify price_var..." | Re-trigger Greptile
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…uard in the reasoning-effort docstring
|
bugbot run |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Autofix Details
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: First PR body can exceed GitHub limit
- render_pr_body now caps the Added and Updated sections to the largest per-section limit whose rendered body fits inside GitHub's 65,536-char PR body limit and appends a note pointing to the workflow run log for the full list.
Or push these changes by commenting:
@cursor push ac9ba03805
Preview (ac9ba03805)
diff --git a/scripts/sync_cost_map.py b/scripts/sync_cost_map.py
--- a/scripts/sync_cost_map.py
+++ b/scripts/sync_cost_map.py
@@ -384,19 +384,25 @@
)
-def _section_block(title: str, lines: Sequence[str], backtick: bool) -> str:
- bullets: Final = "\n".join(f"- `{line}`" if backtick else f"- {line}" for line in lines) or "- none"
- return f"### {title} ({len(lines)})\n{bullets}\n"
+GITHUB_PR_BODY_LIMIT: Final = 65_536
-def _provider_body(outcome: ProviderOutcome) -> str:
+def _section_block(title: str, lines: Sequence[str], backtick: bool, max_lines: int | None = None) -> str:
+ shown: Final = tuple(lines) if max_lines is None or len(lines) <= max_lines else tuple(lines)[:max_lines]
+ hidden: Final = len(lines) - len(shown)
+ bullets: Final = "\n".join(f"- `{line}`" if backtick else f"- {line}" for line in shown) or "- none"
+ footer: Final = f"\n- ... and {hidden} more (see the workflow run log for the full list)" if hidden else ""
+ return f"### {title} ({len(lines)})\n{bullets}{footer}\n"
+
+
+def _provider_body(outcome: ProviderOutcome, max_lines: int | None = None) -> str:
skipped: Final = ", ".join(f"{reason} ({count})" for reason, count in sorted(outcome.skipped.items())) or "none"
return (
f"## {outcome.provider}\n"
"\n"
- f"{_section_block('Added', outcome.added, backtick=True)}"
+ f"{_section_block('Added', outcome.added, backtick=True, max_lines=max_lines)}"
"\n"
- f"{_section_block('Updated', outcome.updated, backtick=True)}"
+ f"{_section_block('Updated', outcome.updated, backtick=True, max_lines=max_lines)}"
"\n"
f"{_section_block('Warnings needing a human call', outcome.warnings, backtick=False)}"
"\n"
@@ -404,15 +410,27 @@
)
-def render_pr_body(outcome: SyncOutcome) -> str:
+def _rendered(outcome: SyncOutcome, max_lines: int | None) -> str:
return (
"Automated sync of the openrouter and vercel_ai_gateway entries in model_prices_and_context_window.json "
f"against `GET {OPENROUTER_MODELS_URL}` and `GET {VERCEL_MODELS_URL}` by scripts/sync_cost_map.py. "
"The cost-map-guard check enforces that this PR only adds or reprices models.\n"
- "\n" + "\n".join(_provider_body(provider) for provider in outcome.providers)
+ "\n" + "\n".join(_provider_body(provider, max_lines) for provider in outcome.providers)
)
+def render_pr_body(outcome: SyncOutcome) -> str:
+ full: Final = _rendered(outcome, max_lines=None)
+ if len(full) <= GITHUB_PR_BODY_LIMIT:
+ return full
+ max_count: Final = max((max(len(p.added), len(p.updated)) for p in outcome.providers), default=0)
+ return next(
+ body
+ for body in (_rendered(outcome, max_lines=cap) for cap in range(max_count, -1, -1))
+ if len(body) <= GITHUB_PR_BODY_LIMIT
+ )
+
+
def render_summary(outcome: SyncOutcome) -> str:
return " ".join(
f"{provider.provider}: added={len(provider.added)} updated={len(provider.updated)} "
diff --git a/tests/test_litellm/test_sync_cost_map.py b/tests/test_litellm/test_sync_cost_map.py
--- a/tests/test_litellm/test_sync_cost_map.py
+++ b/tests/test_litellm/test_sync_cost_map.py
@@ -264,6 +264,46 @@
assert "Catalog rows skipped: deprecated (1), no usable price (1), not token priced (1)" in body
+def test_pr_body_stays_within_github_limit_when_the_diff_is_huge(sync: ModuleType) -> None:
+ huge: Final = sync.SyncOutcome(
+ cost_map={},
+ providers=(
+ sync.ProviderOutcome(
+ provider="openrouter",
+ added=tuple(f"openrouter/vendor/model-{i:04d}" for i in range(500)),
+ updated=tuple(
+ f"openrouter/vendor/model-{i:04d}: input_cost_per_token: 1e-06 -> 2e-06; "
+ "output_cost_per_token: 3e-06 -> 4e-06; cache_read_input_token_cost: 1e-07 -> 2e-07"
+ for i in range(300)
+ ),
+ warnings=(),
+ skipped={},
+ ),
+ sync.ProviderOutcome(
+ provider="vercel_ai_gateway",
+ added=tuple(f"vercel_ai_gateway/vendor/model-{i:04d}" for i in range(400)),
+ updated=(),
+ warnings=(),
+ skipped={},
+ ),
+ ),
+ )
+
+ body: Final = sync.render_pr_body(huge)
+
+ assert len(body) <= sync.GITHUB_PR_BODY_LIMIT
+ assert "### Added (500)" in body and "### Updated (300)" in body
+ assert "### Added (400)" in body
+ assert "more (see the workflow run log for the full list)" in body
+
+
+def test_pr_body_is_not_truncated_when_it_already_fits(sync: ModuleType) -> None:
+ body: Final = sync.render_pr_body(_run(sync, _base_map()))
+
+ assert len(body) <= sync.GITHUB_PR_BODY_LIMIT
+ assert "more (see the workflow run log for the full list)" not in body
+
+
@pytest.mark.parametrize(
("loader", "raw"),
[You can send follow-ups to the cloud agent here.
…der GitHub's body limit
… warnings stay findable
|
bugbot run |
…-of-bounds changes, and reconcile the open bot PR Vercel long-context tiers become *_above_<N>k_tokens keys when contiguous on a whole thousand, and a row whose tiers do not fit is skipped with a warning. Image and audio output are priced per token, and a row with an unpriced non-text output is skipped instead of billed as text. A new entry inherits the traits no catalog expresses (cache minimum, adaptive thinking, sampling params, system messages, thinking always on) from its same-mode root, found by the bare name or its longest dash prefix. The max_tokens / max_output_tokens pair moves as a unit. Shrinking limits, prices crossing zero or moving more than 10x, and every price on an already-priced varies_by_provider row are held back and listed as warnings for a human commit. Updated entries keep their curated key order with new keys appended sorted. The workflow's own token is read-only and every write uses the GitHub App token; without the App a scheduled run explains why it cannot open a PR. Each tick first reconciles the open bot PR: a conflicting one is closed and re-synced, a green one is merged, a red one is left for a human, and a sync only runs when none is open. The sync step runs with --no-dev and only when it will be used. The hardcoded map schema in test_utils.py gains the 32k tier keys the synced map now carries.
PR overviewThis PR adds a CI bot that synchronizes model cost maps from OpenRouter and Vercel AI Gateway pricing catalogs. One issue has been addressed, but the remaining workflow still automatically merges externally sourced pricing into budget controls. Manipulated additions or incremental price reductions could understate usage costs and allow paid calls without accurate spend accounting; approval or independent verification is still needed. Open issues (1)
Fixed/addressed: 1 · PR risk: 6/10 |
…repo The reconciler picked the open sync PR by title and branch prefix alone, so a fork PR carrying the same title and a litellm_cost_map_sync_ branch could pass the guard with its own repricing and be merged with the App token. It now lists PRs authored by the App (--author app/<slug>) and drops cross-repository heads, and without the App it never selects a PR, which also removes the unreachable no-App warning branch.
|
bugbot run |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Autofix Details
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Output tiers ignored without input keys
- Made _vercel_tiers reject rows whose output or cache tier breakpoints do not appear in the input tier breakpoints, so those rows are skipped instead of stored with tier keys the runtime cost calculator would never consult.
Or push these changes by commenting:
@cursor push d89d3c7280
Preview (d89d3c7280)
diff --git a/scripts/sync_cost_map.py b/scripts/sync_cost_map.py
--- a/scripts/sync_cost_map.py
+++ b/scripts/sync_cost_map.py
@@ -261,15 +261,32 @@
def _vercel_tiers(pricing: VercelPricing, cache_read: float | None, cache_write: float | None) -> Prices | Unmappable:
- parts: Final = (
- _tiered("input_cost_per_token", _token_price(pricing.input), pricing.input_tiers),
+ input_part: Final = _tiered("input_cost_per_token", _token_price(pricing.input), pricing.input_tiers)
+ dependents: Final = (
_tiered("output_cost_per_token", _token_price(pricing.output), pricing.output_tiers),
_tiered("cache_read_input_token_cost", cache_read, pricing.input_cache_read_tiers),
_tiered("cache_creation_input_token_cost", cache_write, pricing.input_cache_write_tiers),
)
+ parts: Final = (input_part, *dependents)
problem: Final = next((part for part in parts if isinstance(part, Unmappable)), None)
if problem is not None:
return problem
+ input_thresholds: Final = frozenset(
+ name.rsplit("_above_", 1)[1] for part in (input_part,) if not isinstance(part, Unmappable) for name in part
+ )
+ orphan: Final = next(
+ (
+ name
+ for part in dependents
+ if not isinstance(part, Unmappable)
+ for name in part
+ if name.rsplit("_above_", 1)[1] not in input_thresholds
+ ),
+ None,
+ )
+ if orphan is not None:
+ base, threshold = orphan.rsplit("_above_", 1)
+ return Unmappable(f"{base} tier at {threshold} has no matching input tier")
return MappingProxyType(
{name: price for part in parts if not isinstance(part, Unmappable) for name, price in part.items()}
)
diff --git a/tests/test_litellm/test_sync_cost_map.py b/tests/test_litellm/test_sync_cost_map.py
--- a/tests/test_litellm/test_sync_cost_map.py
+++ b/tests/test_litellm/test_sync_cost_map.py
@@ -572,14 +572,17 @@
pricing: Final = {
"input": "0.0000015",
"input_tiers": [
- {"cost": "0.0000015", "min": 0, "max": 32001},
- {"cost": "0.0000027", "min": 32001, "max": 128001},
- {"cost": "0.0000045", "min": 128001},
+ {"cost": "0.0000015", "min": 0, "max": 128001},
+ {"cost": "0.0000027", "min": 128001, "max": 200001},
+ {"cost": "0.0000045", "min": 200001},
],
"output": "0.0000075",
"output_tiers": [{"cost": "0.0000075", "max": 200001}, {"cost": "0.00001125", "min": 200001}],
"input_cache_read": "0.0000003",
- "input_cache_read_tiers": [{"cost": "0.0000006", "min": 256000}],
+ "input_cache_read_tiers": [
+ {"cost": "0.0000003", "min": 0, "max": 200001},
+ {"cost": "0.0000006", "min": 200001},
+ ],
"input_cache_write": "0.000002",
"input_cache_write_tiers": [{"cost": "0.000002", "min": 0, "max": 200001}, {"cost": "0.000004", "min": 200001}],
}
@@ -589,14 +592,37 @@
entry: Final = outcome.cost_map["vercel_ai_gateway/acme/long"]
assert entry["input_cost_per_token"] == 1.5e-6
- assert entry["input_cost_per_token_above_32k_tokens"] == 2.7e-6
- assert entry["input_cost_per_token_above_128k_tokens"] == 4.5e-6
+ assert entry["input_cost_per_token_above_128k_tokens"] == 2.7e-6
+ assert entry["input_cost_per_token_above_200k_tokens"] == 4.5e-6
assert entry["output_cost_per_token_above_200k_tokens"] == 1.125e-5
- assert entry["cache_read_input_token_cost_above_256k_tokens"] == 6e-7
+ assert entry["cache_read_input_token_cost_above_200k_tokens"] == 6e-7
assert entry["cache_creation_input_token_cost_above_200k_tokens"] == 4e-6
assert not any(key.endswith("_above_0k_tokens") for key in entry)
+def test_output_or_cache_tiers_without_matching_input_tier_skip_the_row(sync: ModuleType) -> None:
+ pricing: Final = {
+ "input": "0.0000015",
+ "input_tiers": [
+ {"cost": "0.0000015", "min": 0, "max": 32001},
+ {"cost": "0.0000027", "min": 32001, "max": 128001},
+ {"cost": "0.0000045", "min": 128001},
+ ],
+ "output": "0.0000075",
+ "output_tiers": [{"cost": "0.0000075", "max": 200001}, {"cost": "0.00001125", "min": 200001}],
+ }
+ catalog: Final = sync.load_vercel(_vercel_rows({"id": "acme/orphan", "pricing": pricing}), now_ms=NOW_MS)
+
+ outcome: Final = sync.compute_sync({}, (catalog,))
+
+ assert "vercel_ai_gateway/acme/orphan" not in outcome.cost_map
+ assert dict(catalog.skipped) == {"tiers outside the registry's thresholds": 1}
+ assert outcome.providers[0].warnings == (
+ "vercel_ai_gateway/acme/orphan: output_cost_per_token tier at 200k_tokens has no matching input tier; "
+ "row skipped",
+ )
+
+
@pytest.mark.parametrize(
("tiers", "problem"),
[You can send follow-ups to the cloud agent here.
…breakpoints The cost calculator walks the input_cost_per_token_above_* thresholds and reads the output and cache prices at the same threshold, so an output or cache tier that broke at a breakpoint no input tier had was stored and never billed. Each list is now written at the union of the row's breakpoints, priced from the tier that covers that breakpoint. Today's 41 tiered catalog rows are aligned, so the synced map is byte-identical; the regression test bills a mismatched row through generic_cost_per_token
|
bugbot run |
… stop pinning the prices it owns The reconcile only looks at bot PRs against the branch the run is on, so a dispatch from another branch never counts as the open sync PR. When a green bot PR cannot be merged because the app is not a bypass actor yet, the run arms auto-merge and warns instead of failing every tick. A base with no required checks falls back to every check so a dispatch there can still merge, and a tick whose catalogs and base match the last no-op sync skips the install and the script. guard-main-branch accepts litellm_cost_map_sync_* heads so the bot keeps working once main is the default branch again. The tests that pinned exact OpenRouter prices and limits now check that the entries exist and are priced: the sync owns those values, and a pin would turn every legitimate reprice into a red bot PR that pauses syncing.
|
bugbot run |
| merged=false | ||
| case "$guard,$required" in | ||
| SUCCESS,pass|SUCCESS,pass,skipping|SUCCESS,skipping) | ||
| if gh pr merge "$number" --repo "$GITHUB_REPOSITORY" --merge --delete-branch; then |
There was a problem hiding this comment.
Medium: Third-party pricing is auto-merged into budget controls
An attacker who alters either external catalog can add a paid model with a zero price or repeatedly reduce an existing price in increments that pass the 10x check. This PR then merges those values without review; because the resulting map drives cost and budget accounting, users can consume paid calls without the corresponding spend being recorded. Require human approval for additions and price decreases, or verify them against an independent trusted source before allowing the bot to merge.
There was a problem hiding this comment.
Both catalogs are the gateways' own published prices over HTTPS, and each gateway bills what it publishes. The 10x hold catches slips, by design.
There was a problem hiding this comment.
Thanks for the detail. I can't automatically confirm this is safe to dismiss, so I'm leaving the thread open for a maintainer to make the call.
…copied caps A Vercel row seeded at a varies_by_provider headline price now carries price_varies_by_provider: true and only a row with that mark keeps following the catalog; a curated row citing the catalog page as source holds its price like any other. A copied output cap still yields to the catalog ceiling, but a ceiling more than 10x below it is held as a catalog glitch. The map schema test learns the new key.
|
bugbot run |
| "litellm_provider": entry.provider, | ||
| "mode": entry.mode, | ||
| "source": entry.source, | ||
| **({"price_varies_by_provider": True} if entry.indicative_prices else {}), |
There was a problem hiding this comment.
Schema Rejects Ownership Marker
New Vercel entries whose catalog prices vary by provider receive price_varies_by_provider, but the production schema generator does not classify this key. When the first such entry is added, generate_model_prices_schema.py exits because the key is unclassified, so the scheduled workflow cannot generate the schema or open a usable sync PR.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
Autofix Details
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: New price mark breaks schema generation
- Added price_varies_by_provider to EXTRA_BOOLEAN_KEYS in ci_cd/generate_model_prices_schema.py so classify recognizes the key that sync_cost_map now writes.
Or push these changes by commenting:
@cursor push b4640ae966
Preview (b4640ae966)
diff --git a/ci_cd/generate_model_prices_schema.py b/ci_cd/generate_model_prices_schema.py
--- a/ci_cd/generate_model_prices_schema.py
+++ b/ci_cd/generate_model_prices_schema.py
@@ -28,6 +28,7 @@
"use_openai_responses_path",
"bedrock_converse_supports_strict_tools",
"thinking_always_on",
+ "price_varies_by_provider",
}
)You can send follow-ups to the cloud agent here.
… map passes the guard The sync marks a Vercel row seeded at a varies_by_provider headline price, but the production schema generator only knew the key from the test-side INTENDED_SCHEMA and exited on the first synced map as unclassified, so the workflow would have stopped before opening a PR. The key is a boolean in the generator's key tables, and a regression test syncs the fixtures plus a varies-by-provider row and validates the result against the generated schema.
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 84b7f25. Configure here.
|
Closing as superseded since the provider info sync bot now opens pricing PRs that merge into main through cost-map-guard, and a second writer would conflict |

TLDR
Problem this solves:
How it solves it:
scripts/sync_cost_map.pydiffs both public catalogs into the mapcost-map-sync.ymlruns it every 5 minutes as the GitHub App and opens alitellm_cost_map_sync_*PRcost-map-guard(feat(ci): add the cost map guard check #39835) and CI are green, closes it if it stops merging cleanly, and leaves a red one for a humanauto_update_price_and_context_window.ymland its scriptvalidate-model-prices-jsoncheck tocost-map-guardin thedeclared_reasoning_effortsdocstring*_above_32k_tokenskeys the qwen3 tiers need to the hardcoded map schema intest_utils.pyguard-main-branchaccept alitellm_cost_map_sync_*head opened by the sync App (vars.COST_MAP_BOT_APP_SLUG), so the bot keeps merging oncemainis the default branch againtest_get_model_cost_map.py,test_cost_calculator.py, andtest_utils.py: the sync owns those values, so the tests now check that the entries exist and are priced; the map schema test accepts any*_above_<N>k_tokensbreakpoint the catalogs useUser Flow
Before: a proxy admin who routes to a model OpenRouter shipped this week gets no context window, no prices, and no capability flags for it until someone hand-edits the map
openrouter/inception/mercury-2.5-previewandopenrouter/deepseek/deepseek-v4-pro-0813to their config and boots the proxyGET https://litellm-domain/model/inforeturnsmercury-2.5withmax_input_tokens: null,input_cost_per_token: 0, and nosupports_*flags, anddeepseek-v4-proat $1.32/M input and $3.96/M output while https://openrouter.ai/deepseek/deepseek-v4-pro-0813 lists $1.12/M and $3.36/MPOST https://litellm-domain/v1/chat/completionsto either model returns 200 withx-litellm-response-costset from OpenRouter's own usage cost, so spend still tracks, but context-window routing and capability checks treatmercury-2.5as unknown and the model hub shows it with no limitsAfter: the map on the default branch catches up within minutes of the catalog, with no human in the loop
GET https://litellm-domain/model/inforeturnsmercury-2.5withmax_input_tokens: 260000,max_output_tokens: 65536,input_cost_per_token: 4e-08,output_cost_per_token: 1.5e-07,supports_function_calling: true,supports_reasoning: true, anddeepseek-v4-proat $1.12/M input and $3.36/M outputPOST https://litellm-domain/v1/chat/completionsto either model returns 200 as before, and every Vercel AI Gateway model the admin routes to is now billed at the gateway's current price instead of the months-old onecost-map-guardcheck is greenDesign
Two providers, both with public machine-readable catalogs:
GET https://openrouter.ai/api/v1/modelsandGET https://ai-gateway.vercel.sh/v1/models. Both price per token as decimal strings; the script normalizes to six significant digits, maps context and output limits, cache read and write prices and the reasoning price, and turnssupported_parametersand input modalities into thesupports_*flags. Vercel's long-context tiers become litellm's*_above_<N>k_tokenskeys when the tiers are contiguous and break on a whole thousand, which all 41 tiered rows do today; a row whose tiers do not fit is skipped with a warning rather than flattened to its headline price. Every list (input, output, cache read, cache write) is written at the union of the row's breakpoints, priced from the tier that covers each one, because the cost calculator walks the input thresholds and reads the output and cache prices at the same threshold; a breakpoint only one list had would otherwise be stored and never billed. Image and audio output are priced per token fromimage_outputandaudio_output(output_cost_per_image_token,output_cost_per_audio_token), and a row whose non-text output modality carries no per-token price is skipped, since billing its images as text would undercharge. Two catalog fields are deliberately left out: OpenRouter'spricing.image(input images) is per image on some rows and per image token on others, so it cannot be written to either litellm field safely, andsupports_prompt_cachingis not set from a cache price alone because the map pairs it with a per-modelprompt_cache_min_tokensthe catalogs do not carry (a whole-map unit test enforces that pairing for the Claude entries). Vercel rows maplanguagetomode: chatandembeddingtomode: embedding; image, video, speech, transcription, realtime, and reranking rows are skipped and counted in the PR body, as are rows whosedeprecated_atdate has passed (a scheduled deprecation keeps syncing until the date), router rows priced-1, and rows with no usable priceThe contract is the one the guard enforces, so a bad catalog day can never delete anything: an existing entry only gains or changes the fields the catalog expresses, no field is ever removed, capability flags are only ever set to true and a flag curated as
falseis held for a human, a curatedmax_tokens/max_output_tokenspair moves as a unit to the catalog's output ceiling (a legacy entry with onlymax_tokensgainsmax_output_tokensat the same value, which keepstest_max_tokens_consistencygreen across the whole map; a curated output cap equal to the entry's ownmax_input_tokensis a copy of the context window rather than a ceiling, 12 entries on today's catalogs such asopenrouter/deepseek/deepseek-v3.2at 163840 for both, so the catalog's smaller ceiling replaces it instead of being held as a shrink, unless the ceiling is more than 10x smaller, which reads as a catalog glitch and is held: 1 of the 12 today,openrouter/qwen/qwen3-235b-a22b-2507at 262144 against a 16384 ceiling), a mode mismatch (the map sayschat, the catalog saysembedding) is left alone and listed under "Warnings needing a human call", and a model that left the catalog stays in the map. Some catalog changes are held back instead of applied and listed under the same warnings for a human commit: a limit that shrinks, a price that crosses zero or moves more than 10x, and any price on a Vercel row flaggedvaries_by_provideronce a human priced the entry (the catalog shows one upstream's price there, and 7 of the 65 such rows are curated at a different one); every entry the sync creates carries its catalog page assource, and one seeded at avaries_by_providerheadline is markedprice_varies_by_provider: trueand keeps following the catalog while the mark is there (the schema generator inci_cd/generate_model_prices_schema.pyknows the key, so the workflow's schema regeneration accepts the first marked row), so a bot-seeded row does not freeze after its first merge and a human who curates one provider's own price drops the mark (sourceis never read as provenance:vercel_ai_gateway/zai/glm-4.6cites its catalog page assourceand still holds). A new entry inherits the model-intrinsic traits of the root entry it routes to, the exact bare name in any mode (vercel_ai_gateway/openai/gpt-5-codextakessupports_system_messages: falsefromgpt-5-codex, nottruefromgpt-5) or else the longest same-mode dash prefix (prompt_cache_min_tokens,supports_adaptive_thinking,thinking_always_on,supports_sampling_params, andsupports_system_messages; every othersupports_*flag comes from the catalog), soopenrouter/anthropic/claude-fable-5:batchgets the family's 512-token cache minimum and always-on thinking; route features like web search or service tiers are deliberately not inherited. Updated entries keep their curated key order with new keys appended sorted, new entries land at the end of their provider's block, and both the root file and thelitellm/backup are written with the repo's own serializer so the guard's byte-identical check holds. Nothing is remembered between runs, so a held change is listed again on every run until a human commits it: today that is 7 Vercel rows curated at a price other than the catalog's, 26 shrinking limits on 17 entries (context windows the catalog now states lower, e.g.openrouter/qwen/qwen3-235b-a22b-thinking-2507262144 to 131072, and genuine output caps such asvercel_ai_gateway/anthropic/claude-sonnet-464000 to 8192), onesupports_reasoningcurated asfalse, and 4 embedding rows curated aschatOpenRouter reports the billed cost in
usage.costand the proxy already prefers it forx-litellm-response-cost, so for OpenRouter the map drives model info, context-window routing, capability checks, and the fallback price; for Vercel AI Gateway the map is the only price sourceThe workflow only ever writes as the GitHub App: its own token is read-only (
contents: read,pull-requests: read), and the branch push, the PR, the close, and the merge all use the token minted fromCOST_MAP_BOT_APP_IDandCOST_MAP_BOT_PRIVATE_KEY. The reconciler only ever acts on a PR the App itself authored from a same-repo branch (--author app/<app-slug>plusisCrossRepository == false), so a fork PR carrying the sync title and branch prefix is never closed or merged with the App token. There is nogithub.tokenfallback on purpose: a PR opened with the workflow's own token never triggerspull_requestworkflows, socost-map-guardcould not run on it. Without those secrets a scheduled run explains that it cannot open a PR and stops, and thedry_runinput runs the script and prints the report without opening anything. An app is needed because PRs created withgithub.tokentrigger no checks at all, and a ruleset bypass actor has to be an app or a team. Every tick starts by reconciling the one open bot PR against the branch the run is on before it syncs anything: a PR that no longer merges cleanly is closed with a comment and re-synced in the same run, a PR whosecost-map-guardand every required check have passed is merged, a PR with a failed check is left open for a human and the run prints a warning naming it, and a PR still being checked is left alone; only when no bot PR is open does the run sync and open one. On a base that reports no required checks (a dispatch from a branch without a ruleset) every check has to pass instead. When a green PR cannot be merged because the app is not a bypass actor yet, the run arms auto-merge on it and warns, so one approval lands it and nothing goes red every five minutes; if even arming fails, the run warns that a human has to merge it and carries on. So a merge lands one tick after the PR goes green, nothing polls inside a run, and a red bot PR pauses syncing until someone merges or closes it. Once the bot PR has been open for a day without merging, every tick fails with the PR number, because a warning inside a green scheduled run reaches nobody and a failed run does. A tick that would sync first hashes both catalogs together with the blob ids of the map, its schema, the sync script, and the schema generator, and looks that key up in the Actions cache; a hit means the last run with this exact input found nothing to sync, so the run stops before installing anything, and only a no-op sync saves the key. Keying on those blobs rather than the base sha keeps the hit across the unrelated merges staging takes every dayThe app needs to bypass review, never checks: the owner steps move the required status checks out of
guard-internal-staginginto a ruleset of their own with no bypass actor, and add the app to the three review rulesets in "pull requests only" mode. The app's token can then merge its own PR without approvals but cannot merge or push past a red required check, and a leaked key cannot push to the default branch at all;Protect Sensitive Fileskeeps two approvals on any change to the workflow itself.guard-main-branchaccepts alitellm_cost_map_sync_*head only when the PR author is the sync App (<COST_MAP_BOT_APP_SLUG>[bot], read from a repository variable, so the exception stays closed until the owner sets it), so the same flow works oncemainis the default branch again (wheremain-mergeneeds the same bypass andcost-map-guardhas to be required) and neither a person nor another installed bot can borrow the prefix to route a change past stagingThe bot does not skip CI on purpose, and a required check that goes red holds the bot PR for a human exactly as it would hold a hand-made price PR. The tests that pinned exact OpenRouter prices and limits (
test_get_model_cost_map.py,test_cost_calculator.py,test_utils.py) now check that the entries exist and are priced, because the sync owns those values and every legitimate reprice would otherwise red the bot PR; a new test for anopenrouter/*orvercel_ai_gateway/*entry should do the same. The map schema intest_utils.pylisted every tier breakpoint by hand, so it now takes any*_above_<N>k_tokenskey on the four ladders the script writes, since the cost calculator parses the threshold out of the key and a new Vercel breakpoint would otherwise red the bot PR until someone edited the testRelevant issues
Linear ticket
Resolves LIT-6995
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more@greptileaito re-request a review after pushing changes)Delays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Shared setup: a four-model proxy config (Before boots the first two; the two Vercel AI Gateway entries carry a placeholder key and are only read through
/model/info)Both legs boot
litellm/proxy/proxy_cli.py --config <the yaml above> --num_workers 2from the worktree (two uvicorn workers, the smallest multi-pod shape). Before runs at the guard tip with the map the proxy pulls from GitHub; After runs at this PR's tip withLITELLM_LOCAL_MODEL_COST_MAP=Trueon the map thatpython scripts/sync_cost_map.py --writeproduced from the live catalogsBefore (61bed79)
Sync against the live catalogs
ls scripts/sync_cost_map.py .github/workflows/cost-map-sync.ymlNo such file or directoryfor both; the only updater is the weekly workflow, whose scheduled runs since August 2 are allfailure(gh run list --workflow auto_update_price_and_context_window.yml --limit 6)Whole-map unit tests
LITELLM_LOCAL_MODEL_COST_MAP=True pytest tests/test_litellm/test_utils.py tests/test_litellm/test_cost_calculator.py tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py <and the 13 other files that iterate the whole map or pin an OpenRouter price> -q -n 41 failed, 1479 passed, the one failure beingtest_vertex_claude_completion_does_not_mutate_shared_extra_headerswithModuleNotFoundError: No module named 'vertexai'(a missing optional dependency in the worktree)Model info for a new and a stale OpenRouter model
curl -s http://127.0.0.1:48192/model/info -H 'Authorization: Bearer sk-lit6995-repro' | jq -c '.data[] | {name: .model_name, input: .model_info.input_cost_per_token, output: .model_info.output_cost_per_token, max_in: .model_info.max_input_tokens, max_out: .model_info.max_output_tokens, tools: .model_info.supports_function_calling, reasoning: .model_info.supports_reasoning}'Spend calculation for a three-tier model
for n in 20000 100000 200000 300000; do printf 'prompt_tokens=%s -> ' "$n"; curl -s http://127.0.0.1:48192/spend/calculate -H 'Authorization: Bearer sk-lit6995-repro' -H 'Content-Type: application/json' -d "{\"completion_response\":{\"model\":\"vercel_ai_gateway/alibaba/qwen3-coder-plus\",\"choices\":[{\"index\":0,\"finish_reason\":\"stop\",\"message\":{\"role\":\"assistant\",\"content\":\"ok\"}}],\"usage\":{\"prompt_tokens\":$n,\"completion_tokens\":1000,\"total_tokens\":$((n+1000))}}}" | jq -c '.cost // .error.message'; donevercel_ai_gateway/alibaba/qwen3-coder-plus, so the proxy cannot price it at any prompt size):Chat completion
for m in mercury-2.5 deepseek-v4-pro; do curl -si http://127.0.0.1:48192/v1/chat/completions -H 'Authorization: Bearer sk-lit6995-repro' -H 'Content-Type: application/json' -d "{\"model\":\"$m\",\"messages\":[{\"role\":\"user\",\"content\":\"Reply with the single word ok\"}],\"max_tokens\":16}" | grep -i 'HTTP/\|^x-litellm-response-cost'; doneusage.cost, so it is set even for the unmapped model):After (84b7f25)
The leg first ran at 340569b. b2402f8, d3ff59f, 5ad768d, and 9c1c0a2 only change
.github/workflows/guard-main-branch.ymland.github/workflows/cost-map-sync.yml, and 81142d4 only widens the map schema intests/test_litellm/test_utils.py, so no proxy code path read them. 412db8d changes the sync script's hold and inheritance rules, fb8f9af adds theprice_varies_by_providermark and the 10x floor on copied caps, and 84b7f25 teaches the schema generator the mark after the leg at fb8f9af failed its guard step onUnclassified keys in model_prices_and_context_window.json: price_varies_by_provider; each changes the synced map, so the whole leg was re-run at every one of them and every output below is from the run at 84b7f25Sync against the live catalogs
python scripts/sync_cost_map.py --write --pr-body-file /tmp/body.md && python ci_cd/generate_model_prices_schema.py && git diff --stat/tmp/body.mdis 18,253 chars, so every warning is listed (the 30-line cap applies to the added and updated lists; the warnings fall back to it only when listing them all would pass GitHub's 65k limit). Its 26 warning rows are the changes the script held back for a human plus the embedding rows curated aschat: 26 shrinking limits on 17 entries (e.g.openrouter/gryphe/mythomax-l2-13b: max_output_tokens: None -> 3686 held back: a shrinking limit; max_tokens: 8192 -> 3686 held back: a shrinking limit; 11 output caps that were copies of the entry's context window, such asopenrouter/deepseek/deepseek-v3.2at 163840, now land as updates, and one,openrouter/qwen/qwen3-235b-a22b-2507at 262144 against a 16384 ceiling, is held as a copied output cap shrinking more than 10x), 23 per-provider prices on 8 curated Vercel rows,vercel_ai_gateway/zai/glm-4.6among them now thatsourceno longer counts as provenance (e.g.vercel_ai_gateway/alibaba/qwen3-coder: input_cost_per_token: 4e-07 -> 1.5e-06 held back: the catalog price varies by provider), one capability flag curated asfalse(openrouter/deepseek/deepseek-v3.2-exp: supports_reasoning: False -> True held back: a capability flag curated as false), and 4 mode mismatches (vercel_ai_gateway/amazon/titan-embed-text-v2,vercel_ai_gateway/cohere/embed-v4.0,vercel_ai_gateway/mistral/codestral-embed,vercel_ai_gateway/mistral/mistral-embed, all left untouched)git checkout -b litellm_cost_map_sync_qa && git commit -qam 'qa' && python ci_cd/cost_map_guard.py --base 84b7f25e46 --head litellm_cost_map_sync_qa --head-ref litellm_cost_map_sync_qa; echo "guard exit $?"Whole-map unit tests
LITELLM_LOCAL_MODEL_COST_MAP=True python ci_cd/generate_model_prices_schema.py && LITELLM_LOCAL_MODEL_COST_MAP=True pytest $(grep -rl model_prices_and_context_window tests/test_litellm --include='*.py') -q -n 4with the synced map and schema in place: 85 files, every test that reads the map1 failed, 3713 passed, 16 skipped, the failure being the pre-existingvertexaiimport error from Before. At 340569b the same sweep gave2 failed, 3708 passed, 16 skipped, the other failure beingtest_aaamodel_prices_and_context_window_json_is_valid, whose hardcoded schema lacked the*_above_32k_tokenskeys the qwen3 tiers add (81142d4 adds them and fb8f9af addsprice_varies_by_provider, so the test passes on both the synced and the committed map). The same sweep before the dash-prefix root lookup caughtvercel_ai_gateway/anthropic/claude-opus-5-fastfailingtest_opus_5_all_variants_carry_512_token_cache_minimum, which is why a variant now inherits from its family rootModel info for a new and a stale OpenRouter model, a tiered and a new Vercel AI Gateway model
curlagainst the After proxy on port 43142, with the jq extended byabove_200k: .model_info.input_cost_per_token_above_200k_tokens, cache_min: .model_info.prompt_cache_min_tokens, adaptive: .model_info.supports_adaptive_thinking, thinking_on: .model_info.thinking_always_onclaude-sonnet-4.5is a curated entry that gained its 200k tier,claude-fable-5.1is a new entry that inherited the family's cache minimum and thinking traits):Spend calculation for a three-tier model
for n in 20000 100000 200000 300000; do printf 'prompt_tokens=%s -> ' "$n"; curl -s http://127.0.0.1:43142/spend/calculate -H 'Authorization: Bearer sk-lit6995-repro' -H 'Content-Type: application/json' -d "{\"completion_response\":{\"model\":\"vercel_ai_gateway/alibaba/qwen3-coder-plus\",\"choices\":[{\"index\":0,\"finish_reason\":\"stop\",\"message\":{\"role\":\"assistant\",\"content\":\"ok\"}}],\"usage\":{\"prompt_tokens\":$n,\"completion_tokens\":1000,\"total_tokens\":$((n+1000))}}}" | jq -c '.cost // .error.message'; doneinput_cost_per_token1e-06 with*_above_32k_tokens1.8e-06,*_above_128k_tokens3e-06 and*_above_256k_tokens6e-06, and output 5e-06 / 9e-06 / 1.5e-05 / 6e-05; the cost calculator prices the whole request at the highest tier the prompt crosses, which is what Alibaba bills):Chat completion
usage.cost, which depends on the upstream that served the request):Type
🆕 New Feature
🚄 Infrastructure
✅ Test
Caveats (if any)
High
gh workflow run cost-map-sync.yml404s until this merges, and the threeCOST_MAP_BOT_*secrets and the slug variable are unset; the first real execution is the scheduled tick on staging after merge, on the path that prints why it cannot open a PRcost-map-guardruns onpull_request_target, which takes the default branch's copy of the workflow, so no PR has had it report yet (this PR's tip got onlypull_requestruns); the first run is on the first PR opened after feat(ci): add the cost map guard check #39835 merges, and the ticket lists the demo PRs that exercise itactionlint; the first real proof is a dry-run dispatch on staging after this merges, listed on the ticketMedium
COST_MAP_BOT_APP_IDandCOST_MAP_BOT_PRIVATE_KEY, and its slug as the repository variableCOST_MAP_BOT_APP_SLUGguard-internal-staginginto a ruleset with no bypass actor and addcost-map-guardto them; add the app toguard-internal-staging,Protect Sensitive Files, andProtect dot directoriesas a bypass actor in "pull requests only" modemain-mergeoncemainis the default branch againguard-internal-stagingrequires code owner review, so that approval has to come from the map's code owneropenrouter/*orvercel_ai_gateway/*price is overwritten by the next tickvercel_ai_gateway/*entry markedprice_varies_by_providerfollows the catalog's headline price; a correction belongs in a non-synced key, in the hold rules, or in dropping that mark, and the 10x hold is the only thing that keeps a catalog value outmainlags the default branch untilmainis the default branch againmainat boot, so they see a sync at the next promotion--diff-algorithm=patience), no entry removed and the key order keptusage.costLow
openrouter/*orvercel_ai_gateway/*rows whosemax_output_tokenswas filled frommax_input_tokens; 11 take the gateway's ceiling andopenrouter/qwen/qwen3-235b-a22b-2507(262144 against 16384) is held; a model that can really emit its whole context window gets the gateway's own ceiling instead, which is what that route enforces; a ceiling more than 10x below the copied cap is held like any other shrink, so a catalog glitch still gets a humanmin: 272000, 53 of the 134 tier lists) is off by one token at the boundaryabove_272kis exclusive, so exactly 272,000 prompt tokens bills the base tiergpt-5.1-codex-maxtogpt-5.1-codex)varies_by_providerthat a human priced never gets new tiers, and held warnings never clearproxy-infra / Run tests (Python 3.10)is red at the tip, inherited from the base branchtest_http_parsing_utils.py::TestNumericFormFields::test_qualifiers_and_optionality_are_unwrappedfails the same way on feat(ci): add the cost map guard check #39835's tip 61bed79: both branches predate fix(proxy): strip every TypedDict qualifier before numeric form-field detection #39780 (merged to staging 2026-09-05 01:36Z; staging's Unit Tests run 33956401452 is green since); the required context is the aggregateproxy-infra / Run tests, which is green, and this clears when this PR retargets onto staginglitellm_cost_map_sync_the guard keys onFinal Attestation
The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
5cc9690 passes /live-pr-risk
f41b19a passes /live-pr-risk
a13daf7 passes /live-pr-risk
9478a32 passes /live-pr-risk
26f74e6 passes /live-pr-risk
340569b passes /live-pr-risk
b2402f8 passes /live-pr-risk
d3ff59f passes /live-pr-risk
5ad768d passes /live-pr-risk
9c1c0a2 passes /live-pr-risk
81142d4 passes /live-pr-risk
412db8d passes /live-pr-risk
fb8f9af passes /live-pr-risk
84b7f25 passes /live-pr-risk