Skip to content

fix: 修复 Anthropic 渠道缓存计费错误 - #2477

Merged
Calcium-Ion merged 1 commit into
QuantumNous:mainfrom
1420970597:fix/anthropic-cache-billing
Dec 24, 2025
Merged

Calcium-Ion merged 1 commit into
QuantumNous:mainfrom
1420970597:fix/anthropic-cache-billing

Conversation

@1420970597

@1420970597 1420970597 commented Dec 20, 2025 •

Copy link
Copy Markdown
Contributor

fix #2420

问题描述

当使用 Anthropic 渠道通过 /v1/chat/completions 端点调用且启用缓存功能时, 计费逻辑错误地减去了缓存 tokens,导致严重的计费错误。
image

根本原因

不同 API 的 prompt_tokens 定义不同:

  • Anthropic API: input_tokens 字段已经是纯输入 tokens(不包含缓存)
  • OpenAI API: prompt_tokens 字段包含所有 tokens(包含缓存)
  • OpenRouter API: prompt_tokens 字段包含所有 tokens(包含缓存)

当前 postConsumeQuota 函数对所有渠道都减去缓存 tokens,这对 Anthropic 渠道是错误的,因为其 input_tokens 已经不包含缓存。

修复方案

在 relay/compatible_handler.go 的 postConsumeQuota 函数中,添加渠道类型判断:

if relayInfo.ChannelType != constant.ChannelTypeAnthropic {
    baseTokens = baseTokens.Sub(dCacheTokens)
}

只对非 Anthropic 渠道减去缓存 tokens。

影响分析

✅ 不受影响的场景

  1. 无缓存调用(所有渠道)

    • cache_tokens = 0
    • 减去 0 = 不减去
    • 结果:完全一致
  2. OpenAI/OpenRouter 渠道 + 缓存

    • 继续减去缓存(因为 ChannelType != Anthropic)
    • 结果:完全一致
  3. Anthropic 渠道 + /v1/messages 端点

    • 使用 PostClaudeConsumeQuota(不修改)
    • 结果:完全不受影响

✅ 修复的场景

  1. Anthropic 渠道 + /v1/chat/completions + 缓存
    • 修复前:错误地减去缓存,导致出现负数
    • 修复后:不减去缓存,计费正确

Summary by CodeRabbit

  • Bug Fixes
    • Corrected cache token deduction handling for Anthropic-channel requests when pricing calculations are disabled.

✏️ Tip: You can customize this high-level summary in your review settings.

## 问题描述

当使用 Anthropic 渠道通过 `/v1/chat/completions` 端点调用且启用缓存功能时,
计费逻辑错误地减去了缓存 tokens,导致严重的收入损失(94.5%)。

## 根本原因

不同 API 的 `prompt_tokens` 定义不同:

- **Anthropic API**: `input_tokens` 字段已经是纯输入 tokens(不包含缓存)
- **OpenAI API**: `prompt_tokens` 字段包含所有 tokens(包含缓存)
- **OpenRouter API**: `prompt_tokens` 字段包含所有 tokens(包含缓存)

当前 `postConsumeQuota` 函数对所有渠道都减去缓存 tokens,这对 Anthropic
渠道是错误的,因为其 `input_tokens` 已经不包含缓存。

## 修复方案

在 `relay/compatible_handler.go` 的 `postConsumeQuota` 函数中,添加渠道类型判断:

```go
if relayInfo.ChannelType != constant.ChannelTypeAnthropic {
    baseTokens = baseTokens.Sub(dCacheTokens)
}
```

只对非 Anthropic 渠道减去缓存 tokens。

## 影响分析

### ✅ 不受影响的场景

1. **无缓存调用**(所有渠道)
   - cache_tokens = 0
   - 减去 0 = 不减去
   - 结果:完全一致

2. **OpenAI/OpenRouter 渠道 + 缓存**
   - 继续减去缓存(因为 ChannelType != Anthropic)
   - 结果:完全一致

3. **Anthropic 渠道 + /v1/messages 端点**
   - 使用 PostClaudeConsumeQuota(不修改)
   - 结果:完全不受影响

### ✅ 修复的场景

4. **Anthropic 渠道 + /v1/chat/completions + 缓存**
   - 修复前:错误地减去缓存,导致 94.5% 收入损失
   - 修复后:不减去缓存,计费正确

## 验证数据

以实际记录 143509 为例:

| 项目 | 修复前 | 修复后 | 差异 |
|------|--------|--------|------|
| Quota | 10,489 | 191,330 | +180,841 |
| 费用 | ¥0.020978 | ¥0.382660 | +¥0.361682 |
| 收入恢复 | - | - | **+1724.1%** |

## 测试建议

1. 测试 Anthropic 渠道 + 缓存场景
2. 测试 OpenAI 渠道 + 缓存场景(确保不受影响)
3. 测试无缓存场景(确保不受影响)

## 相关 Issue

修复 Anthropic 渠道使用 prompt caching 时的计费错误。
@coderabbitai

coderabbitai Bot commented Dec 20, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Modified postConsumeQuota function in compatible_handler.go to skip cache token deductions (dCacheTokens and dCachedCreationTokens) when UsePrice is false for Anthropic-channel requests. Deductions are only applied for non-Anthropic channel types.

Changes

Cohort / File(s) Change Summary
Token deduction logic
relay/compatible_handler.go
Modified postConsumeQuota to conditionally skip baseTokens reduction by cache-related deductions for Anthropic channels when UsePrice is false

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

  • Verify the channel type check logic is correct
  • Confirm Anthropic-specific behavior is intentional and properly motivated
  • Ensure no unintended side effects from conditional deduction skipping

Poem

🐰 A token dance, refined with care,
For Anthropic's special channel fare,
Cache deductions now spare the way,
When prices rest and logic plays! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: fixing Anthropic channel cache billing errors by conditionally skipping cache token deductions.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ 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.

@Calcium-Ion
Calcium-Ion merged commit 0b1a562 into QuantumNous:main Dec 24, 2025
ennnnny pushed a commit to ennnnny/new-api that referenced this pull request Mar 17, 2026
…he-billing

fix: 修复 Anthropic 渠道缓存计费错误
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
…he-billing

fix: 修复 Anthropic 渠道缓存计费错误
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
…he-billing

fix: 修复 Anthropic 渠道缓存计费错误
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.

计费有问题authropic端点的模型使用openai请求会导致计费出错

3 participants