Skip to content

feat: claude 1h cache - #2155

Merged
Calcium-Ion merged 3 commits into
QuantumNous:mainfrom
seefs001:fix/claude-cache-1h
Nov 3, 2025
Merged

Calcium-Ion merged 3 commits into
QuantumNous:mainfrom
seefs001:fix/claude-cache-1h

Conversation

@seefs001

@seefs001 seefs001 commented Nov 3, 2025 •

Copy link
Copy Markdown
Collaborator

fix #2129

Summary by CodeRabbit

  • New Features
    • Added separate 5-minute and 1-hour cache-creation usage metrics for Claude.
    • Pricing now supports distinct 5m/1h cache-creation rates and shows per-interval cost breakdowns.
    • Usage logs and pricing UI updated to display time-based cache-creation details with new localized strings (en/fr/ja/ru/zh).

@coderabbitai

coderabbitai Bot commented Nov 3, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This 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

Cohort / File(s) Summary
DTO & Response Models
dto/claude.go, dto/openai_response.go
Add ClaudeCacheCreationUsage and new fields on ClaudeUsage (CacheCreation pointer, ClaudeCacheCreation5mTokens, ClaudeCacheCreation1hTokens) plus getters; add matching ClaudeCacheCreation5mTokens and ClaudeCacheCreation1hTokens fields to Usage in dto/openai_response.go.
Relay & Response Handling
relay/channel/claude/relay-claude.go
Populate new usage metrics ClaudeCacheCreation5mTokens and ClaudeCacheCreation1hTokens from ClaudeUsage getters in stream and non-stream flows; use total/getters where appropriate.
Price Calculation & Types
relay/helper/price.go, types/price_data.go
Introduce claudeCacheCreation1hMultiplier, compute separate 5m and 1h cache-creation ratios; add CacheCreation5mRatio and CacheCreation1hRatio to PriceData and include them in settings output.
Logging & Quota
service/log_info_generate.go, service/quota.go
Extend GenerateClaudeOtherInfo signature to accept 5m/1h cache tokens and ratios; update Claude quota logic to allocate/aggregate 5m and 1h cache-creation tokens and pass new values into logging output.
Frontend Rendering & Hooks
web/src/helpers/render.jsx, web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx, web/src/hooks/usage-logs/useUsageLogsData.jsx
Add parameters and propagate cacheCreationTokens5m, cacheCreationRatio5m, cacheCreationTokens1h, cacheCreationRatio1h through price renderers and Claude log renderers; implement conditional breakdowns for 5m/1h vs combined display.
Localization
web/src/i18n/locales/{en,fr,ja,ru,zh}.json
Add four new translation keys per locale for "cache creation" and "cache creation multiplier" at 5m and 1h intervals.

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)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25–30 minutes

  • Attention areas:
    • service/quota.go: token allocation and remaining-token handling across 5m/1h pools
    • relay/helper/price.go & types/price_data.go: multiplier derivation and PriceData propagation
    • web/src/helpers/render.jsx: correctness of conditional breakdown and all call-site updates
    • dto/claude.go getters: nil-safety and backward compatibility with existing CacheCreationInputTokens

Possibly related PRs

  • feat: auto分组 #1239 — touches pricing helpers and PriceData; may conflict with PriceData/ratio changes here.

Suggested reviewers

  • Calcium-Ion
  • creamlike1024

Poem

🐰
I hopped through tokens, five and sixty bright,
Split the cache in windows, tracked each little byte,
From Go to React I carried the tune,
Ratios and logs beneath the moon,
A tiny rabbit cheers the metrics' light! 🥕

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'feat: claude 1h cache' is directly related to the main objective of the changeset. The title clearly indicates a feature addition for Claude's 1-hour cache functionality. The changes across multiple files consistently implement support for 5-minute and 1-hour cache creation timing metrics for Claude, which aligns with the title's focus on 1h cache support.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 00782aa and c68c0d4.

📒 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.go
  • 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:

  • service/log_info_generate.go
  • relay/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, and cacheCreationRatio1h. 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分 and 1時間 to align with ja.json's existing time formatting patterns.

Comment thread dto/openai_response.go
Comment on lines +233 to +237

// claude cache 1h
ClaudeCacheCreation5mTokens int `json:"claude_cache_creation_5_m_tokens"`
ClaudeCacheCreation1hTokens int `json:"claude_cache_creation_1_h_tokens"`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ 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 tsx

Length 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 json

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

Suggested change
// 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.

Comment on lines +1094 to +1104
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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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.

Comment on lines 1771 to +1783
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.75 correctly 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

📥 Commits

Reviewing files that changed from the base of the PR and between c68c0d4 and de18599.

📒 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 PriceData struct 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 !usePrice branch (relay/helper/price.go:84-86) and are used only within the !relayInfo.PriceData.UsePrice guard in service/quota.go:274-279. This prevents any unintended calculations with zero values when UsePrice is true.

Minor note: Line 85 contains a Chinese comment; consider aligning with your project's documentation standards if English is preferred.

@Calcium-Ion
Calcium-Ion merged commit df2ee64 into QuantumNous:main Nov 3, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Feb 22, 2026
ennnnny pushed a commit to ennnnny/new-api that referenced this pull request Mar 17, 2026
* feat: claude 1h cache

* feat: claude 1h cache

* fix price
@coderabbitai coderabbitai Bot mentioned this pull request Apr 6, 2026
6 of 9 tasks
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
* feat: claude 1h cache

* feat: claude 1h cache

* fix price
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
* feat: claude 1h cache

* feat: claude 1h cache

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

claude-sonnet-4-5-20250929计费问题

2 participants