Skip to content

feat(ci): add the cost map sync bot for openrouter and vercel_ai_gateway - #39845

Closed
mateo-berri wants to merge 16 commits into
mainfrom
litellm_cost_map_sync_bot
Closed

mateo-berri wants to merge 16 commits into
mainfrom
litellm_cost_map_sync_bot

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • OpenRouter and Vercel AI Gateway ship new models weekly; the map lags by weeks
  • Stale entries carry old prices, context windows, and capability flags
  • The weekly LLM-based updater has failed every run since August 2

How it solves it:

  • scripts/sync_cost_map.py diffs both public catalogs into the map
    • adds and reprices, never removes; a new entry inherits its family's curated traits
    • holds back shrinking limits, prices crossing zero or moving more than 10x, per-provider prices on curated rows, and capability flags curated as false for a human; a curated output cap equal to the entry's own context window is a copy of that window, so the catalog's real ceiling replaces it unless that shrinks it more than 10x
  • cost-map-sync.yml runs it every 5 minutes as the GitHub App and opens a litellm_cost_map_sync_* PR
    • a later tick merges it once cost-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 human
    • a green PR the app cannot merge yet gets auto-merge armed, so one approval lands it and the run stays green; a bot PR still open after a day fails every tick so the stall is visible
    • a tick whose catalogs, map, schema, and sync script match the last no-op sync skips the install and the script
    • the PR body lists every held change and at most 30 added or updated lines per provider (the diff has the rest), and caps the warnings too only when the body would pass GitHub's 65k limit; the first sync's body is 18k chars
    • the workflow log carries the uncapped report
  • Retires auto_update_price_and_context_window.yml and its script
  • Renames the retired validate-model-prices-json check to cost-map-guard in the declared_reasoning_efforts docstring
  • Adds the *_above_32k_tokens keys the qwen3 tiers need to the hardcoded map schema in test_utils.py
  • Lets guard-main-branch accept a litellm_cost_map_sync_* head opened by the sync App (vars.COST_MAP_BOT_APP_SLUG), so the bot keeps merging once main is the default branch again
  • Unpins the exact OpenRouter prices and limits in test_get_model_cost_map.py, test_cost_calculator.py, and test_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_tokens breakpoint the catalogs use

User 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

  1. The admin adds openrouter/inception/mercury-2.5-preview and openrouter/deepseek/deepseek-v4-pro-0813 to their config and boots the proxy
  2. GET https://litellm-domain/model/info returns mercury-2.5 with max_input_tokens: null, input_cost_per_token: 0, and no supports_* flags, and deepseek-v4-pro at $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/M
  3. POST https://litellm-domain/v1/chat/completions to either model returns 200 with x-litellm-response-cost set from OpenRouter's own usage cost, so spend still tracks, but context-window routing and capability checks treat mercury-2.5 as unknown and the model hub shows it with no limits
  4. The admin waits for a hand-made cost map PR; the weekly bot at https://github.com/BerriAI/litellm/actions/workflows/auto_update_price_and_context_window.yml has been red on every scheduled run since August 2

After: the map on the default branch catches up within minutes of the catalog, with no human in the loop

  1. The admin adds the same two models to their config and boots a proxy on a build that includes the merged sync PR (or one that pulls the map from GitHub at boot)
  2. GET https://litellm-domain/model/info returns mercury-2.5 with max_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, and deepseek-v4-pro at $1.12/M input and $3.36/M output
  3. POST https://litellm-domain/v1/chat/completions to 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 one
  4. The admin can see how the map got there: https://github.com/BerriAI/litellm/pulls?q=head%3Alitellm_cost_map_sync_ lists the bot PR, its body names every model added or repriced per provider, and its cost-map-guard check is green

Design

Two providers, both with public machine-readable catalogs: GET https://openrouter.ai/api/v1/models and GET 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 turns supported_parameters and input modalities into the supports_* flags. Vercel's long-context tiers become litellm's *_above_<N>k_tokens keys 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 from image_output and audio_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's pricing.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, and supports_prompt_caching is not set from a cache price alone because the map pairs it with a per-model prompt_cache_min_tokens the catalogs do not carry (a whole-map unit test enforces that pairing for the Claude entries). Vercel rows map language to mode: chat and embedding to mode: embedding; image, video, speech, transcription, realtime, and reranking rows are skipped and counted in the PR body, as are rows whose deprecated_at date has passed (a scheduled deprecation keeps syncing until the date), router rows priced -1, and rows with no usable price

