feat: add single-model pricing endpoint and containing-match fallback - #65
Conversation
|
Warning Review limit reached
Next review available in: 43 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (5)
📝 WalkthroughSummary by CodeRabbit
WalkthroughThe PR adds model-specific pricing resolution, cost-match precedence rules, provider multipliers, and a ChangesPricing resolution flow
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant ViteApiProxy
participant PricingAPI
participant CostResolver
Client->>ViteApiProxy: Request /pricing/{model}
ViteApiProxy->>PricingAPI: Forward pricing request
PricingAPI->>CostResolver: Resolve configured and remote costs
CostResolver-->>PricingAPI: Match metadata or unresolved result
PricingAPI-->>ViteApiProxy: Pricing response
ViteApiProxy-->>Client: Return pricing data
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/api.py (1)
947-1011: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the provider-multiplier lookup into a shared helper.
get_model_pricing(lines 970-974) re-implements the same provider-multiplier resolution already present inget_pricing(lines 921-927): readconfig_snapshot["providers"][provider], then extractprice_multiplierwith anisinstanceguard. Both endpoints compute the same value with slightly different code shapes.Extract a small helper, for example
_resolve_provider_multiplier(config_snapshot, provider) -> float, and call it from both endpoints. This keeps the multiplier logic in one place and prevents the two pricing endpoints from silently diverging if this logic changes later.♻️ Proposed refactor
+def _resolve_provider_multiplier(config_snapshot: dict, provider: str | None) -> float: + if provider is None: + return 1.0 + provider_config = config_snapshot.get("providers", {}).get(provider, {}) + if not isinstance(provider_config, dict): + return 1.0 + return float(provider_config.get("price_multiplier", 1.0)) + + `@app.get`("/pricing/{model:path}") async def get_model_pricing(model: str, provider: str | None = None): ... - multiplier = 1.0 - if provider is not None: - provider_config = config_snapshot.get("providers", {}).get(provider, {}) - if isinstance(provider_config, dict): - multiplier = float(provider_config.get("price_multiplier", 1.0)) + multiplier = _resolve_provider_multiplier(config_snapshot, provider)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/api.py` around lines 947 - 1011, Extract the duplicated provider multiplier lookup into a shared _resolve_provider_multiplier(config_snapshot, provider) helper, preserving the existing provider dictionary and isinstance guard with a default multiplier of 1.0. Replace the local multiplier logic in both get_pricing and get_model_pricing with calls to this helper.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/costs.py`:
- Around line 41-53: Update _find_containing and the resolve_model_cost fallback
path to avoid scanning every pricing-map entry on each lookup. Build or reuse an
index keyed by each key’s trailing model segment, preserving exact-match
precedence and selecting the lowest-cost matching vendor entry; apply the same
indexed lookup to both provider and global maps.
---
Nitpick comments:
In `@src/api.py`:
- Around line 947-1011: Extract the duplicated provider multiplier lookup into a
shared _resolve_provider_multiplier(config_snapshot, provider) helper,
preserving the existing provider dictionary and isinstance guard with a default
multiplier of 1.0. Replace the local multiplier logic in both get_pricing and
get_model_pricing with calls to this helper.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 27090c83-9c66-4801-8c08-02442dc6f834
📒 Files selected for processing (9)
VERSIONconfig.example.yamlconfig/pricing.pyfrontend/tests/vite-api-proxy-routes-regression.test.mjsfrontend/vite-api-proxy.jssrc/api.pysrc/costs.pytests/test_costs.pytests/test_pricing.py
Summary
This PR changes high-risk area(s): cost/token accounting and provider/model normalization.
GET /pricing/{model:path}to look up resolved pricing for a single model, mirroring the resolution used at record time.resolve_model_costintoresolve_cost_match, adding a containing-name fallback:mimo-v2.5-proresolves to LiteLLM'sopenrouter/xiaomi/mimo-v2.5-pro. On multiple containing matches, the cheapest combined rate wins.responses-mode pricing entries so GPT Pro/Codex models resolve from the catalog.config.example.yaml(covered by LiteLLM)./pricing/to the Vite dev proxy.Why / Context
Manual pricing config listed many models LiteLLM already prices, and LiteLLM prefixes many models with vendor names (e.g.
openrouter/xiaomi/mimo-v2.5-pro), so exact name matching missed them. Users need a per-model pricing lookup that matches what billing actually uses.How It Works
src/costs.py::resolve_cost_matchpriority: provider exact → global exact → provider containing (cheapest) → global containing (cheapest). Containing matches compare only the last path segment (key.rsplit("/",1)[-1] == model) to avoid family/variant collisions (gpt-5vsgpt-5-mini).GET /pricing/{model:path}returnsmodel(the matched key),resolved, base + effective rates,source(litellm/yaml),scope(globalor provider name),multiplier; orresolved: falsewith zero rates when nothing matches. Optionalprovider=query applies that provider's overrides/multiplier.Design Decisions
Why: requested behavior.
Trade-off: a bare model name with no exact price now bills at the cheapest matching vendor's price instead of
$0(previously silent). This is an estimate heuristic, not per-request token weighting.Manual QA
GET /pricing/mimo-v2.5-pro→model: openrouter/xiaomi/mimo-v2.5-pro, $1.0/$3.0/$0.2GET /pricing/mimo-v2.5→model: openrouter/xiaomi/mimo-v2.5, $0.4/$2.0/$0.08GET /pricing/z-ai/glm-5.1-20260406→ exact yaml overrideGET /pricing/unknown-model→resolved: false, zero rates/pricing/(empty) → 422Testing
uv run python -m pytest -q: pass — 669 passeduv run ruff format --check+ruff check: passuv run python -m mypy src/: passpre-commit run --files <touched files>: pass (includes full pytest hook)cd frontend && node --test tests/vite-api-proxy-routes-regression.test.mjs: passcd frontend && npm test: 45 pre-existing failures unrelated to this change (confirmed identical with the proxy change stashed)Risk / Rollout / Rollback
$0to cheapest containing vendor). Exact matches and all existing precedence behavior unchanged.resolve_model_costbehavior restored.Data / Privacy Impact
Cost / Provider / Schema Impact
responsesmode acceptanceReview
match_typefield, added global-exact-beats-provider-containing test)AGENTS.md,.agents/commands/llm-tracker.md, and.agents/commands/pre-pr.md: yesKnown Limitations / Follow-ups