Repository navigation
feat: claude 1h cache - #2155
Conversation
WalkthroughThis PR adds time-windowed Claude cache-creation metrics (5m and 1h), propagates them through DTOs, relay pricing, quota and logging, extends PriceData and pricing helpers, updates frontend rendering and localization, and surfaces the new fields in usage and response structures. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Relay as Relay (claude)
participant Price as Price Helper
participant Quota as Quota Service
participant Logger as Log Generator
participant Frontend
Note over Client,Relay: request with Claude activity
Client->>Relay: send Claude response payload
Relay->>Relay: extract ClaudeUsage (includes CacheCreation 5m/1h)
Relay->>Price: compute ratios (5m & 1h) and prices
Relay->>Quota: update quotas using 5m/1h tokens & ratios
Relay->>Logger: GenerateClaudeOtherInfo including 5m/1h fields
Relay->>Frontend: emit usage & price data (includes 5m/1h)
Frontend->>Frontend: render breakdown conditionally (5m,1h,combined)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25–30 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ 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: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
relay/channel/claude/relay-claude.go (1)
740-747: Non‑stream path still reads legacy CacheCreationInputTokens; use aggregated getters.For consistency with the stream path and the new split 5m/1h metrics, replace direct field access with the total getter.
Apply:
- claudeInfo.Usage.PromptTokensDetails.CachedCreationTokens = claudeResponse.Usage.CacheCreationInputTokens + claudeInfo.Usage.PromptTokensDetails.CachedCreationTokens = claudeResponse.Usage.GetCacheCreationTotalTokens()Also keep the newly added:
claudeInfo.Usage.ClaudeCacheCreation5mTokens = claudeResponse.Usage.GetCacheCreation5mTokens() claudeInfo.Usage.ClaudeCacheCreation1hTokens = claudeResponse.Usage.GetCacheCreation1hTokens()
🧹 Nitpick comments (3)
web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx (1)
554-557: Prefer nullish coalescing for ratios to avoid treating 0 as falsy.Using “||” will fall back when ratio === 0. Use “??” to only fallback on null/undefined.
- other.cache_creation_ratio_5m || other.cache_creation_ratio || 1.0, + (other.cache_creation_ratio_5m ?? other.cache_creation_ratio) ?? 1.0, - other.cache_creation_tokens_1h || 0, - other.cache_creation_ratio_1h || other.cache_creation_ratio || 1.0, + other.cache_creation_tokens_1h || 0, + (other.cache_creation_ratio_1h ?? other.cache_creation_ratio) ?? 1.0,And in the OpenAI branch keep zeros/1.0 as-is.
Also applies to: 572-576
web/src/hooks/usage-logs/useUsageLogsData.jsx (2)
364-367: Same: use nullish coalescing for cache‑creation ratios.Avoid “||” on numeric ratios.
- other.cache_creation_ratio_5m || other.cache_creation_ratio || 1.0, + (other.cache_creation_ratio_5m ?? other.cache_creation_ratio) ?? 1.0, - other.cache_creation_tokens_1h || 0, - other.cache_creation_ratio_1h || other.cache_creation_ratio || 1.0, + other.cache_creation_tokens_1h || 0, + (other.cache_creation_ratio_1h ?? other.cache_creation_ratio) ?? 1.0,
436-440: And here for renderClaudeModelPrice call.Mirror the same “??” change to keep semantics consistent.
- other.cache_creation_ratio_5m || other.cache_creation_ratio || 1.0, + (other.cache_creation_ratio_5m ?? other.cache_creation_ratio) ?? 1.0, - other.cache_creation_tokens_1h || 0, - other.cache_creation_ratio_1h || other.cache_creation_ratio || 1.0, + other.cache_creation_tokens_1h || 0, + (other.cache_creation_ratio_1h ?? other.cache_creation_ratio) ?? 1.0,
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (15)
dto/claude.go(1 hunks)dto/openai_response.go(1 hunks)relay/channel/claude/relay-claude.go(2 hunks)relay/helper/price.go(4 hunks)service/log_info_generate.go(1 hunks)service/quota.go(3 hunks)types/price_data.go(2 hunks)web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx(2 hunks)web/src/helpers/render.jsx(10 hunks)web/src/hooks/usage-logs/useUsageLogsData.jsx(2 hunks)web/src/i18n/locales/en.json(2 hunks)web/src/i18n/locales/fr.json(1 hunks)web/src/i18n/locales/ja.json(2 hunks)web/src/i18n/locales/ru.json(1 hunks)web/src/i18n/locales/zh.json(2 hunks)
🧰 Additional context used
🧠 Learnings (3)
📚 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:
service/log_info_generate.gorelay/helper/price.go
📚 Learning: 2025-08-05T17:14:17.246Z
Learnt from: neotf
Repo: QuantumNous/new-api PR: 1511
File: setting/ratio_setting/model_ratio.go:118-123
Timestamp: 2025-08-05T17:14:17.246Z
Learning: Claude models handle "-thinking" variants differently from Gemini models. For Claude models, only the base model (without "-thinking") gets an entry in defaultModelRatio map. The "-thinking" variants rely on the Claude relay handler stripping the suffix using strings.TrimSuffix(textRequest.Model, "-thinking") before looking up the ratio, so they automatically use the base model's ratio.
Applied to files:
service/log_info_generate.gorelay/helper/price.go
📚 Learning: 2025-06-18T12:20:25.779Z
Learnt from: neotf
Repo: QuantumNous/new-api PR: 1120
File: service/quota.go:0-0
Timestamp: 2025-06-18T12:20:25.779Z
Learning: For OpenRouter integration: cacheTokens returned from upstream always belong to [0, promptTokens], meaning cacheTokens will never exceed the original promptTokens value. This constraint ensures that operations like `promptTokens -= cacheTokens` will not result in negative values.
Applied to files:
service/quota.go
🧬 Code graph analysis (3)
web/src/hooks/usage-logs/useUsageLogsData.jsx (1)
web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx (1)
other(176-176)
relay/channel/claude/relay-claude.go (1)
dto/openai_response.go (1)
Usage(222-240)
service/quota.go (1)
types/price_data.go (2)
PriceData(11-27)GroupRatioInfo(5-9)
🔇 Additional comments (7)
web/src/i18n/locales/ru.json (1)
1537-1540: LGTM – keys and placeholders match conventions.Russian strings correctly mirror the new 5m/1h cache‑creation entries; units and placeholders are intact and consistent with other locales.
web/src/i18n/locales/en.json (1)
1519-1522: LGTM – entries added correctly and consistently.Keys, units (5m/1h), and placeholders align with the rest of the locale set.
relay/channel/claude/relay-claude.go (1)
595-601: Stream path uses aggregated cache‑creation tokens — good.web/src/i18n/locales/zh.json (1)
1510-1513: All four cache-creation keys verified with parity across en/fr/ru locales.The verification confirms all four keys exist with matching placeholders across the requested locales:
- Both "缓存创建" and "缓存创建倍率" variants present for 5m and 1h in en.json, fr.json, and ru.json
- Placeholder variables {{cacheCreationRatio5m}} and {{cacheCreationRatio1h}} correctly maintained
types/price_data.go (1)
18-20: Fields are correctly wired into pricing — verified.CacheCreation5mRatio and CacheCreation1hRatio are:
- Populated by relay/helper/price.go (lines 127–128)
- Used actively in quota calculation (service/quota.go:276–277)
- Included in the renderer (types/price_data.go:36) and consume logs
Not silent no-ops; they have direct multiplicative impact on pricing.
service/log_info_generate.go (1)
94-111: All callers correctly updated — verification passed.Only one caller exists (
service/quota.go:333), and it has been properly updated with all new parameters in the correct order:cacheCreationTokens5m,cacheCreationRatio5m,cacheCreationTokens1h, andcacheCreationRatio1h. The backward-incompatible signature change is consistent across the codebase.web/src/i18n/locales/ja.json (1)
1519-1522: Consider standardizing time units in Japanese to full-width characters for consistency with existing entries.The parity check confirms the half-width format (
1h,5m) is used consistently across all locales (zh, en, fr, ru, ja). However, existing Japanese entries use full-width equivalents (1時間,時間, etc.). Choose either:
- Keep half-width for cross-locale parity in technical labels, or
- Adopt
5分and1時間to align with ja.json's existing time formatting patterns.
|
|
||
| // claude cache 1h | ||
| ClaudeCacheCreation5mTokens int `json:"claude_cache_creation_5_m_tokens"` | ||
| ClaudeCacheCreation1hTokens int `json:"claude_cache_creation_1_h_tokens"` | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
🧩 Analysis chain
Align JSON tags with expected “5m/1h” keys; add omitempty; clarify comment.
Using 5_m / 1_h in tags is likely mismatched with upstream/UI naming (5m / 1h). This can silently drop fields on unmarshal and skew usage/cost. Also add omitempty to avoid emitting zeros, and fix the comment scope.
Apply:
- // claude cache 1h
- ClaudeCacheCreation5mTokens int `json:"claude_cache_creation_5_m_tokens"`
- ClaudeCacheCreation1hTokens int `json:"claude_cache_creation_1_h_tokens"`
+ // Claude cache creation windows (5m / 1h)
+ ClaudeCacheCreation5mTokens int `json:"claude_cache_creation_5m_tokens,omitempty"`
+ ClaudeCacheCreation1hTokens int `json:"claude_cache_creation_1h_tokens,omitempty"`Run to verify naming consistency across the repo and spot consumers:
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Search for existing consumers of claude cache creation fields (any 5m/1h variants)"
rg -n -C2 -S 'claude_cache_creation_([0-9]+_?m|[0-9]+_?h)_tokens' --type go --type ts --type tsx
echo "Search UI/backend for 5m/1h cache-creation metrics"
rg -n -C2 -S 'cacheCreation.*(5m|1h)' --type ts --type tsx --type go
echo "Locate any remaining 5_m/1_h JSON references"
rg -n -C2 -S '"claude_cache_creation_5_m_tokens"|"claude_cache_creation_1_h_tokens"' --type go --type ts --type tsxLength of output: 110
Let me retry with valid file types:Now I understand—tsx is not a recognized type. I'll retry with valid file types. Let me search without specifying file types or use glob patterns instead:
[/run_scripts]
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Search for claude_cache_creation fields (any 5m/1h variants) ==="
rg -n -C2 -S 'claude_cache_creation.*tokens' --type go
echo ""
echo "=== Search in JS/TS files for cacheCreation references ==="
rg -n -C2 -S 'cacheCreation' --type js --type json
echo ""
echo "=== Broaden search: Look for any 5_m or 1_h in JSON context ==="
rg -n -C2 -S '5_m|1_h' --type go --type jsonLength of output: 35508
Let me search for Claude API client code and response handling to confirm if these fields are actually populated from an external API:
Let me search specifically for Claude's cache creation windows documentation:
Fix JSON tag naming for cache creation window fields; add omitempty; clarify comment.
Claude API returns usage with cache_creation_input_tokens and cache_read_input_tokens fields, following snake_case convention without underscores between number and unit. The current Go JSON tags use 5_m_tokens and 1_h_tokens (with underscores), which will fail to unmarshal if Claude's API returns 5m_tokens and 1h_tokens. This silently drops fields on unmarshal and skews token counts. Also add omitempty to reduce noise when zero-valued.
- // claude cache 1h
- ClaudeCacheCreation5mTokens int `json:"claude_cache_creation_5_m_tokens"`
- ClaudeCacheCreation1hTokens int `json:"claude_cache_creation_1_h_tokens"`
+ // Claude cache creation windows (5m / 1h)
+ ClaudeCacheCreation5mTokens int `json:"claude_cache_creation_5m_tokens,omitempty"`
+ ClaudeCacheCreation1hTokens int `json:"claude_cache_creation_1h_tokens,omitempty"`Verify the same naming issue exists in dto/claude.go lines 519–520 and apply the same fix there.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // claude cache 1h | |
| ClaudeCacheCreation5mTokens int `json:"claude_cache_creation_5_m_tokens"` | |
| ClaudeCacheCreation1hTokens int `json:"claude_cache_creation_1_h_tokens"` | |
| // Claude cache creation windows (5m / 1h) | |
| ClaudeCacheCreation5mTokens int `json:"claude_cache_creation_5m_tokens,omitempty"` | |
| ClaudeCacheCreation1hTokens int `json:"claude_cache_creation_1h_tokens,omitempty"` |
🤖 Prompt for AI Agents
In dto/openai_response.go around lines 233–237 the JSON tags for Claude cache
creation window fields use `5_m_tokens` and `1_h_tokens` which won't match the
API's snake_case `5m_tokens`/`1h_tokens`; change the tags to `5m_tokens` and
`1h_tokens`, add `omitempty` to both tags, and update the comment to clarify
these are cache-creation window token counts; apply the same tag/name +
omitempty fixes to dto/claude.go at lines ~519–520 to keep both DTOs consistent
with the Claude API.
| parts.push( | ||
| i18next.t( | ||
| '缓存创建: 5m {{cacheCreationRatio5m}} / 1h {{cacheCreationRatio1h}}', | ||
| ), | ||
| ); | ||
| } else if (shouldShowCacheCreation5m) { | ||
| parts.push(i18next.t('缓存创建: 5m {{cacheCreationRatio5m}}')); | ||
| } else if (shouldShowCacheCreation1h) { | ||
| parts.push(i18next.t('缓存创建: 1h {{cacheCreationRatio1h}}')); | ||
| } | ||
| } else if (shouldShowLegacyCacheCreation) { |
There was a problem hiding this comment.
Add a proper translation key for the 5 m/1 h cache string
The new call to i18next.t('缓存创建: 5m {{cacheCreationRatio5m}} / 1h {{cacheCreationRatio1h}}', …) has no corresponding entry in the locale files (only the singular 5 m and 1 h keys were added). In non-Chinese locales this will now render the raw Chinese key, degrading the UX. Please add localized strings for this combined message (or reuse existing keys) across all supported locales.
🤖 Prompt for AI Agents
In web/src/helpers/render.jsx around lines 1094 to 1104 the call uses a raw
Chinese string as the i18next key for the combined "5m / 1h" cache creation
message, which has no entries in the locale files and will show the raw text in
other locales; add a proper translation key (for example "cacheCreation.both" or
reuse existing singular keys to build the combined string) to all supported
locale files with matching interpolation tokens {{cacheCreationRatio5m}} and
{{cacheCreationRatio1h}}, and update the code to call i18next.t with that key
(or compose the translated singular keys) so all locales render correctly.
| const nonCachedTokens = inputTokens; | ||
| const effectiveInputTokens = | ||
| nonCachedTokens + | ||
| cacheTokens * cacheRatio + | ||
| cacheCreationTokens * cacheCreationRatio; | ||
| cacheCreationTokens * cacheCreationRatio + | ||
| cacheCreationTokens5m * cacheCreationRatio5m + | ||
| cacheCreationTokens1h * cacheCreationRatio1h; | ||
|
|
||
| let price = | ||
| (effectiveInputTokens / 1000000) * inputRatioPrice * groupRatio + | ||
| (completionTokens / 1000000) * completionRatioPrice * groupRatio; | ||
|
|
||
| const inputUnitPrice = inputRatioPrice * rate; |
There was a problem hiding this comment.
Fix double counting in effectiveInputTokens
effectiveInputTokens now adds the full inputTokens, then adds cache tokens (5 m / 1 h / legacy) again after multiplying by their ratios. Because cacheCreationTokens already includes the 5 m and 1 h amounts, this double counts those tokens, inflating the displayed price even though quota calculation uses the correct numbers. Please mirror the quota math: subtract the cache-related tokens from the raw prompt total, then add each bucket back once with the appropriate ratio (and guard against negative remainders). A possible fix:
- const nonCachedTokens = inputTokens;
- const effectiveInputTokens =
- nonCachedTokens +
- cacheTokens * cacheRatio +
- cacheCreationTokens * cacheCreationRatio +
- cacheCreationTokens5m * cacheCreationRatio5m +
- cacheCreationTokens1h * cacheCreationRatio1h;
+ const basePromptTokens =
+ inputTokens - cacheTokens - cacheCreationTokens;
+ const remainingCacheCreationTokens =
+ cacheCreationTokens - cacheCreationTokens5m - cacheCreationTokens1h;
+ const effectiveInputTokens =
+ Math.max(basePromptTokens, 0) +
+ cacheTokens * cacheRatio +
+ cacheCreationTokens5m * cacheCreationRatio5m +
+ cacheCreationTokens1h * cacheCreationRatio1h +
+ Math.max(remainingCacheCreationTokens, 0) * cacheCreationRatio;🤖 Prompt for AI Agents
In web/src/helpers/render.jsx around lines 1771 to 1783, effectiveInputTokens is
double-counting cache tokens because it adds inputTokens (which already includes
cacheCreationTokens and its 5m/1h parts) and then adds those cache buckets again
multiplied by ratios; change the computation to mirror quota math: compute
rawPrompt = inputTokens, compute nonCachePrompt = Math.max(0, rawPrompt -
cacheCreationTokens) (or subtract the sum of cache buckets), then set
effectiveInputTokens = nonCachePrompt + cacheTokens * cacheRatio +
cacheCreationTokens * cacheCreationRatio + cacheCreationTokens5m *
cacheCreationRatio5m + cacheCreationTokens1h * cacheCreationRatio1h, ensuring
you use Math.max(0, ...) where appropriate to avoid negative remainders so
pricing matches quota calculation.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
relay/helper/price.go (1)
16-17: Consider documenting the pricing values for clarity.The constant calculation
6 / 3.75correctly yields 1.6, but the meaning of these specific values isn't immediately clear. Consider adding a brief comment explaining what 6 and 3.75 represent (e.g., "// 1h cache: $6.00 per MTok, 5m cache: $3.75 per MTok" or similar).
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
relay/channel/claude/relay-claude.go(2 hunks)relay/helper/price.go(4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- relay/channel/claude/relay-claude.go
🧰 Additional context used
🧠 Learnings (2)
📚 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/helper/price.go
📚 Learning: 2025-08-05T17:14:17.246Z
Learnt from: neotf
Repo: QuantumNous/new-api PR: 1511
File: setting/ratio_setting/model_ratio.go:118-123
Timestamp: 2025-08-05T17:14:17.246Z
Learning: Claude models handle "-thinking" variants differently from Gemini models. For Claude models, only the base model (without "-thinking") gets an entry in defaultModelRatio map. The "-thinking" variants rely on the Claude relay handler stripping the suffix using strings.TrimSuffix(textRequest.Model, "-thinking") before looking up the ratio, so they automatically use the base model's ratio.
Applied to files:
relay/helper/price.go
🔇 Additional comments (3)
relay/helper/price.go (3)
59-60: LGTM!Variable declarations are clear and follow existing naming conventions.
127-128: LGTM!The new cache creation ratio fields are properly added to the
PriceDatastruct with clear naming and logical positioning.
84-86: Code logic is correct; downstream handling properly guards against zero values.Verification confirms that the implementation is sound. The new ratios (
CacheCreation5mRatio,CacheCreation1hRatio) are assigned only in the!usePricebranch (relay/helper/price.go:84-86) and are used only within the!relayInfo.PriceData.UsePriceguard in service/quota.go:274-279. This prevents any unintended calculations with zero values whenUsePriceis true.Minor note: Line 85 contains a Chinese comment; consider aligning with your project's documentation standards if English is preferred.
* feat: claude 1h cache * feat: claude 1h cache * fix price
* feat: claude 1h cache * feat: claude 1h cache * fix price
* feat: claude 1h cache * feat: claude 1h cache * fix price
fix #2129
Summary by CodeRabbit