The 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 false is held for a human, a curated max_tokens / max_output_tokens pair moves as a unit to the catalog's output ceiling (a legacy entry with only max_tokens gains max_output_tokens at the same value, which keeps test_max_tokens_consistency green across the whole map; a curated output cap equal to the entry's own max_input_tokens is a copy of the context window rather than a ceiling, 12 entries on today's catalogs such as openrouter/deepseek/deepseek-v3.2 at 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-2507 at 262144 against a 16384 ceiling), a mode mismatch (the map says chat, the catalog says embedding) 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 flagged varies_by_provider once 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 as source, and one seeded at a varies_by_provider headline is marked price_varies_by_provider: true and keeps following the catalog while the mark is there (the schema generator in ci_cd/generate_model_prices_schema.py knows 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 (source is never read as provenance: vercel_ai_gateway/zai/glm-4.6 cites its catalog page as source and 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-codex takes supports_system_messages: false from gpt-5-codex, not true from gpt-5) or else the longest same-mode dash prefix (prompt_cache_min_tokens, supports_adaptive_thinking, thinking_always_on, supports_sampling_params, and supports_system_messages; every other supports_* flag comes from the catalog), so openrouter/anthropic/claude-fable-5:batch gets 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 the litellm/ 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-2507 262144 to 131072, and genuine output caps such as vercel_ai_gateway/anthropic/claude-sonnet-4 64000 to 8192), one supports_reasoning curated as false, and 4 embedding rows curated as chat

OpenRouter reports the billed cost in usage.cost and the proxy already prefers it for x-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 source

The 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 from COST_MAP_BOT_APP_ID and COST_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> plus isCrossRepository == false), so a fork PR carrying the sync title and branch prefix is never closed or merged with the App token. There is no github.token fallback on purpose: a PR opened with the workflow's own token never triggers pull_request workflows, so cost-map-guard could not run on it. Without those secrets a scheduled run explains that it cannot open a PR and stops, and the dry_run input runs the script and prints the report without opening anything. An app is needed because PRs created with github.token trigger 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 whose cost-map-guard and 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 day

The app needs to bypass review, never checks: the owner steps move the required status checks out of guard-internal-staging into 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 Files keeps two approvals on any change to the workflow itself. guard-main-branch accepts a litellm_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 once main is the default branch again (where main-merge needs the same bypass and cost-map-guard has to be required) and neither a person nor another installed bot can borrow the prefix to route a change past staging

