Skip to content

feat(ratio-sync): add create_cache_ratio support for upstream sync - #4375

Closed
RedwindA wants to merge 2 commits into
QuantumNous:mainfrom
RedwindA:feat/syncCacheCreateRatio
Closed

RedwindA wants to merge 2 commits into
QuantumNous:mainfrom
RedwindA:feat/syncCacheCreateRatio

Conversation

@RedwindA

@RedwindA RedwindA commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

📝 变更描述 / Description

本次 PR 为上游倍率同步功能增加了对 create_cache_ratio(缓存创建倍率) 的支持。

变更内容:

  1. 后端 (controller/ratio_sync.go):

    • 将 create_cache_ratio 添加到支持的 ratioTypes 列表中
    • 针对 OpenRouter 数据源:解析 InputCacheWrite 定价字段,转换为 create_cache_ratio
    • 针对 models.dev 数据源:新增 CacheWrite 字段到 cost/candidate 结构体,在价格候选者选择时优先选择包含更完整缓存元数据的候选者
    • 为两个上游数据源添加 createCacheRatioMap 转换逻辑
  2. 前端 (web/src/pages/Setting/Ratio/UpstreamRatioSync.jsx):

    • 在同步逻辑中处理 CreateCacheRatio 字段
    • 在 UI 选择器中新增 "缓存创建倍率" 选项
    • 在模型冲突检测和清理逻辑中包含 CreateCacheRatio

技术实现说明:

  • 缓存创建倍率的计算逻辑与其他倍率一致:cache_write_price / prompt_price
  • models.dev 候选者选择算法现在会优先考虑包含 cache_read 和 cache_write 元数据的候选者(优先于仅包含基础价格的候选者),以确保获取权威的缓存定价数据

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)
  • ✨ 新功能 (New feature)
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

(请在此粘贴截图、关键日志或测试报告,以证明变更生效)

  • new-api
c1ed49bf-024b-4e34-941a-be47893c198d - models.dev dda01a1d-4995-4c11-b58c-2625a417c174 - OpenRouter fcb4a82d9bb77206777d454775fad61e

备注:新版前端合并后需要移植

Summary by CodeRabbit

Release Notes

  • New Features
    • Added cache creation ratio configuration in upstream ratio sync settings
    • Enhanced upstream provider integration to process cache write pricing information
    • Improved model candidate selection logic with better tie-breaking based on cache metadata availability

Add support for syncing cache creation ratios from OpenRouter and models.dev:
- Add "create_cache_ratio" to ratioTypes list in controller
- Parse InputCacheWrite from OpenRouter pricing data and convert to create_cache_ratio
- Add CacheWrite field to models.dev cost/candidate structs
- Prefer candidates with richer cache metadata in models.dev selection
- Add createCacheRatioMap for both upstream sources
- Update frontend to handle CreateCacheRatio in sync operations
- Add "缓存创建倍率" (Cache Create Ratio) option in UI

This enables proper pricing for cache write operations when syncing from upstream providers.
@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a new ratio key create_cache_ratio across backend ratio-sync logic and frontend settings UI: parses cache-write pricing from OpenRouter and models.dev, computes and emits the ratio, updates candidate selection, and surfaces the ratio in the Upstream Ratio Sync UI.

Changes

Cohort / File(s) Summary
Backend — Ratio sync & converters
controller/ratio_sync.go
Added create_cache_ratio to ratioTypes; parse pricing.input_cache_write from OpenRouter and compute create_cache_ratio (rounded); emit in converted ratio maps.
Backend — models.dev parsing & candidate logic
.../models_dev.go (parsing structs and buildModelsDevCandidate), .../convert_models_dev.go
Added CacheWrite *float64 to models.dev parse structs with non-negative validation; compute create_cache_ratio = cache_write / input when present; tie-breaker updated to prefer candidates with richer cache metadata.
Frontend — Settings UI
web/src/pages/Setting/Ratio/UpstreamRatioSync.jsx
Plumbed create_cache_ratio into options, ratio-type filtering, label/tag rendering (缓存创建倍率), merging/delete-on-price-switch logic, and conflict detection in the upstream sync UI.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Poem

🐰 I nibbled code beneath the moon,
Cache-write whispers found their tune.
Ratios bloom from bytes and price,
Syncing now — how very nice! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: adding support for create_cache_ratio (cache creation ratio) in the upstream synchronization feature.
Linked Issues check ✅ Passed The PR fully addresses the requirements from issue #2679 by implementing cache price ratio synchronization, displaying cache ratios on the UI, and extending sync interfaces.
Out of Scope Changes check ✅ Passed All changes are directly related to adding create_cache_ratio support for upstream sync; no unrelated modifications were detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai 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.

🧹 Nitpick comments (2)
controller/ratio_sync.go (1)

822-832: Update the docstring to mention create_cache_ratio.

The function comment enumerates the ratio outputs (model_ratio, completion_ratio, cache_ratio) but now create_cache_ratio = cache_write / input_cost is also emitted. Minor, but keeps the contract accurate for future maintainers.

📝 Proposed doc update
 //	model_ratio = input_cost_per_1M / 2
 //	completion_ratio = output_cost / input_cost
 //	cache_ratio = cache_read_cost / input_cost
+//	create_cache_ratio = cache_write_cost / input_cost
 //
 // Duplicate model keys across providers are resolved by selecting the
 // cheapest non-zero input cost. If only zero-priced candidates exist,
 // a zero ratio is kept.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@controller/ratio_sync.go` around lines 822 - 832, Update the docstring for
convertModelsDevToRatioData to include the new emitted ratio create_cache_ratio
and its formula; currently the comment lists model_ratio, completion_ratio, and
cache_ratio but omits create_cache_ratio, so add a line like "create_cache_ratio
= cache_write_cost / input_cost" (referencing create_cache_ratio) and ensure the
docstring clearly lists all four outputs and their formulas to keep the contract
accurate.
web/src/pages/Setting/Ratio/UpstreamRatioSync.jsx (1)

328-340: Conflict description doesn't cover cache_ratio/create_cache_ratio-only locals.

getLocalBillingCategory (Line 302-312) now returns 'ratio' when a model only has CacheRatio or CreateCacheRatio set locally, but the currentDesc/newDesc builder below only renders 模型倍率/补全倍率. In that edge case, the conflict modal will show 模型倍率 : -, 补全倍率 : - even though a real cache-related local value exists, which is confusing.

Pre-existing issue for CacheRatio, now broadened. Consider extending the description to include 缓存倍率 and 缓存创建倍率 when present (both for currentDesc and the newCat === 'ratio' branch of newDesc).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/pages/Setting/Ratio/UpstreamRatioSync.jsx` around lines 328 - 340,
The conflict description misses cache-only locals: update the builders that
produce currentDesc and newDesc to include cache fields when
getLocalBillingCategory returns 'ratio' for cache-only models; specifically, in
the currentDesc and the newCat === 'ratio' branch of newDesc, append display
lines for CacheRatio (缓存倍率) and CreateCacheRatio (缓存创建倍率) using values from
currentRatios (e.g., currentRatios.CacheRatio[model],
currentRatios.CreateCacheRatio[model]) and from ratios (e.g.,
ratios['cache_ratio'], ratios['create_cache_ratio']), falling back to '-' when
undefined, so the modal shows these cache values instead of empty dashes in
cache-only cases.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@controller/ratio_sync.go`:
- Around line 822-832: Update the docstring for convertModelsDevToRatioData to
include the new emitted ratio create_cache_ratio and its formula; currently the
comment lists model_ratio, completion_ratio, and cache_ratio but omits
create_cache_ratio, so add a line like "create_cache_ratio = cache_write_cost /
input_cost" (referencing create_cache_ratio) and ensure the docstring clearly
lists all four outputs and their formulas to keep the contract accurate.

In `@web/src/pages/Setting/Ratio/UpstreamRatioSync.jsx`:
- Around line 328-340: The conflict description misses cache-only locals: update
the builders that produce currentDesc and newDesc to include cache fields when
getLocalBillingCategory returns 'ratio' for cache-only models; specifically, in
the currentDesc and the newCat === 'ratio' branch of newDesc, append display
lines for CacheRatio (缓存倍率) and CreateCacheRatio (缓存创建倍率) using values from
currentRatios (e.g., currentRatios.CacheRatio[model],
currentRatios.CreateCacheRatio[model]) and from ratios (e.g.,
ratios['cache_ratio'], ratios['create_cache_ratio']), falling back to '-' when
undefined, so the modal shows these cache values instead of empty dashes in
cache-only cases.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 55092775-591d-4951-bab3-164b263291bd

📥 Commits

Reviewing files that changed from the base of the PR and between f995a86 and 00a7e50.

📒 Files selected for processing (2)
  • controller/ratio_sync.go
  • web/src/pages/Setting/Ratio/UpstreamRatioSync.jsx

Align convertModelsDevToRatioData's docstring with its actual output by
listing create_cache_ratio = cache_write_cost / input_cost alongside the
other three emitted ratios, keeping the contract accurate.

@coderabbitai coderabbitai 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.

🧹 Nitpick comments (1)
controller/ratio_sync.go (1)

798-820: Tie-breaker logic looks sound; consider weighting cache_write over cache_read.

The new cacheFieldCount-based preference correctly addresses resellers (e.g., 302ai) that mirror list pricing but drop cache metadata, so the authoritative upstream (Anthropic) wins on ties. One nit: counts are equally weighted, so a candidate exposing only cache_read ties with one exposing only cache_write, and the lexicographic provider fallback decides. In practice both fields typically travel together, so this is unlikely to matter — just flagging in case a future provider publishes asymmetric metadata and you want a deterministic preference (e.g., prefer the candidate that has CacheWrite set, since that's the new authoritative signal this PR relies on).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@controller/ratio_sync.go` around lines 798 - 820, The tie-breaker should
prefer candidates that expose CacheWrite; update the comparison in the provider
selection logic (the block that calls cacheFieldCount(current) and
cacheFieldCount(next)) to first check if one candidate has CacheWrite and the
other does not and return the one with CacheWrite, then fall back to CacheRead
presence or the existing cacheFieldCount logic, and finally the existing
lexicographic provider tie-breaker; alternatively, modify
cacheFieldCount(modelsDevCandidate) to weight CacheWrite higher than CacheRead
(e.g., add 2 for CacheWrite, 1 for CacheRead) so that candidates with CacheWrite
rank above those with only CacheRead while leaving the rest of the comparison
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@controller/ratio_sync.go`:
- Around line 798-820: The tie-breaker should prefer candidates that expose
CacheWrite; update the comparison in the provider selection logic (the block
that calls cacheFieldCount(current) and cacheFieldCount(next)) to first check if
one candidate has CacheWrite and the other does not and return the one with
CacheWrite, then fall back to CacheRead presence or the existing cacheFieldCount
logic, and finally the existing lexicographic provider tie-breaker;
alternatively, modify cacheFieldCount(modelsDevCandidate) to weight CacheWrite
higher than CacheRead (e.g., add 2 for CacheWrite, 1 for CacheRead) so that
candidates with CacheWrite rank above those with only CacheRead while leaving
the rest of the comparison unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 129dc0ae-e007-4ec3-8b80-699db585ed0c

📥 Commits

Reviewing files that changed from the base of the PR and between 00a7e50 and d0e795e.

📒 Files selected for processing (1)
  • controller/ratio_sync.go

@RedwindA RedwindA closed this Jul 23, 2026
@RedwindA
RedwindA deleted the feat/syncCacheCreateRatio branch July 23, 2026 07:03
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.

同步价格可以加入缓存价格倍率吗

1 participant