Repository navigation
Conversation
- 实现分段计费核心逻辑 - 添加前端管理界面 - 支持按倍率和按价格两种设置方式 - 集成到模型定价和日志展示 - 完成 6 种语言的国际化翻译
WalkthroughAdds a per-model, four-segment token tier pricing system: backend config/resolution, relay quota application and logging, admin settings UI, frontend hooks/UI to surface tier details, and i18n translations across multiple locales. Changes
Sequence Diagram(s)sequenceDiagram
participant Admin as Admin (Settings UI)
participant API as Backend API (controller/pricing)
participant Config as TokenTierPricing Config
participant Relay as Relay Handler
participant ClientUI as Client UI (Pricing / Usage logs)
Admin->>API: Save token_tier_pricing (global + model rules)
API->>Config: Update in-memory config (SetModelTierPricing)
API-->>Admin: 200 OK
Relay->>Config: ResolveTokenTierPrice(model, inputTokens, outputTokens)
alt match found
Config-->>Relay: TokenTierPriceResult (matched, rule, prices/ratios)
Relay->>Relay: Compute quotas (CalcQuotaByTierPrice/CalcQuotaByTierRatio), add cache/image/audio quotas, enforce min quota
Relay-->>ClientUI: Response includes token_tier_pricing and tiered_pricing metadata
ClientUI->>ClientUI: Render tier details in pricing modal / usage logs
else no match
Config-->>Relay: no match
Relay-->>ClientUI: Response without tiered_pricing metadata
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45–75 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 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: 10
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
web/src/helpers/render.jsx (2)
1220-1347: Fix tier-mode cache/image unit price rendering (currently uses base modelRatio, not tier input unit price)
WhentierNameis set,inputRatioPriceis tier-derived, butcacheRatioPrice/imageRatioPriceare still computed frommodelRatio, so some displayed breakdown numbers become incorrect in tier mode.- let cacheRatioPrice = modelRatio * 2.0 * cacheRatio; - let imageRatioPrice = modelRatio * 2.0 * imageRatio; + // Cache/image unit prices should be based on the (possibly tiered) input unit price + let cacheRatioPrice = inputRatioPrice * cacheRatio; + let imageRatioPrice = inputRatioPrice * imageRatio;This also fixes the cached breakdown branch that uses
cachePrice: (cacheRatioPrice * rate)..., and makes the image paragraph consistent with tier pricing.Also applies to: 1373-1418
1519-1569: Avoid hardcoded Chinese inrenderLogContent; reuserenderTieredPricingContentand i18n keys
renderLogContentnow returns strings like模型倍率 ${modelRatio}/输出倍率...directly, which won’t localize. Also, tiered logic is duplicated instead of callingrenderTieredPricingContent.- // 如果有分段计费规则,使用极简格式 - if (tierName) { - if (tierUseRatio) { - // 倍率模式 - 极简格式 - const modelRatio = tierInputRatio?.toFixed(2) || '0.00'; - return `模型: ${modelRatio} * ${ratioLabel}: ${ratio}`; - } else { - // 价格模式 - 极简格式 - const inputPrice = (tierInputPrice * rate).toFixed(4); - const outputPrice = (tierOutputPrice * rate).toFixed(4); - return `输入: ${symbol}${inputPrice}/M, 输出: ${symbol}${outputPrice}/M * ${ratioLabel}: ${ratio}`; - } - } + if (tierName) { + return renderTieredPricingContent( + tierName, + tierUseRatio, + tierInputPrice, + tierOutputPrice, + tierInputRatio, + tierCompletionRatio, + groupRatio, + user_group_ratio, + ); + } ... - // 简化的倍率展示 - const parts = []; - parts.push(`模型倍率 ${modelRatio}`); + // Prefer i18n keys here (existing keys already cover these phrases in multiple locales) + const parts = []; + parts.push(i18next.t('模型倍率 {{modelRatio}}', { modelRatio })); ... - parts.push(`输出倍率 ${completionRatio}`); + parts.push(i18next.t('输出倍率 {{completionRatio}}', { completionRatio })); ... - parts.push(`缓存倍率 ${cacheRatio}`); + parts.push(i18next.t('缓存倍率 {{cacheRatio}}', { cacheRatio })); ... - parts.push(`图片倍率 ${imageRatio}`); + parts.push(i18next.t('图片倍率 {{imageRatio}}', { imageRatio })); ... - parts.push(`${ratioLabel} ${ratio}`); + parts.push(i18next.t('{{ratioType}} {{ratio}}', { ratioType: ratioLabel, ratio })); ... - parts.push(`Web搜索 ${webSearchCallCount}次`); + parts.push(i18next.t('Web搜索调用 {{webSearchCallCount}} 次', { webSearchCallCount })); ... - parts.push(`文件搜索 ${fileSearchCallCount}次`); + parts.push(i18next.t('文件搜索调用 {{fileSearchCallCount}} 次', { fileSearchCallCount }));(Last two keys may already exist as similar strings; if not, they should be added consistently across locales.)
Also applies to: 1572-1617
🧹 Nitpick comments (9)
relay/compatible_handler.go (1)
476-495: Consider extracting baseInputTokens calculation to reduce duplication.The baseInputTokens calculation (lines 489-494) duplicates the logic from lines 307-310. While this may be intentional for clarity, consider extracting it to a variable after line 310 and reusing it here to maintain DRY principles.
Apply this diff to reduce duplication:
// 尝试四段计费 tierResult := operation_setting.ResolveTokenTierPrice(modelName, promptTokens, completionTokens) + var baseInputTokens int if tierResult.Matched && !relayInfo.PriceData.UsePrice { // 四段计费路径:需要处理特殊tokens(缓存、图片、音频等) // 计算基础输入tokens(排除特殊tokens) - baseInputTokens := promptTokens - cacheTokens - imageTokens - audioTokens - cachedCreationTokens + baseInputTokens = promptTokens - cacheTokens - imageTokens - audioTokens - cachedCreationTokens if baseInputTokens < 0 { baseInputTokens = 0 } // ... existing logic ... // 添加四段计费相关日志字段 if tierResult.Matched { other["tiered_pricing"] = true other["tier_name"] = tierResult.RuleName other["tier_use_ratio"] = tierResult.UseRatio if tierResult.UseRatio { other["tier_input_ratio"] = tierResult.InputRatio other["tier_completion_ratio"] = tierResult.CompletionRatio } else { other["tier_input_price"] = tierResult.InputPrice other["tier_output_price"] = tierResult.OutputPrice } - // 计算基础输入tokens(用于计费的实际tokens数) - baseInputTokens := promptTokens - cacheTokens - imageTokens - audioTokens - cachedCreationTokens - if baseInputTokens < 0 { - baseInputTokens = 0 - } + // 使用之前计算的基础输入tokens other["tier_base_input_tokens"] = baseInputTokens other["tier_output_tokens"] = completionTokens }web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (3)
44-72: Make tier-config selection deterministic when multiple configs match.
getTierConfig()returns the first matched config based on object iteration order. If multiple configs can match the samemodel_name(e.g.,gpt-4*+gpt-4o), selection becomes order-dependent.Consider: (1) enforcing uniqueness (only one config may match), or (2) sorting by an explicit
priorityfield / keepingmodel_configsas an ordered array.
73-92: Avoid hardcoded2.0base in tier price conversion (cross-layer contract).
calculateTierPrice()assumes1 ratio = $2/1M tokensvia* 2.0. If the backend/base pricing changes, UI becomes wrong.Please confirm the canonical source of this constant (backend/system settings) and consider exporting it from a shared helper (or returning computed prices directly from the API).
217-272: Tier condition display may be misleading + defaultExpandAllRows UX.
- Condition strings use
</>for mins, but “Min/Max Token” typically implies inclusive bounds.- Input uses “K” units while output uses raw tokens; may confuse.
defaultExpandAllRowswill expand every group row when tiers exist.web/src/hooks/usage-logs/useUsageLogsData.jsx (2)
352-389: Verify render helper signatures after adding tiered-pricing positional args.These calls extend already-long positional parameter lists (
renderLogContent,renderModelPrice). Any mismatch in order/arity will produce incorrect “日志详情/计费过程” rendering without obvious failures.Recommendation: switch these helpers to accept a single options object (or at least group tier fields into one object) to make call sites robust.
Also please confirm the intended “no tier” sentinel values (e.g.,
null/0/false) align with the renderer logic.Also applies to: 448-478
563-566: Avoid empty.then((r)=>{})in handlePageChange.This adds noise and still doesn’t handle failures.
web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (2)
187-197: Normalize “模型列表” input before persisting
Today the UI stores raw comma-separated text; spaces/newlines can produce surprising matches (e.g."gpt-4, gpt-4o"). Consider trimming and canonicalizing to"gpt-4,gpt-4o"(or at least trim each token) on save.Also applies to: 505-528
257-273: “ratio ↔ price” conversions are hardcoded and partially stale when values go to 0
The* 2conversion is duplicated in several places and some transitions don’t clear staleinputPrice/outputPricewhen the source value becomes 0. Consider centralizing conversion helpers and explicitly resetting derived fields on 0 to avoid confusing UI state.Also applies to: 288-307, 684-818
web/src/helpers/render.jsx (1)
165-183: Category filter additions look fine; empty catch blocks are still silent
The expanded vendor model filters (Gemini/Moonshot/Zhipu/MiniMax/Cohere/Mistral) look reasonable. Thecatch (e) { }blocks still swallow parsing issues; if this is intentional, consider at least a comment or a single shared safe JSON parse helper.Also applies to: 206-209, 256-262, 878-880, 948-951, 972-984
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (19)
controller/pricing.go(3 hunks)relay/compatible_handler.go(2 hunks)setting/operation_setting/token_tier_pricing.go(1 hunks)web/src/components/settings/RatioSetting.jsx(2 hunks)web/src/components/table/model-pricing/layout/PricingPage.jsx(1 hunks)web/src/components/table/model-pricing/modal/ModelDetailSideSheet.jsx(2 hunks)web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx(11 hunks)web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx(1 hunks)web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx(2 hunks)web/src/helpers/render.jsx(18 hunks)web/src/hooks/model-pricing/useModelPricingData.jsx(4 hunks)web/src/hooks/usage-logs/useUsageLogsData.jsx(4 hunks)web/src/i18n/locales/en.json(1 hunks)web/src/i18n/locales/fr.json(1 hunks)web/src/i18n/locales/ja.json(1 hunks)web/src/i18n/locales/ru.json(1 hunks)web/src/i18n/locales/vi.json(1 hunks)web/src/i18n/locales/zh.json(1 hunks)web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx(1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
📚 Learning: 2025-06-21T03:37:41.726Z
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
Applied to files:
relay/compatible_handler.gosetting/operation_setting/token_tier_pricing.go
📚 Learning: 2025-08-27T02:15:25.448Z
Learnt from: AAEE86
Repo: QuantumNous/new-api PR: 1658
File: web/src/components/table/channels/modals/EditChannelModal.jsx:555-569
Timestamp: 2025-08-27T02:15:25.448Z
Learning: In EditChannelModal.jsx, the applyModelMapping function transforms the models list by replacing original model names (mapping values) with display names (mapping keys). The database stores this transformed list containing mapped keys. On channel load, data.models contains these mapped display names, making the initialization filter if (data.models.includes(key)) correct.
Applied to files:
web/src/helpers/render.jsx
🧬 Code graph analysis (8)
web/src/components/settings/RatioSetting.jsx (3)
web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (1)
TokenTierPricingSettings(106-824)web/src/pages/Setting/Ratio/GroupRatioSettings.jsx (1)
inputs(35-42)web/src/pages/Setting/Ratio/ModelRatioSettings.jsx (1)
inputs(42-51)
web/src/components/table/model-pricing/modal/ModelDetailSideSheet.jsx (1)
web/src/hooks/model-pricing/useModelPricingData.jsx (1)
tokenTierPricing(54-54)
web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (3)
web/src/components/table/model-pricing/modal/ModelDetailSideSheet.jsx (1)
Typography(30-30)web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (2)
Typography(25-25)tierConfig(71-71)web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (1)
Typography(43-43)
web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx (1)
web/src/helpers/render.jsx (2)
renderTieredPricingContent(1573-1617)renderModelPriceSimple(1619-1654)
web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (6)
web/src/components/table/model-pricing/modal/ModelDetailSideSheet.jsx (1)
Typography(30-30)web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (1)
Typography(25-25)web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (1)
Typography(24-24)web/src/components/settings/RatioSetting.jsx (1)
useTranslation(34-34)web/src/helpers/render.jsx (6)
options(603-609)options(2219-2219)i(449-449)i(578-578)i(594-594)i(597-597)web/src/helpers/utils.jsx (2)
showError(122-151)showSuccess(157-159)
controller/pricing.go (1)
setting/operation_setting/token_tier_pricing.go (1)
GetTokenTierPricingConfig(65-69)
setting/operation_setting/token_tier_pricing.go (3)
setting/ratio_setting/model_ratio.go (1)
CompletionRatio(324-324)setting/config/config.go (1)
GlobalConfig(19-19)setting/operation_setting/payment_setting_old.go (1)
USDExchangeRate(18-18)
web/src/helpers/render.jsx (2)
web/src/helpers/utils.jsx (3)
statusStr(654-654)s(656-656)symbol(649-649)web/src/hooks/model-pricing/useModelPricingData.jsx (1)
groupRatio(50-50)
🪛 Biome (2.1.2)
web/src/i18n/locales/ru.json
[error] 2288-2288: The key 添加模型 was already declared.
This where a duplicated key was declared again.
If a key is defined multiple times, only the last definition takes effect. Previous definitions are ignored.
(lint/suspicious/noDuplicateObjectKeys)
🔇 Additional comments (14)
web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx (1)
545-596: LGTM! Clean integration of tiered pricing rendering.The conditional logic correctly prioritizes tiered pricing over existing Claude and OpenAI pricing paths, ensuring backward compatibility while introducing the new feature.
relay/compatible_handler.go (1)
304-363: Verify tiered pricing scope: ratio mode only.The condition
tierResult.Matched && !relayInfo.PriceData.UsePricerestricts tiered pricing to ratio-based models. WhenUsePriceis true (fixed-price models), the code falls through to line 405 even if a tier matches. Please confirm this is intentional—the design may be that tiered pricing is incompatible with per-request fixed pricing.setting/operation_setting/token_tier_pricing.go (4)
59-88: LGTM! Proper thread safety with RWMutex.The configuration accessors and mutators correctly use RWMutex for thread-safe read/write operations. Defensive nil checks in SetModelTierPricing and DeleteModelTierPricing prevent panics.
90-136: LGTM! Clean resolution logic with sensible defaults.The rule resolution correctly implements first-match semantics with early-exit optimizations. The default CompletionRatio of 1.0 (line 128-130) prevents edge cases when users configure input ratio but forget output ratio.
189-202: LGTM! Simple and efficient wildcard matching.The pattern matching supports exact matches and suffix wildcards (e.g.,
gpt-4*), which covers common use cases efficiently. The limitation to suffix-only wildcards is a reasonable trade-off for performance and simplicity.
205-267: LGTM! Accurate quota calculations with proper precision.Both CalcQuotaByTierPrice and CalcQuotaByTierRatio use decimal arithmetic for financial accuracy and enforce a minimum quota of 1 when tokens are consumed, preventing zero-cost requests on low-token usage.
web/src/components/settings/RatioSetting.jsx (1)
29-29: LGTM! Clean integration of token tier pricing tab.The new tab is integrated consistently with existing ratio setting tabs, properly passing the
optionsandrefreshprops to maintain the data flow pattern.Also applies to: 118-120
web/src/components/table/model-pricing/modal/ModelDetailSideSheet.jsx (1)
45-45: LGTM! Proper prop threading.The tokenTierPricing prop is cleanly threaded from parent to ModelPricingTable with no logic changes.
Also applies to: 101-101
controller/pricing.go (1)
6-6: LGTM! Clean API integration.The token tier pricing config is properly retrieved and exposed in the API response without breaking existing fields.
Also applies to: 42-43, 53-53
web/src/i18n/locales/zh.json (1)
2210-2274: LGTM! Comprehensive Chinese translations.The translation keys cover all aspects of the token tier pricing feature, including settings UI, rule configuration, price/ratio modes, and user-facing messages. The keys are well-organized and follow the existing translation structure.
web/src/components/table/model-pricing/layout/PricingPage.jsx (1)
66-81: Prop wiring looks correct (tier pricing data now threaded into the detail sheet).
Optional: for consistency with other props, you could passtokenTierPricing={allProps.tokenTierPricing}.web/src/hooks/model-pricing/useModelPricingData.jsx (3)
54-55: State addition is clean and appropriately defaulted to null.
222-257: API field plumbed through safely (token_tier_pricing || null).
330-403: Hook now exposestokenTierPricingfor downstream UI wiring.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (1)
21-21: Remove unused import.The
Collapsiblecomponent is imported but never used in this file.Apply this diff to remove the unused import:
-import { Card, Avatar, Typography, Table, Tag, Collapsible } from '@douyinfe/semi-ui'; +import { Card, Avatar, Typography, Table, Tag } from '@douyinfe/semi-ui';
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx(11 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
🧬 Code graph analysis (1)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (3)
web/src/hooks/model-pricing/useModelPricingData.jsx (4)
tokenTierPricing(54-54)models(47-47)displayPrice(175-187)tokenUnit(46-46)web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (1)
modelConfigs(124-124)web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (1)
tierConfig(28-54)
🔇 Additional comments (3)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (3)
44-69: LGTM!The tier config matching logic is correct, including wildcard pattern support (
gpt-4*) and exact matching. The implementation properly checks if configs are enabled before matching.
137-207: LGTM!The explicit column widths improve layout consistency and readability. The removal of the billing type column and the width allocations are appropriate for the table structure.
286-314: LGTM!The conditional UI elements (updated header text and purple notification box) provide clear user feedback when tiered pricing is active. The informational message appropriately guides users to expand rows for tier details.
| defaultExpandAllRows={tierConfig && tierConfig.rules && tierConfig.rules.length > 0} | ||
| expandedRowRender={ | ||
| tierConfig && tierConfig.rules && tierConfig.rules.length > 0 | ||
| ? (record) => { | ||
| const tierData = tierConfig.rules.map((rule, index) => { | ||
| const prices = calculateTierPrice(rule, record.ratio); | ||
| const conditions = []; | ||
| if (rule.max_input_tokens > 0) { | ||
| conditions.push(rule.min_input_tokens > 0 | ||
| ? `${(rule.min_input_tokens / 1000).toFixed(0)}K < ${t('输入')} ≤ ${(rule.max_input_tokens / 1000).toFixed(0)}K` | ||
| : `${t('输入')} ≤ ${(rule.max_input_tokens / 1000).toFixed(0)}K`); | ||
| } else if (rule.min_input_tokens > 0) { | ||
| conditions.push(`${t('输入')} > ${(rule.min_input_tokens / 1000).toFixed(0)}K`); | ||
| } | ||
| if (rule.max_output_tokens > 0) { | ||
| conditions.push(rule.min_output_tokens > 0 | ||
| ? `${rule.min_output_tokens} < ${t('输出')} ≤ ${rule.max_output_tokens}` | ||
| : `${t('输出')} ≤ ${rule.max_output_tokens}`); | ||
| } else if (rule.min_output_tokens > 0) { | ||
| conditions.push(`${t('输出')} > ${rule.min_output_tokens}`); | ||
| } | ||
| return { | ||
| key: index, | ||
| name: rule.name || `T${index + 1}`, | ||
| condition: conditions.join(' & ') || t('默认'), | ||
| inputPrice: prices.inputPrice, | ||
| outputPrice: prices.outputPrice, | ||
| }; | ||
| }); | ||
| return ( | ||
| <div className='bg-gradient-to-r from-blue-50 to-indigo-50 py-2 px-4'> | ||
| {tierData.map((tier, idx) => ( | ||
| <div key={tier.key} className={`flex items-center justify-between py-2 ${idx < tierData.length - 1 ? 'border-b border-blue-100' : ''}`}> | ||
| <div className='flex-1'> | ||
| <Tag color='cyan' size='small' className='font-semibold'>{tier.name}</Tag> | ||
| <div className='text-gray-500 text-xs mt-1'>{tier.condition}</div> | ||
| </div> | ||
| <div className='flex'> | ||
| <div style={{ width: 120 }}> | ||
| <div className='text-xs text-gray-500'>{t('提示')}</div> | ||
| <div className='font-semibold text-orange-600'>{tier.inputPrice}</div> | ||
| <div className='text-xs text-gray-500'>/ {tokenUnit === 'K' ? '1K' : '1M'} tokens</div> | ||
| </div> | ||
| <div style={{ width: 120 }}> | ||
| <div className='text-xs text-gray-500'>{t('补全')}</div> | ||
| <div className='font-semibold text-orange-600'>{tier.outputPrice}</div> | ||
| <div className='text-xs text-gray-500'>/ {tokenUnit === 'K' ? '1K' : '1M'} tokens</div> | ||
| </div> | ||
| </div> | ||
| </div> | ||
| ))} | ||
| </div> | ||
| ); | ||
| } | ||
| : undefined | ||
| } |
There was a problem hiding this comment.
Fix inconsistent token unit display in tier conditions.
The condition strings display input and output tokens inconsistently:
- Input tokens: Divided by 1,000 and shown with "K" suffix (line 226:
(rule.min_input_tokens / 1000).toFixed(0)}K) - Output tokens: Shown as raw numbers without conversion (line 233:
${rule.min_output_tokens})
This creates user confusion. Both should use the same unit formatting, ideally respecting the tokenUnit prop ('K' or 'M') that's already used for price display (lines 258, 263).
Apply this diff to make the display consistent:
const conditions = [];
if (rule.max_input_tokens > 0) {
+ const divisor = tokenUnit === 'K' ? 1000 : 1000000;
+ const minInput = (rule.min_input_tokens / divisor).toFixed(tokenUnit === 'K' ? 0 : 3);
+ const maxInput = (rule.max_input_tokens / divisor).toFixed(tokenUnit === 'K' ? 0 : 3);
conditions.push(rule.min_input_tokens > 0
- ? `${(rule.min_input_tokens / 1000).toFixed(0)}K < ${t('输入')} ≤ ${(rule.max_input_tokens / 1000).toFixed(0)}K`
- : `${t('输入')} ≤ ${(rule.max_input_tokens / 1000).toFixed(0)}K`);
+ ? `${minInput}${tokenUnit} < ${t('输入')} ≤ ${maxInput}${tokenUnit}`
+ : `${t('输入')} ≤ ${maxInput}${tokenUnit}`);
} else if (rule.min_input_tokens > 0) {
- conditions.push(`${t('输入')} > ${(rule.min_input_tokens / 1000).toFixed(0)}K`);
+ const divisor = tokenUnit === 'K' ? 1000 : 1000000;
+ const minInput = (rule.min_input_tokens / divisor).toFixed(tokenUnit === 'K' ? 0 : 3);
+ conditions.push(`${t('输入')} > ${minInput}${tokenUnit}`);
}
if (rule.max_output_tokens > 0) {
+ const divisor = tokenUnit === 'K' ? 1000 : 1000000;
+ const minOutput = (rule.min_output_tokens / divisor).toFixed(tokenUnit === 'K' ? 0 : 3);
+ const maxOutput = (rule.max_output_tokens / divisor).toFixed(tokenUnit === 'K' ? 0 : 3);
conditions.push(rule.min_output_tokens > 0
- ? `${rule.min_output_tokens} < ${t('输出')} ≤ ${rule.max_output_tokens}`
- : `${t('输出')} ≤ ${rule.max_output_tokens}`);
+ ? `${minOutput}${tokenUnit} < ${t('输出')} ≤ ${maxOutput}${tokenUnit}`
+ : `${t('输出')} ≤ ${maxOutput}${tokenUnit}`);
} else if (rule.min_output_tokens > 0) {
- conditions.push(`${t('输出')} > ${rule.min_output_tokens}`);
+ const divisor = tokenUnit === 'K' ? 1000 : 1000000;
+ const minOutput = (rule.min_output_tokens / divisor).toFixed(tokenUnit === 'K' ? 0 : 3);
+ conditions.push(`${t('输出')} > ${minOutput}${tokenUnit}`);
}🤖 Prompt for AI Agents
In web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx
around lines 217 to 272, the tier condition strings format input tokens in
thousands (K) but leave output tokens as raw numbers, causing inconsistent
units; update the condition construction to use the tokenUnit prop so both input
and output token values are divided by 1_000 for 'K' or 1_000_000 for 'M',
formatted with .toFixed(0) and suffixed with the appropriate unit (K or M), and
ensure comparisons (≤, >) use the converted numbers consistently for
min_input_tokens, max_input_tokens, min_output_tokens and max_output_tokens so
the displayed condition text matches the price unit shown elsewhere.
- 修复边界条件显示:将 < 改为 ≤,正确表示区间边界 - 统一 Token 单位显示:添加 formatTokens() 函数处理小于 1K 的情况 - 动态计算基础价格:使用 getRatioBasePrice() 替代硬编码 $2/1M - 添加配置优先级排序:按 priority 字段升序排列确定匹配顺序 - 添加重复名称检测:配置名称和规则名称不允许重复 - 添加规则验证:最小值不能大于最大值 - 移除 i18n 重复 key:清理所有语言文件中的重复翻译 - 添加新翻译 key:相对于基础倍率(6 种语言)
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (3)
web/src/i18n/locales/en.json (1)
2241-2242:tier_ratio_mode_tipvalue is cryptic/inconsistent with nearby copy.
"1x=$2/1M"reads as shorthand; consider"1x = $2 / 1M tokens"to match the longer explanatory strings and avoid ambiguity.web/src/i18n/locales/ru.json (1)
2282-2282: Wording consistency/completeness: avoid “коэф.” + the long help text looks truncated vs CN.
Recommend using consistent terminology (“коэффициент/множитель”) and completing the guidance string so RU users get the same instructions (matching order, first-match behavior, price→ratio helper, etc.).Also applies to: 2291-2291
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (1)
246-308: Tier rendering with minor unit inconsistency.The expanded tier rendering now consistently applies
formatTokensto both input and output token ranges. However, note that condition ranges are always displayed in thousands (K), while the price unit labels respect thetokenUnitprop ('K' or 'M'). This minor inconsistency is acceptable but could be unified for perfect consistency.If desired, you could make the condition formatting respect
tokenUnit:const formatTokens = (tokens) => { - if (tokens >= 1000) { - return `${(tokens / 1000).toFixed(0)}K`; + const divisor = tokenUnit === 'K' ? 1000 : 1000000; + const decimals = tokenUnit === 'K' ? 0 : 3; + if (tokens >= divisor) { + return `${(tokens / divisor).toFixed(decimals)}${tokenUnit}`; } return tokens.toString(); };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx(12 hunks)web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx(1 hunks)web/src/i18n/locales/en.json(1 hunks)web/src/i18n/locales/fr.json(1 hunks)web/src/i18n/locales/ja.json(1 hunks)web/src/i18n/locales/ru.json(1 hunks)web/src/i18n/locales/vi.json(1 hunks)web/src/i18n/locales/zh.json(1 hunks)web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
🧬 Code graph analysis (2)
web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (4)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (2)
Typography(25-25)tierConfig(94-94)web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (1)
Typography(43-43)web/src/components/table/model-pricing/modal/ModelDetailSideSheet.jsx (1)
Typography(30-30)web/src/hooks/model-pricing/useModelPricingData.jsx (1)
tokenTierPricing(54-54)
web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (3)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (2)
getRatioBasePrice(30-33)quotaPerUnit(31-31)web/src/helpers/render.jsx (9)
quotaPerUnit(915-915)quotaPerUnit(921-921)quotaPerUnit(928-928)quotaPerUnit(999-999)getQuotaPerUnit(914-918)i(449-449)i(578-578)i(594-594)i(597-597)web/src/helpers/utils.jsx (3)
showError(122-151)showSuccess(157-159)a(259-259)
🔇 Additional comments (18)
web/src/i18n/locales/en.json (1)
2183-2246: No duplicate key collisions were found. The three generic keys flagged—"模型列表", "计费设置", and "价格模式"—each appear only once in the file (at lines 2197, 2216, and 2236 respectively) and are new additions, not overwrites of existing translations. The Tiered Pricing additions do not cause silent key override issues.web/src/i18n/locales/fr.json (1)
2232-2294: No duplicate i18n keys detected—this concern is unfounded.Verification of both
web/src/i18n/locales/fr.json(2292 unique keys) anden.json(2244 unique keys) confirms zero duplicate keys exist in either file. The Tiered Pricing block additions (lines 2232–2294) introduce new, non-conflicting keys. Namespacing is not required.Likely an incorrect or invalid review comment.
web/src/i18n/locales/ja.json (1)
2131-2193: No issues found. The ja.json file contains 2,192 unique keys with no duplicates, so there is no duplicate-key override risk from the tier-pricing additions at lines 2131–2193.web/src/i18n/locales/vi.json (1)
2742-2800: Looks good: tier-pricing VI strings are consistent and appear to avoid the earlier duplicate-key issue.web/src/i18n/locales/ru.json (1)
2242-2304: No duplicate keys detected in the Russian locale file.
Verified that the full JSON contains no duplicate keys, so no CI risk from this file.web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (3)
28-55: LGTM! Priority-based matching correctly implemented.The tier config matching now properly sorts by priority and uses wildcard pattern matching as intended. The logic correctly returns the first matching config, giving precedence to lower priority values.
62-120: Well-structured tier data preparation with consistent formatting.The token formatting is now consistent between input and output ranges using the
formatTokenshelper, and the mode detection properly checks for null/undefined rather than just comparing to zero. The tier conditions correctly use inclusive operators (≤, ≥).
169-189: Card rendering is clean and functional.The component renders a well-structured card with tier pricing information. The footer provides helpful context about matching priority and billing modes.
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (4)
27-33: Well-documented ratio base price calculation.The
getRatioBasePricehelper now includes clear documentation explaining the quotaPerUnit relationship and how the $2/1M base price is derived. This addresses the previous concern about the undocumented hardcoded value.
52-92: Tier config matching with helpful implementation notes.The
getTierConfigfunction correctly implements priority-based matching with wildcard support. The extensive inline comments show thoughtful consideration of the sort order and will help future maintainers understand the intended behavior.
96-121: Robust tier price calculation with proper mode detection.The
calculateTierPricefunction correctly handles both price and ratio modes. The ratio mode calculation now uses the documentedratioBasePricehelper and provides a sensible fallback for output ratio calculation. The price mode detection properly checks for null/undefined rather than just comparing to zero.
313-353: Clean integration of tier pricing UI elements.The component properly conditionally renders tier-related UI elements (description text and hint block) based on the presence of
tierConfig. The user guidance is clear and helpful.web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (6)
48-112: Well-designed default templates for tier pricing rules.The default rule templates provide clear examples of different token range configurations and ratio settings. These will help users understand how to structure their tier pricing rules. The
getRatioBasePricecalculation is consistent with other components.
156-193: Proper save flow with error handling and refresh.The save functions correctly handle API calls, error cases, and trigger the parent refresh callback to ensure the UI stays in sync with persisted data.
239-259: Duplicate name check successfully prevents accidental overwrites.The save logic now properly validates that new model configurations don't reuse existing names, addressing the previous concern about silent overwrites during Add/Copy operations.
304-362: Comprehensive rule validation successfully implemented.The save logic now includes proper validation for:
- Required rule names
- Unique rule names within a model config (prevents rowKey conflicts)
- Token range sanity (min ≤ max when max is set)
- Proper price-to-ratio conversion
This addresses the previous review comments about missing validation.
698-741: Bidirectional price/ratio conversion works correctly.The pricing mode toggle properly converts between ratio and price representations using the
getRatioBasePrice()helper. The conversion logic correctly handles both input and output values, including the relative completion ratio calculation.
743-880: Excellent live synchronization between price and ratio modes.The input fields for both ratio and price modes include live synchronization that updates the equivalent values as users type. This provides excellent UX by showing real-time conversions. The calculations consistently use
getRatioBasePrice()and properly handle the relationships between input/output and ratio/completion values.
| "开启后,当前分组渠道失败时会按顺序尝试下一个分组的渠道": "开启后,当前分组渠道失败时会按顺序尝试下一个分组的渠道", | ||
| "分段计费": "分段计费", | ||
| "分段计费设置": "分段计费设置", | ||
| "启用分段计费": "启用分段计费", | ||
| "全局开关,关闭后所有模型的分段计费都将禁用": "全局开关,关闭后所有模型的分段计费都将禁用", | ||
| "模型计费配置": "模型计费配置", | ||
| "暂无配置,点击\"添加模型\"开始配置": "暂无配置,点击\"添加模型\"开始配置", | ||
| "条规则": "条规则", | ||
| "确定删除此模型配置吗?": "确定删除此模型配置吗?", | ||
| "添加模型计费配置": "添加模型计费配置", | ||
| "编辑模型计费配置": "编辑模型计费配置", | ||
| "配置名称": "配置名称", | ||
| "例如: GPT-4系列": "例如: GPT-4系列", | ||
| "给这个配置起一个名字,方便管理": "给这个配置起一个名字,方便管理", | ||
| "模型列表": "模型列表", | ||
| "例如: gpt-4, gpt-4o, gpt-4-turbo 或 gpt-4*": "例如: gpt-4, gpt-4o, gpt-4-turbo 或 gpt-4*", | ||
| "多个模型用英文逗号分割,支持通配符 *": "多个模型用英文逗号分割,支持通配符 *", | ||
| "启用状态": "启用状态", | ||
| "计费规则": "计费规则", | ||
| "使用默认模板": "使用默认模板", | ||
| "添加规则": "添加规则", | ||
| "添加计费规则": "添加计费规则", | ||
| "编辑计费规则": "编辑计费规则", | ||
| "规则名称": "规则名称", | ||
| "例如: T1_input_le_32k": "例如: T1_input_le_32k", | ||
| "输入Token条件": "输入Token条件", | ||
| "最小输入Token": "最小输入Token", | ||
| "最大输入Token": "最大输入Token", | ||
| "0 表示无下限": "0 表示无下限", | ||
| "0 表示无上限": "0 表示无上限", | ||
| "输出Token条件": "输出Token条件", | ||
| "最小输出Token": "最小输出Token", | ||
| "最大输出Token": "最大输出Token", | ||
| "计费设置": "计费设置", | ||
| "设置方式": "设置方式", | ||
| "输入倍率": "输入倍率", | ||
| "输出倍率": "输出倍率", | ||
| "相对于输入倍率的倍数,默认1.0": "相对于输入倍率的倍数,默认1.0", | ||
| "例如: 0.800000": "例如: 0.800000", | ||
| "例如: 1.600000": "例如: 1.600000", | ||
| "两种方式可相互转换,最终以倍率形式保存 (1倍率 = $2/1M tokens)": "两种方式可相互转换,最终以倍率形式保存 (1倍率 = $2/1M tokens)", | ||
| "等价倍率: {{ratio}}": "等价倍率: {{ratio}}", | ||
| "等价倍率: {{ratio}} (相对于输入价格)": "等价倍率: {{ratio}} (相对于输入价格)", | ||
| "(等价价格: ${{price}}/1M)": "(等价价格: ${{price}}/1M)", | ||
| "确定删除此规则吗?": "确定删除此规则吗?", | ||
| "请填写规则名称": "请填写规则名称", | ||
| "输入Token范围": "输入Token范围", | ||
| "输出Token范围": "输出Token范围", | ||
| "计费倍率": "计费倍率", | ||
| "分段计费使用倍率模式计费(1倍率 = $2/1M tokens)。您可以为每个配置设置多个模型(逗号分割,支持通配符*),根据输入/输出Token数量的不同范围使用不同的倍率。规则按顺序匹配,第一条匹配的规则将被使用。支持通过价格快速计算倍率。": "分段计费使用倍率模式计费(1倍率 = $2/1M tokens)。您可以为每个配置设置多个模型(逗号分割,支持通配符*),根据输入/输出Token数量的不同范围使用不同的倍率。规则按顺序匹配,第一条匹配的规则将被使用。支持通过价格快速计算倍率。", | ||
| "使用分段计费规则:{{tierName}}": "使用分段计费规则:{{tierName}}", | ||
| "此模型启用了分段计费,点击展开按钮查看各阶段价格详情": "此模型启用了分段计费,点击展开按钮查看各阶段价格详情", | ||
| "不同用户分组的价格信息(包含分段计费)": "不同用户分组的价格信息(包含分段计费)", | ||
| "价格模式": "价格模式", | ||
| "相对于基础倍率": "相对于基础倍率", | ||
| "分段计费详情": "分段计费详情", | ||
| "规则按优先级从上到下匹配": "规则按优先级从上到下匹配", | ||
| "实际费用乘以分组倍率": "实际费用乘以分组倍率", | ||
| "tier_ratio_mode_tip": "1倍率=$2/1M tokens", | ||
| "数值越小优先级越高,多个配置匹配同一模型时优先使用低优先级配置": "数值越小优先级越高,多个配置匹配同一模型时优先使用低优先级配置", | ||
| "配置名称已存在,请使用其他名称": "配置名称已存在,请使用其他名称", | ||
| "规则名称已存在,请使用其他名称": "规则名称已存在,请使用其他名称", | ||
| "最小输入Token不能大于最大输入Token": "最小输入Token不能大于最大输入Token", | ||
| "最小输出Token不能大于最大输出Token": "最小输出Token不能大于最大输出Token" |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Get a summary of which locales have the new key
echo "=== Summary: locales with tier_ratio_mode_tip ==="
for locale in web/src/i18n/locales/*.json; do
if grep -q '"tier_ratio_mode_tip"' "$locale" 2>/dev/null; then
basename "$locale"
fi
done
echo -e "\n=== Summary: locales WITHOUT tier_ratio_mode_tip ==="
for locale in web/src/i18n/locales/*.json; do
if ! grep -q '"tier_ratio_mode_tip"' "$locale" 2>/dev/null; then
basename "$locale"
fi
doneRepository: QuantumNous/new-api
Length of output: 214
Add missing tier-pricing keys to all locale files.
The new tier_ratio_mode_tip key and related tier-pricing translations are present in en.json and zh.json only. They are missing from fr.json, ja.json, ru.json, and vi.json, causing users with these languages to see untranslated keys at runtime. Add these keys to all 6 locale files to maintain consistency.
🤖 Prompt for AI Agents
In web/src/i18n/locales/{fr.json, ja.json, ru.json, vi.json} (around the same
section as lines 2209-2272 in zh.json), add the missing tier-pricing keys that
exist in en.json/zh.json (notably "tier_ratio_mode_tip" and the other
tier-related labels/strings shown in the zh.json snippet) so all locales have
the same keys; if you don't have translations yet, add the keys with the English
values as placeholders, keep key names identical, and place them in the matching
location/order to remain consistent across locale files.
- 修复价格模式判断:将 !== undefined 改回 > 0 - 修复硬编码 * 2 乘数:使用 getRatioBasePrice() 动态计算 - 添加俄语复数形式:条规则 支持 one/few/many/other - 修复法语标点:问号前添加空格 - 添加 tier_ratio_mode_tip 到 fr/ja/ru/vi - 移除俄语翻译尾部空格 - 统一所有语言的复数形式支持 count 参数
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (3)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (1)
247-309: Token range display ignorestokenUnitand reintroduces inconsistent units.
formatTokens()forces “K” display and doesn’t respect thetokenUnitprop (K vs M). This is the same class of issue previously flagged.web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (1)
105-120: Fix “price mode” detection (input_price > 0is not robust).
This repeats a previously addressed issue pattern; here it can still mislabel tiers and mis-render values.- const isPriceMode = rule.input_price > 0; + const isPriceMode = + (rule.input_price ?? 0) !== 0 || (rule.output_price ?? 0) !== 0;web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (1)
305-363: Critical: remove hardcoded/ 2in price→ratio conversion (billing config will be wrong).
Must usegetRatioBasePrice()(and ideally allow 0-price tiers without silently flipping modes).// 如果是价格模式,需要从价格计算倍率 if (pricingSubMode === 'price') { + const ratioBasePrice = getRatioBasePrice(); if (editingRule.inputPrice > 0) { - ruleToSave.input_ratio = editingRule.inputPrice / 2; + ruleToSave.input_ratio = editingRule.inputPrice / ratioBasePrice; } else { ruleToSave.input_ratio = 0; } if (editingRule.outputPrice > 0 && editingRule.inputPrice > 0) { ruleToSave.completion_ratio = editingRule.outputPrice / editingRule.inputPrice; } else { ruleToSave.completion_ratio = 1.0; } }#!/bin/bash # Verify no other hardcoded ratio-base constants remain in tier pricing paths. rg -n --hidden --no-ignore -S '\/\s*2\b|\*\s*2\b|2\.0\b' web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx || true
🧹 Nitpick comments (3)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (2)
27-33: ExtractgetRatioBasePrice()to a shared helper (duplication across UI).
You now have the same logic in multiple components/settings; consider centralizing to avoid drift.
52-93: Remove the inline “bot reasoning” comment block; keep a short deterministic note instead.
Those lines read like debugging chatter and will age poorly.web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (1)
186-188: Footer messaging is good, but consider clarifying output ratio semantics.
IfoutputValueiscompletion_ratio(relative to input), the column title “输出计费” can be misread as “最终输出倍率/价格”.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx(12 hunks)web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx(1 hunks)web/src/i18n/locales/en.json(1 hunks)web/src/i18n/locales/fr.json(1 hunks)web/src/i18n/locales/ja.json(1 hunks)web/src/i18n/locales/ru.json(1 hunks)web/src/i18n/locales/vi.json(1 hunks)web/src/i18n/locales/zh.json(1 hunks)web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- web/src/i18n/locales/en.json
- web/src/i18n/locales/vi.json
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
🧬 Code graph analysis (3)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (4)
web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (2)
Typography(24-24)tierConfig(28-55)web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (4)
Typography(43-43)getRatioBasePrice(48-51)quotaPerUnit(49-49)modelConfigs(132-132)web/src/helpers/render.jsx (7)
quotaPerUnit(915-915)quotaPerUnit(921-921)quotaPerUnit(928-928)quotaPerUnit(999-999)getQuotaPerUnit(914-918)displayPrice(1091-1091)displayPrice(1203-1203)web/src/helpers/utils.jsx (1)
a(259-259)
web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (2)
web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (1)
Typography(43-43)web/src/hooks/model-pricing/useModelPricingData.jsx (1)
tokenTierPricing(54-54)
web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (3)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (2)
getRatioBasePrice(30-33)quotaPerUnit(31-31)web/src/helpers/render.jsx (9)
quotaPerUnit(915-915)quotaPerUnit(921-921)quotaPerUnit(928-928)quotaPerUnit(999-999)getQuotaPerUnit(914-918)i(449-449)i(578-578)i(594-594)i(597-597)web/src/helpers/utils.jsx (3)
showError(122-151)showSuccess(157-159)a(259-259)
🪛 Biome (2.1.2)
web/src/i18n/locales/fr.json
[error] 2299-2299: The key 确定删除此规则吗? was already declared.
This where a duplicated key was declared again.
If a key is defined multiple times, only the last definition takes effect. Previous definitions are ignored.
(lint/suspicious/noDuplicateObjectKeys)
🔇 Additional comments (7)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (1)
323-351: Nice UX touch surfacing tier pricing presence.
Header copy + hint block make discoverability much better.web/src/i18n/locales/zh.json (1)
2209-2274: Locale additions look consistent and complete for the new tier-pricing UI.
No functional concerns in this change.web/src/i18n/locales/ja.json (1)
2131-2196: JA tier-pricing translations look OK (and no duplicate-key smell in this snippet).web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (1)
26-60: Config matching by ascending priority is consistent with “数值越小优先级越高”.
Looks deterministic and readable.web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (2)
239-260: Good: prevents accidental overwrite on Add/Copy via name collision check.
45-51: Verify the source ofquota_per_unitand its role in pricing calculations.The
getQuotaPerUnit()function retrievesquota_per_unitfrom localStorage, which is populated by the backend'scommon.QuotaPerUnitconstant (500,000 = $0.002 per 1K tokens). This is the intended canonical source for tier pricing base conversion. The formula1000000 / quotaPerUnitcorrectly derives the USD/1M tokens base price. No action needed—the dependency and semantics are correct.web/src/i18n/locales/ru.json (1)
2242-2308: ✅ Tier pricing translations complete and previous issues resolved.The new token tier pricing (分段计费) translations are well-integrated into the Russian locale file:
- Pluralization fixed (lines 2249–2252): "条规则" now correctly uses Russian plural forms (_one/_few/_many/_other), addressing the prior issue.
- No duplicate keys in the new section (previous "添加模型" duplicate removed).
- Trailing spaces removed (verified on line 2258).
- Complete coverage: All new tier pricing UI strings have Russian translations.
- Consistent placeholders: {{tierName}}, {{count}}, {{ratio}}, {{price}} used correctly throughout.
Russian translations are contextually appropriate (e.g., "Уровневая тарификация" for "分段计费", "Коэффициент" for "倍率"). Minor note: line 2304–2305 explanation is somewhat redundant in phrasing but semantically correct.
- 改进价格模式检测:使用 hasPrice 检查任一价格字段非零 - 修复 NaN 风险:为 input_ratio、completion_ratio 添加默认值 - 添加注释说明当前后端仅保存倍率模式 - 删除法语文件中重复的 "确定删除此规则吗?" key
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
web/src/i18n/locales/fr.json (1)
2233-2296: Approve tier pricing translations — verify usage in UI components.The tier pricing feature translations are well-structured and contextual (e.g.,
"输入Token条件","最大输出Token","分段计费设置"), avoiding the silent override risk of bare duplicate keys. The new entries follow the established pattern and include helpful descriptions and examples for operators.However, to ensure these keys are wired correctly in the frontend components, please verify:
- RatioSetting, ModelDetailSideSheet, ModelPricingTable, ModelTierPricingInfo components correctly reference these new keys.
- No orphaned keys — confirm all 60+ new keys added here are actually used by the UI components mentioned in the AI summary.
- Translation quality — spot-check a few French translations for accuracy and tone consistency.
Run the following verification script to confirm key usage:
#!/bin/bash # Description: Verify tier pricing i18n keys are referenced in UI components. # Find all i18n key references in the components listed echo "=== Checking for tier pricing key usage in components ===" grep -r "分段计费\|分段计费设置\|启用分段计费\|模型计费配置\|规则名称" \ web/src/components/RatioSetting \ web/src/components/ModelDetailSideSheet \ web/src/components/ModelPricingTable \ web/src/components/ModelTierPricingInfo \ 2>/dev/null | head -10 || echo "No direct matches; may use dynamic keys or aliases." # Check for any unused keys in fr.json tier pricing section (cross-reference with zh.json) echo "" echo "=== Comparing fr.json vs zh.json tier pricing keys ===" rg '"分段计费' web/src/i18n/locales/{fr,zh}.json | wc -lThe past review raised concerns about duplicate keys like
"输入","输出","已启用","已禁用","无限制"appearing twice in the file. Upon inspection of the current code, the new tier pricing section does not introduce bare duplicates of these common terms; they appear only in longer, context-specific keys. This suggests proper remediation was applied or the concern was misidentified.web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (1)
259-264: Fix token unit inconsistency in tier conditions display.The
formatTokenshelper hard-codes division by 1,000 and the 'K' suffix, ignoring thetokenUnitprop. WhentokenUnitis'M', tier conditions will incorrectly display 'K' units while the price columns use 'M' units, creating user confusion.This issue was previously flagged (lines 251-313 past review). Apply the following fix to respect
tokenUnit:- const formatTokens = (tokens) => { - if (tokens >= 1000) { - return `${(tokens / 1000).toFixed(0)}K`; - } - return tokens.toString(); - }; + const formatTokens = (tokens) => { + const divisor = tokenUnit === 'K' ? 1000 : 1000000; + const converted = tokens / divisor; + const decimals = tokenUnit === 'K' ? 0 : 3; + return `${converted.toFixed(decimals)}${tokenUnit}`; + };
🧹 Nitpick comments (3)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (1)
52-92: Remove verbose uncertainty comments about priority sorting.The long comment block (lines 59-68) expresses confusion about priority sorting direction, making the code harder to maintain. The actual implementation (ascending sort, first-match-wins) is correct and aligns with the resolution from previous reviews (ModelTierPricingInfo.jsx past comments show this was addressed). Replace the verbose commentary with a concise explanation.
Apply this diff:
- // Convert to array and sort by priority (ascending, assuming lower number = higher priority/checked first?? - // Wait, the bot said "sort the array by priority (descending if higher number means higher priority, or ascending if opposite)". - // Usually in this project, priority is higher = better. BUT if we iterate and return the FIRST match, we want the HIGHEST priority first. - // So we should sort DESCENDING (b - a). - // Let's re-read the bot's code suggestion in Chunk 28: `.sort((a, b) => (a?.priority ?? 0) - (b?.priority ?? 0));` -> This is ASCENDING. - // And it iterates: `for (const config of configs) { if (matched) return config; }`. - // So it picks the one with the SMALLEST priority value first. - // If standard "Priority" means higher is better, this code picks the lowest priority? - // Unless "Priority" here means "Order" (Sequence). - // I will stick to the bot's EXACT code suggestion to be safe. - - // Sort configs by priority to ensure deterministic matching order + // Sort by priority (ascending); lower priority values are matched first const configs = Object.values(modelConfigs) .filter((c) => c?.enabled) .sort((a, b) => (a?.priority ?? 0) - (b?.priority ?? 0));web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (2)
63-68: Consider acceptingtokenUnitprop for display consistency.The
formatTokenshelper hard-codes the 'K' suffix (1,000 divisor). For consistency with the broader pricing UI that supports both 'K' and 'M' units via thetokenUnitprop, consider having this component accept and usetokenUnitin the same wayModelPricingTabledoes.If you choose to add this, update the component signature and helper:
-const ModelTierPricingInfo = ({ modelData, tokenTierPricing, t }) => { +const ModelTierPricingInfo = ({ modelData, tokenTierPricing, tokenUnit = 'K', t }) => { // ... const formatTokens = (tokens) => { - if (tokens >= 1000) { - return `${(tokens / 1000).toFixed(0)}K`; - } - return tokens.toString(); + const divisor = tokenUnit === 'K' ? 1000 : 1000000; + const decimals = tokenUnit === 'K' ? 0 : 3; + return `${(tokens / divisor).toFixed(decimals)}${tokenUnit}`; };
115-120: Consider respectingtokenUnitin price display strings.Lines 116 and 119 hard-code the
"/ 1M"suffix for price mode. For consistency with the rest of the pricing UI, consider using thetokenUnitprop (if added per previous suggestion) to display either"/ 1K"or"/ 1M"tokens, matching the user's selected unit preference.If
tokenUnitis added:inputValue: isPriceMode - ? `$${(rule.input_price ?? 0).toFixed(6)} / 1M` + ? `$${(rule.input_price ?? 0).toFixed(6)} / ${tokenUnit === 'K' ? '1K' : '1M'}` : `${(rule.input_ratio ?? 0).toFixed(2)}x`, outputValue: isPriceMode - ? `$${(rule.output_price ?? 0).toFixed(6)} / 1M` + ? `$${(rule.output_price ?? 0).toFixed(6)} / ${tokenUnit === 'K' ? '1K' : '1M'}` : `${(rule.completion_ratio ?? 1.0).toFixed(2)}x`,
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx(12 hunks)web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx(1 hunks)web/src/i18n/locales/fr.json(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
🧬 Code graph analysis (2)
web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (4)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (2)
Typography(25-25)tierConfig(94-94)web/src/components/table/model-pricing/modal/ModelDetailSideSheet.jsx (1)
Typography(30-30)web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (1)
Typography(43-43)web/src/hooks/model-pricing/useModelPricingData.jsx (1)
models(47-47)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (4)
web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (2)
tierConfig(28-55)formatTokens(63-68)web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (3)
getRatioBasePrice(48-51)quotaPerUnit(49-49)modelConfigs(132-132)web/src/helpers/render.jsx (7)
quotaPerUnit(915-915)quotaPerUnit(921-921)quotaPerUnit(928-928)quotaPerUnit(999-999)getQuotaPerUnit(914-918)displayPrice(1091-1091)displayPrice(1203-1203)web/src/hooks/model-pricing/useModelPricingData.jsx (3)
tokenTierPricing(54-54)models(47-47)displayPrice(175-187)
🔇 Additional comments (10)
web/src/i18n/locales/fr.json (1)
2232-2232: No duplicate key issue found. Lines 2243 and 2278 contain distinct keys ("添加模型计费配置"and"请填写规则名称"respectively). A scan of all JSON keys in the file shows no duplicates, confirming that the tier pricing feature additions do not introduce conflicting keys.web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (6)
27-33: LGTM!The
getRatioBasePricehelper correctly computes the base price per 1M tokens fromquotaPerUnit. The formula and default value align with the implementation inTokenTierPricingSettings.jsx(lines 42-50).
96-126: LGTM!The
calculateTierPricefunction properly addresses previous review concerns:
- Mode detection correctly uses
!== 0checks to distinguish price mode from ratio mode- All ratio values have proper nullish coalescing defaults to prevent NaN
- Output ratio computation includes appropriate fallback logic
171-171: LGTM!Adding explicit column widths (150, 80, 120px) improves table layout consistency and prevents columns from shifting when tier details are expanded.
Also applies to: 186-186, 204-204, 217-217, 233-233
265-278: LGTM - condition logic structure is correct.The tier condition building logic properly handles all token range cases (max-only, range, min-only) with inclusive boundaries using
≤and≥operators. However, the display will only be fully consistent after fixing theformatTokenshelper to respecttokenUnit.
279-313: LGTM!The tier data rendering logic correctly:
- Maps tier rules to display data using
calculateTierPrice- Renders tier blocks with appropriate visual hierarchy (gradient background, borders)
- Displays input/output prices with proper
tokenUnitcontext- Handles empty conditions with fallback to
t('默认')
327-329: LGTM!The UI text enhancements improve user experience:
- Subtitle clarifies when tiered pricing is active (lines 327-329)
- Purple notification provides clear instructions for viewing tier details (lines 348-355)
Both additions align with the feature's objective to make tier pricing discoverable.
Also applies to: 348-355
web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (3)
28-55: LGTM!The
tierConfigcomputation correctly implements priority-based matching with wildcard pattern support. The logic is consistent withModelPricingTable.jsxand was properly addressed in previous review feedback.
124-169: LGTM!The table column definitions are well-structured:
- Proper internationalization with
t()wrapper- Appropriate visual hierarchy with Tags and color coding
- Clear distinction between price mode (green) and ratio mode (violet)
171-191: LGTM!The Card rendering is properly structured:
- Clear visual hierarchy with icon, title, and table
- Footer text is fully internationalized with
t()wrapping- The previous concern about hard-coded "1x=$2/1M" strings has been addressed
- ModelPricingTable: 添加 unitDivisor 实现 1K/1M tokens 价格单位转换 - ModelPricingTable: 使用 formatTierPrice 统一格式化,保留4位小数 - ModelTierPricingInfo: 添加 tokenUnit prop 支持价格单位显示 1K tokens 时价格除以 1000,1M tokens 时保持原值
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (1)
52-92: Hoist and memoizegetTierConfigto avoid recalculating on every render.
getTierConfigis defined insiderenderGroupPriceTable, causing it to be recreated and re-executed on every render. Since it depends only ontokenTierPricingandmodelData, move it to the component body and wrap it withuseMemofor better performance.Apply this diff:
+ const tierConfig = useMemo(() => { + if (!tokenTierPricing?.global_enabled || !modelData?.model_name) { + return null; + } + + const modelConfigs = tokenTierPricing.model_configs || {}; + const configs = Object.values(modelConfigs) + .filter((c) => c?.enabled) + .sort((a, b) => (a?.priority ?? 0) - (b?.priority ?? 0)); + + for (const config of configs) { + if (!config.enabled) continue; + + const models = config.models?.split(',').map((m) => m.trim()) || []; + const isMatched = models.some((pattern) => { + if (pattern.endsWith('*')) { + const prefix = pattern.slice(0, -1); + return modelData.model_name.startsWith(prefix); + } + return modelData.model_name === pattern; + }); + + if (isMatched) { + return config; + } + } + return null; + }, [tokenTierPricing, modelData]); + const renderGroupPriceTable = () => { - // 获取模型的分段计费配置 - const getTierConfig = () => { - if (!tokenTierPricing?.global_enabled || !modelData?.model_name) { - return null; - } - // ... rest of function - }; - - const tierConfig = getTierConfig();
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx(12 hunks)web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
🧬 Code graph analysis (1)
web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (3)
web/src/pages/Setting/Ratio/TokenTierPricingSettings.jsx (1)
Typography(43-43)web/src/hooks/model-pricing/useModelPricingData.jsx (1)
tokenTierPricing(54-54)web/src/hooks/tokens/useTokensData.jsx (1)
tokens(37-37)
🔇 Additional comments (4)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (2)
27-33: LGTM!The
getRatioBasePricehelper correctly computes the USD per 1M tokens based onquotaPerUnit. The formula and fallback value are appropriate.
96-131: LGTM!The
calculateTierPricefunction correctly handles both price mode and ratio mode, with proper fallbacks to prevent NaN issues. TheunitDivisorlogic appropriately converts prices from /1M to /1K when needed, and the 4-decimal precision is suitable for tier pricing display.web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (2)
28-55: LGTM!The
tierConfigcomputation is properly memoized with correct dependencies (tokenTierPricing,modelData). The priority-based sorting and wildcard pattern matching logic is consistent with the backend's matching behavior.
127-193: LGTM!The table column definitions and card rendering are well-structured. The footer text (line 191) provides helpful context about rule matching order and pricing modes, improving user understanding of the tier pricing system.
- ModelTierPricingInfo: outputValue 显示实际计算的输出倍率 (output_ratio ?? input_ratio * completion_ratio) - ModelTierPricingInfo: formatTokens 根据 tokenUnit 调整显示单位 - ModelPricingTable: formatTokens 根据 tokenUnit 调整显示单位 确保条件显示和价格显示使用相同的单位系统
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (1)
248-320: UI tip says “click expand”, but rows are expanded by default.
WithdefaultExpandAllRows={true}, there may be no expand action to take; the hint becomes misleading. Either (a) removedefaultExpandAllRows(so users expand manually), or (b) change the hint copy to reflect auto-expanded behavior.Option A (prefer, matches current copy):
- defaultExpandAllRows={tierConfig && tierConfig.rules && tierConfig.rules.length > 0} + defaultExpandAllRows={false}Option B (keep auto-expand, adjust copy):
- {t('此模型启用了分段计费,点击展开按钮查看各阶段价格详情')} + {t('此模型启用了分段计费,已展开显示各阶段价格详情')}Also applies to: 355-362
♻️ Duplicate comments (1)
web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx (1)
110-126: Price-mode detection misclassifies valid zero-priced tiers.
isPriceModeuses!== 0, so an explicitly configured free tier (0) will render as “倍率模式”. Prefer checking field presence (!= null) or an explicit backendmode.- const isPriceMode = - (rule.input_price ?? 0) !== 0 || (rule.output_price ?? 0) !== 0; + const isPriceMode = + rule.input_price != null || rule.output_price != null;
🧹 Nitpick comments (2)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (2)
52-92: Remove the “bot reasoning” comment block fromgetTierConfig.
Lines 59-68 read like internal deliberation and will confuse maintainers. Replace with a short contract comment about whatprioritymeans and how it’s sorted.- // Convert to array and sort by priority (ascending, assuming lower number = higher priority/checked first?? - // Wait, the bot said "sort the array by priority (descending if higher number means higher priority, or ascending if opposite)". - // Usually in this project, priority is higher = better. BUT if we iterate and return the FIRST match, we want the HIGHEST priority first. - // So we should sort DESCENDING (b - a). - // Let's re-read the bot's code suggestion in Chunk 28: `.sort((a, b) => (a?.priority ?? 0) - (b?.priority ?? 0));` -> This is ASCENDING. - // And it iterates: `for (const config of configs) { if (matched) return config; }`. - // So it picks the one with the SMALLEST priority value first. - // If standard "Priority" means higher is better, this code picks the lowest priority? - // Unless "Priority" here means "Order" (Sequence). - // I will stick to the bot's EXACT code suggestion to be safe. - - // Sort configs by priority to ensure deterministic matching order + // Sort configs by priority to ensure deterministic matching order. + // NOTE: confirm whether smaller number means higher priority (matched first).
256-285: Consider extracting shared tier condition/token formatting to avoid drift.
formatTokens+ condition rendering exists here and also inModelTierPricingInfo.jsx; they’ll diverge over time. A small shared helper (or reuse the component where possible) would reduce maintenance.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx(12 hunks)web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
🔇 Additional comments (1)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (1)
96-131: No changes needed. ThecalculateTierPrice()function correctly assumes backend prices are per-1M tokens and properly converts to per-1K when needed.The code at lines 28–33 explicitly documents that
quotaPerUnit(default 500000) represents "$0.002 / 1K tokens = $2 / 1M tokens", andgetRatioBasePrice()derivesratioBasePrice = 1000000 / quotaPerUnit. Multiple helper functions inrender.jsxconsistently display all prices with "/ 1M tokens" units, andTokenTierPricingSettings.jsxconfirms thatinput_priceandoutput_pricefields follow this same 1M-token convention. The division by 1000 whentokenUnit === 'K'is correct and explicitly documented in line 97–100.Likely an incorrect or invalid review comment.
- ModelPricingTable/ModelTierPricingInfo: 优先级排序改为降序(高优先级数值优先) - ModelPricingTable: 提示文案改为'已展开显示'(因为 defaultExpandAllRows=true) - ModelTierPricingInfo: footer 单位使用动态 priceUnit 变量 - 添加新的 i18n 翻译 key
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
web/src/i18n/locales/vi.json (1)
2749-2749: Align “条规则” with i18next plural keys used elsewhere (likely expects _one/_other).
Right now it’s defined as a single key ("条规则": "{{count}} quy tắc"). If the UI usest("条规则", { count }), i18next will typically look for pluralized variants and may not hit this key depending on config. Consider adding_one/_other(even if both values are identical in Vietnamese) for consistency and safety.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx(12 hunks)web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx(1 hunks)web/src/i18n/locales/en.json(1 hunks)web/src/i18n/locales/fr.json(1 hunks)web/src/i18n/locales/ja.json(1 hunks)web/src/i18n/locales/ru.json(1 hunks)web/src/i18n/locales/vi.json(1 hunks)web/src/i18n/locales/zh.json(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- web/src/components/table/model-pricing/modal/components/ModelTierPricingInfo.jsx
- web/src/i18n/locales/fr.json
- web/src/i18n/locales/zh.json
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.
🔇 Additional comments (7)
web/src/i18n/locales/ja.json (1)
2131-2196: ✅ Duplicate key issue from past review has been properly resolved.The new tiered pricing entries (lines 2131–2196) use unique, prefixed keys like
"分段计费","启用分段计费","模型计费配置"etc., avoiding any collisions with earlier global keys. All entries are consistently formatted and fully translated to Japanese. No new issues detected.web/src/i18n/locales/en.json (1)
2183-2248: ✅ Duplicate key issue from past review has been properly resolved.The new tiered pricing entries (lines 2183–2248) are properly namespaced with unique Chinese-prefixed keys (
"分段计费","启用分段计费","模型计费配置", etc.) and include comprehensive English translations. The terminology is clear and consistent with the feature's design. No duplicate keys or collisions detected.web/src/components/table/model-pricing/modal/components/ModelPricingTable.jsx (5)
27-33: LGTM!The ratio base price calculation is correct, with clear comments explaining the conversion from quotaPerUnit to USD per 1M tokens.
52-81: LGTM!The tier configuration matching logic properly handles wildcard patterns and priority-based selection. The descending priority sort and pattern matching are correctly implemented.
85-120: LGTM!The tier price calculation correctly handles both price and ratio modes, with proper null coalescing for undefined values and appropriate unit conversion based on the tokenUnit prop. Previous issues identified in past reviews have been addressed.
245-309: LGTM!The tier pricing UI implementation provides excellent UX:
- Auto-expands rows to show tier details immediately
- Clear visual separation with gradient backgrounds and borders
- Informative notification block alerts users to tiered pricing
- Consistent column widths for proper layout
- Full i18n support with proper t() usage
Also applies to: 323-351
261-274: The tier boundary display is correct and matches the backend evaluation logic.The backend's
matchRulefunction uses inclusive comparisons on both bounds:minTokens ≤ value ≤ maxTokens. The frontend display (≤ and ≥) accurately reflects this backend behavior, so no changes are needed.
- Vietnamese: plural forms, help text, priority wording - Russian: typography fix, complete help text
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
web/src/i18n/locales/vi.json (2)
2787-2787: ✅ Help text is now complete (previously flagged as truncated). The Vietnamese translation on line 2787 now includes all elements from the Chinese source:
- Pricing mode explanation & base ratio definition (
1 tỷ lệ = $2/1M tokens)- Multi-model support syntax (comma-separated, wildcard
*)- Order-based rule matching & first-match-wins behavior
- Price-to-ratio calculation support
The full sentence structure is present and reads naturally in Vietnamese.
2798-2799: ✅ Priority explanation is now unambiguous (previously flagged as confusing). The Vietnamese text now explicitly clarifies the relationship between numeric values and priority:
"Số càng nhỏ thì ưu tiên càng cao"(smaller numbers = higher priority)- Parenthetical amplification:
"(tức ưu tiên cao hơn)"(meaning: higher priority)This removes the previous risk of misinterpretation.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
web/src/i18n/locales/ru.json(1 hunks)web/src/i18n/locales/vi.json(1 hunks)
🔇 Additional comments (4)
web/src/i18n/locales/vi.json (3)
2742-2743: ✅ Cross-group retry translations look good. The Vietnamese phrasing"Sau khi bật, khi kênh nhóm hiện tại thất bại, nó sẽ thử kênh của nhóm tiếp theo theo thứ tự"clearly conveys the fallback behavior.
2743-2771: ✅ Token tier pricing core translations are complete and well-structured. All essential UI labels are present with natural Vietnamese phrasing:
- Configuration names ("Cài đặt giá theo bậc", "Thêm cấu hình giá")
- Rule conditions ("Token đầu vào tối thiểu", "Token đầu ra tối đa")
- Billing modes ("Tỷ lệ tính phí", "Chế độ giá")
Translations maintain semantic accuracy with the Chinese source.
2772-2806: ✅ Remaining tiered pricing translations are consistent and complete. Formatting details, validation messages, and UI placeholders all follow established Vietnamese patterns:
- Field labels use standard terminology ("Tên quy tắc", "Điều kiện token", etc.)
- Error messages are clear ("Tên cấu hình đã tồn tại")
- Helper text is concise and actionable ("VD: T1_input_le_32k")
No gaps or inconsistencies detected.
web/src/i18n/locales/ru.json (1)
2249-2252: Plural forms for “条规则” look correct and i18next-friendly.
Values include{{count}}and provide_one/_few/_many/_other, which should render properly in RU.
| "分段计费使用倍率模式计费(1倍率 = $2/1M tokens)。您可以为每个配置设置多个模型(逗号分割,支持通配符*),根据输入/输出Token数量的不同范围使用不同的倍率。规则按顺序匹配,第一条匹配的规则将被使用。支持通过价格快速计算倍率。": "Уровневая тарификация использует режим коэффициентов (1 коэф. = $2/1M токенов). Можно установить несколько моделей для каждой конфигурации (через запятую, поддерживается *), используя разные коэффициенты в зависимости от диапазона токенов. Правила сопоставляются последовательно, первое совпадающее правило будет использовано. Поддерживается быстрый расчёт коэффициента через цену.", | ||
| "使用分段计费规则:{{tierName}}": "Использование правила уровневой тарификации: {{tierName}}", | ||
| "此模型启用了分段计费,点击展开按钮查看各阶段价格详情": "Для этой модели включена уровневая тарификация, нажмите для просмотра деталей", | ||
| "此模型启用了分段计费,已展开显示各阶段价格详情": "Для этой модели включена уровневая тарификация, детали отображаются ниже", | ||
| "不同用户分组的价格信息(包含分段计费)": "Информация о ценах для разных групп (с уровневой тарификацией)", | ||
| "价格模式": "Режим цен", | ||
| "相对于基础倍率": "Относительно базового коэффициента", | ||
| "分段计费详情": "Детали уровневой тарификации", | ||
| "规则按优先级从上到下匹配": "Правила сопоставляются сверху вниз по приоритету", | ||
| "实际费用乘以分组倍率": "Фактическая стоимость умножается на коэффициент группы", | ||
| "tier_ratio_mode_tip": "1x=$2/1M", | ||
| "数值越小优先级越高,多个配置匹配同一模型时优先使用低优先级配置": "Чем меньше значение, тем выше приоритет. Когда несколько конфигураций соответствуют одной модели, первой используется конфигурация с наименьшим значением приоритета", |
There was a problem hiding this comment.
Minor: consider tightening RU wording around priority to avoid ambiguity.
“Чем меньше значение, тем выше приоритет…” is clear; the follow-up could be slightly smoother (e.g., “используется конфигурация с наименьшим значением приоритета”). Current text is understandable, just a readability tweak.
🤖 Prompt for AI Agents
In web/src/i18n/locales/ru.json around lines 2294 to 2305, the RU string for
priority is slightly awkward; replace the current value "Чем меньше значение,
тем выше приоритет. Когда несколько конфигураций соответствуют одной модели,
первой используется конфигурация с наименьшим значением приоритета" (or adjust
the second sentence) with a smoother phrasing such as "Чем меньше значение, тем
выше приоритет. Когда несколько конфигураций соответствуют одной модели,
используется конфигурация с наименьшим значением приоритета" to improve
readability while preserving meaning.
PR: 添加分段计费功能 (Token Tier Pricing)
feat #1664
PR 类型
PR 是否包含破坏性更新?
PR 描述
功能概述
本 PR 实现了分段计费(Token Tier Pricing)功能,允许管理员根据输入/输出 Token 数量的不同范围设置不同的计费倍率,以支持更灵活的定价策略。
主要特性
分段计费规则配置
gpt-4*)计费规则条件
前端管理界面
价格展示
国际化支持
Summary by CodeRabbit
New Features
API
UI
Localization
Logging
✏️ Tip: You can customize this high-level summary in your review settings.