The 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 an openrouter/* or vercel_ai_gateway/* entry should do the same. The map schema in test_utils.py listed every tier breakpoint by hand, so it now takes any *_above_<N>k_tokens key 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 test

Relevant issues

Linear ticket

Resolves LIT-6995

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to 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)

model_list:
  - model_name: mercury-2.5
    litellm_params:
      model: openrouter/inception/mercury-2.5-preview
      api_key: os.environ/OPENROUTER_API_KEY
  - model_name: deepseek-v4-pro
    litellm_params:
      model: openrouter/deepseek/deepseek-v4-pro-0813
      api_key: os.environ/OPENROUTER_API_KEY
  - model_name: claude-sonnet-4.5-vercel
    litellm_params:
      model: vercel_ai_gateway/anthropic/claude-sonnet-4.5
      api_key: model-info-only
  - model_name: claude-fable-5.1-vercel
    litellm_params:
      model: vercel_ai_gateway/anthropic/claude-fable-5.1
      api_key: model-info-only
general_settings:
  master_key: sk-lit6995-repro

Both legs boot litellm/proxy/proxy_cli.py --config <the yaml above> --num_workers 2 from 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 with LITELLM_LOCAL_MODEL_COST_MAP=True on the map that python scripts/sync_cost_map.py --write produced from the live catalogs

Before (61bed79)

Sync against the live catalogs

  1. ls scripts/sync_cost_map.py .github/workflows/cost-map-sync.yml
  2. No such file or directory for both; the only updater is the weekly workflow, whose scheduled runs since August 2 are all failure (gh run list --workflow auto_update_price_and_context_window.yml --limit 6)

Whole-map unit tests

  1. 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 4
  2. Output: 1 failed, 1479 passed, the one failure being test_vertex_claude_completion_does_not_mutate_shared_extra_headers with ModuleNotFoundError: No module named 'vertexai' (a missing optional dependency in the worktree)

Model info for a new and a stale OpenRouter model

  1. 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}'
  2. Output:
    {"name":"mercury-2.5","input":0,"output":0,"max_in":null,"max_out":null,"tools":null,"reasoning":null}
    {"name":"deepseek-v4-pro","input":0.00000132,"output":0.00000396,"max_in":1048576,"max_out":384000,"tools":true,"reasoning":true}
    

Spend calculation for a three-tier model

  1. 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'; done
  2. Output (the committed map has no entry for vercel_ai_gateway/alibaba/qwen3-coder-plus, so the proxy cannot price it at any prompt size):
    prompt_tokens=20000 -> "This model isn't mapped yet. model=vercel_ai_gateway/alibaba/qwen3-coder-plus, custom_llm_provider=vercel_ai_gateway. Add it here - https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json"
    prompt_tokens=100000 -> (same)
    prompt_tokens=200000 -> (same)
    prompt_tokens=300000 -> (same)
    

Chat completion

  1. 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'; done
  2. Output (the cost header is OpenRouter's own usage.cost, so it is set even for the unmapped model):
    HTTP/1.1 200 OK
    x-litellm-response-cost: 2.53e-06
    HTTP/1.1 200 OK
    x-litellm-response-cost: 5.412e-05
    

After (84b7f25)

The leg first ran at 340569b. b2402f8, d3ff59f, 5ad768d, and 9c1c0a2 only change .github/workflows/guard-main-branch.yml and .github/workflows/cost-map-sync.yml, and 81142d4 only widens the map schema in tests/test_litellm/test_utils.py, so no proxy code path read them. 412db8d changes the sync script's hold and inheritance rules, fb8f9af adds the price_varies_by_provider mark and the 10x floor on copied caps, and 84b7f25 teaches the schema generator the mark after the leg at fb8f9af failed its guard step on Unclassified 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 84b7f25

Sync against the live catalogs

  1. python scripts/sync_cost_map.py --write --pr-body-file /tmp/body.md && python ci_cd/generate_model_prices_schema.py && git diff --stat
  2. Output:
    openrouter: added=180 updated=128 warnings=10 vercel_ai_gateway: added=211 updated=38 warnings=16
    wrote model_prices_and_context_window.schema.json
    litellm/model_prices_and_context_window_backup.json | 34597 +++++++++++--------
    model_prices_and_context_window.json                | 34597 +++++++++++--------
    model_prices_and_context_window.schema.json         |    23 +
    
    The body written to /tmp/body.md is 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 as chat: 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 as openrouter/deepseek/deepseek-v3.2 at 163840, now land as updates, and one, openrouter/qwen/qwen3-235b-a22b-2507 at 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.6 among them now that source no 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 as false (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)
  3. 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 $?"
  4. Output (the bot's own first PR passes the guard's full bot contract):
    cost map guard passed (bot contract enforced)
    guard exit 0
    

Whole-map unit tests

  1. 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 4 with the synced map and schema in place: 85 files, every test that reads the map
  2. Output at 84b7f25: 1 failed, 3713 passed, 16 skipped, the failure being the pre-existing vertexai import error from Before. At 340569b the same sweep gave 2 failed, 3708 passed, 16 skipped, the other failure being test_aaamodel_prices_and_context_window_json_is_valid, whose hardcoded schema lacked the *_above_32k_tokens keys the qwen3 tiers add (81142d4 adds them and fb8f9af adds price_varies_by_provider, so the test passes on both the synced and the committed map). The same sweep before the dash-prefix root lookup caught vercel_ai_gateway/anthropic/claude-opus-5-fast failing test_opus_5_all_variants_carry_512_token_cache_minimum, which is why a variant now inherits from its family root

Model info for a new and a stale OpenRouter model, a tiered and a new Vercel AI Gateway model

  1. Same curl against the After proxy on port 43142, with the jq extended by above_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_on
  2. Output (claude-sonnet-4.5 is a curated entry that gained its 200k tier, claude-fable-5.1 is a new entry that inherited the family's cache minimum and thinking traits):
    {"name":"mercury-2.5","input":4E-8,"output":1.5E-7,"max_in":260000,"max_out":65536,"tools":true,"reasoning":true,"above_200k":null,"cache_min":null,"adaptive":null,"thinking_on":null}
    {"name":"deepseek-v4-pro","input":0.00000112068,"output":0.00000336204,"max_in":1048576,"max_out":384000,"tools":true,"reasoning":true,"above_200k":null,"cache_min":null,"adaptive":null,"thinking_on":null}
    {"name":"claude-sonnet-4.5-vercel","input":0.000003,"output":0.000015,"max_in":1000000,"max_out":64000,"tools":true,"reasoning":true,"above_200k":0.000006,"cache_min":1024,"adaptive":null,"thinking_on":null}
    {"name":"claude-fable-5.1-vercel","input":0.00001,"output":0.00005,"max_in":1000000,"max_out":128000,"tools":true,"reasoning":true,"above_200k":null,"cache_min":512,"adaptive":true,"thinking_on":true}
    

Spend calculation for a three-tier model

  1. 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'; done
  2. Output (the synced entry carries input_cost_per_token 1e-06 with *_above_32k_tokens 1.8e-06, *_above_128k_tokens 3e-06 and *_above_256k_tokens 6e-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):
    prompt_tokens=20000 -> 0.025
    prompt_tokens=100000 -> 0.189
    prompt_tokens=200000 -> 0.615
    prompt_tokens=300000 -> 1.86
    

Chat completion

  1. Same loop against port 43142
  2. Output (the cost header stays OpenRouter's own usage.cost, which depends on the upstream that served the request):
    HTTP/1.1 200 OK
    x-litellm-response-cost: 2.53e-06
    HTTP/1.1 200 OK
    x-litellm-response-cost: 6.864e-05
    

Type

🆕 New Feature
🚄 Infrastructure
✅ Test

Caveats (if any)

High

  • The bot itself has never run anywhere; only the script is proven
    • the workflow only exists off the default branch, so gh workflow run cost-map-sync.yml 404s until this merges, and the three COST_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 PR
    • cost-map-guard runs on pull_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 only pull_request runs); 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 it
    • the reconcile logic was driven by hand against feat(ci): add the cost map sync bot for openrouter and vercel_ai_gateway #39845 (a base with no required checks falls back to every check and reports the inherited py3.10 red), the rest is checked by reading and actionlint; the first real proof is a dry-run dispatch on staging after this merges, listed on the ticket

Medium

  • Fully automatic merging needs admin-only steps after this lands
    • create and install a GitHub App with contents and pull requests write on this repo, store its id and private key as COST_MAP_BOT_APP_ID and COST_MAP_BOT_PRIVATE_KEY, and its slug as the repository variable COST_MAP_BOT_APP_SLUG
    • move the required status checks from guard-internal-staging into a ruleset with no bypass actor and add cost-map-guard to them; add the app to guard-internal-staging, Protect Sensitive Files, and Protect dot directories as a bypass actor in "pull requests only" mode
    • the same two steps on main-merge once main is the default branch again
    • until the secrets exist a scheduled run prints why it cannot open a PR; until the bypass exists a green bot PR gets auto-merge armed and one approval lands it, and guard-internal-staging requires code owner review, so that approval has to come from the map's code owner
  • A bot PR turned red by a required check stays open and pauses syncing
    • by design: the tick warns with the PR number, and once the PR is a day old every tick fails so someone sees it; a human merges or closes it, and the open PR is never refreshed, so later catalog changes wait behind it
    • the tests that pinned synced prices are unpinned here; a future test that pins one brings this back
  • A hand edit to an openrouter/* or vercel_ai_gateway/* price is overwritten by the next tick
    • the catalogs own those two providers' prices and limits, and a vercel_ai_gateway/* entry marked price_varies_by_provider follows 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 out
  • The map on main lags the default branch until main is the default branch again
    • the bot syncs the branch it runs on; proxies pull the map from main at boot, so they see a sync at the next promotion
  • The first bot PR is big: 391 models added, 166 repriced or relimited, 26 held changes listed for a human
    • the map is months behind both catalogs; later PRs are a few entries
    • GitHub's default diff shows it as tens of thousands of changed lines per map file; the real change is additions and in-place value changes (--diff-algorithm=patience), no entry removed and the key order kept
    • the held changes repeat on every bot PR until a human commits them
  • OpenRouter's catalog price is the cheapest routed provider's, not what a request pays
    • the response cost header keeps coming from OpenRouter's usage.cost
    • so this changes model info and fallback pricing for OpenRouter, and tracked spend for Vercel AI Gateway

Low

  • A catalog price that moves less than 10x lands with no human in the loop
    • the map only mirrors what each gateway publishes for its own routes, and a gateway bills the price it publishes; the 10x hold catches a decimal slip
  • A curated output cap that happens to equal the context window is read as a copy of it and yields to the catalog
    • 12 entries on today's catalogs, all openrouter/* or vercel_ai_gateway/* rows whose max_output_tokens was filled from max_input_tokens; 11 take the gateway's ceiling and openrouter/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 human
  • A Vercel tier that starts on a round thousand (min: 272000, 53 of the 134 tier lists) is off by one token at the boundary
    • litellm's above_272k is exclusive, so exactly 272,000 prompt tokens bills the base tier
  • Trait inheritance is five keys, and a new entry with no exact-name root takes them from its longest same-mode dash prefix (gpt-5.1-codex-max to gpt-5.1-codex)
    • the inherited traits are narrow, so a wrong prefix costs a cache minimum or a thinking flag, never a price or a limit
  • The 5-minute cron is the Actions minimum: a no-op tick costs about 20 seconds of runner time, and a bot PR open for more than a day fails all 288 daily ticks
    • the install and the script only run when a catalog, the map, its schema, or the sync script changed since the last no-op sync
    • failing every tick is what makes a stall impossible to miss; an hourly cron trades the freshness that is the point, failing only once would need state between ticks, and every bot PR runs the full required-check set on purpose
  • A Vercel row marked varies_by_provider that a human priced never gets new tiers, and held warnings never clear
    • the hold fires before the script looks at whether the map had a value at all (2 rows today), and all 26 held changes are listed again on every sync until a human commits or drops them
  • A catalog day with hundreds of held changes caps the warnings section at 30 lines like the others
    • only when listing them all would push the body past GitHub's 65,536-char limit; the workflow log still carries every line
  • proxy-infra / Run tests (Python 3.10) is red at the tip, inherited from the base branch
  • Nothing else references the deleted workflow or script
    • checked the repo, the Makefile, the other workflows, and the docs checkout
    • the legacy CircleCI suites reference OpenRouter models without pinning a price, so a repricing cannot turn them red
    • the bot branch prefix is the same litellm_cost_map_sync_ the guard keys on

Final 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

@greptile-apps

greptile-apps Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR replaces the retired weekly model-price updater with a guarded cost-map synchronization workflow for OpenRouter and Vercel AI Gateway.

  • Adds catalog parsing, normalization, inheritance, safety holds, reporting, and synchronized map serialization.
  • Adds a GitHub App workflow that reconciles, validates, and merges generated synchronization PRs.
  • Extends schema generation for bot-owned variable-provider pricing and updates tests for synchronized catalog values.
  • Restricts the main-branch exception to same-repository synchronization PRs authored by the configured App.

Confidence Score: 5/5

The 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.

Important Files Changed

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

Comment thread scripts/sync_cost_map.py Resolved
Comment thread scripts/sync_cost_map.py Resolved
Comment thread scripts/sync_cost_map.py Resolved
@codecov

codecov Bot commented Sep 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri mateo-berri mentioned this pull request Sep 5, 2026
7 tasks done
@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Create PR

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.

Comment thread scripts/sync_cost_map.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment thread scripts/sync_cost_map.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous 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.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment thread .github/workflows/cost-map-sync.yml Resolved
Comment thread .github/workflows/cost-map-sync.yml Resolved
Comment thread .github/workflows/cost-map-sync.yml Resolved
@veria-ai

veria-ai Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

This 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.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Create PR

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.

Comment thread scripts/sync_cost_map.py Resolved
…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
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous 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.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both catalogs are the gateways' own published prices over HTTPS, and each gateway bills what it publishes. The 10x hold catches slips, by design.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread scripts/sync_cost_map.py Resolved
Comment thread scripts/sync_cost_map.py Resolved

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

…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.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

Comment thread scripts/sync_cost_map.py
"litellm_provider": entry.provider,
"mode": entry.mode,
"source": entry.source,
**({"price_varies_by_provider": True} if entry.indicative_prices else {}),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 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.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Create PR

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.

Comment thread scripts/sync_cost_map.py Resolved
… 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.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants