new-api icon indicating copy to clipboard operation
new-api copied to clipboard

feat(claude): support /v1/messages/count_tokens with local estimation

Open daymade opened this issue 7 months ago • 6 comments

⚠️ 提交说明 / PR Notice

📝 变更描述 / Description

实现 Anthropic /v1/messages/count_tokens 端点的本地估算,避免 Claude SDK / CLI 在该端点 404 时退化为发送 max_tokens=1 的伪请求。

真实事故场景:单个 Claude Code Desktop session 在一分钟内对同一上游 channel 发出 250 个伪 probe 请求(每个请求体 ~53KB,全是 tool schema 但 max_tokens=1),打爆上游 RPM 配额,导致同 channel 上其他用户在 ~2 分钟内收到 429。本地估算端点解决根因:SDK 拿到 200 + 一个合理的 input_tokens 数字就不会 fallback。

实现要点:

  • 路由直接挂在 relayV1Router 上而不是 httpRouter,跳过 middleware.Distribute()——这与 Anthropic 规范一致(count_tokens 不路由到上游、不消费配额)
  • 估算复用项目已有的 ClaudeRequest.GetTokenCountMeta() + EstimateTokenByModel(),与 /v1/messages 实际计费的 tokenizer 一致
  • 一个小 helper normalizeRequestTools() 修了 dto.ProcessTools 在收到 raw map[string]any tool 时静默丢弃的 latent bug——CLI probe 体里 80%+ 的字节都是 tool schema,不修这个 estimate 会严重偏低
  • 图片 token 暂不计入(需要 RelayInfo + http.Request context,本路由刻意没有);CLI probe 不带图片,不影响本 PR 解决的失败场景

🚀 变更类型 / Type of change

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

🔗 关联任务 / Related Issue

  • Closes #1694
  • Closes #2847
  • Closes #1979

参考 #2384(已 close 未 merge)。本 PR 与之相比:不引入新 RelayFormat enum、不改 adaptor、不改 distributor、不引入 autoban 旁路。改动面只有一条新路由 + 一个 controller + 一个 estimator,对所有未触达 /v1/messages/count_tokens 的代码路径零影响。

✅ 提交前检查项 / Checklist

  • [x] 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • [x] 非重复提交: 已搜索现有 Issues / PRs,#1694 / #2847 / #1979 / #2384 全部确认未解决。
  • [ ] Bug fix 说明: 此 PR 不是 bug fix。
  • [x] 变更理解: 已理解 httpRouter 中间件链含 Distribute(),刻意挂到 relayV1Router 上避开。
  • [x] 范围聚焦: 仅 4 个文件 +276 行;diff 中无 fork CI / 个人配置等无关改动。
  • [x] 本地验证: go test ./service/ -run 'TestEstimateClaude|TestNormalizeRequestTools' -v 全部通过;go build ./... 通过;本地 curl 实测端点返回正确 shape。
  • [x] 安全合规: 无凭据;遵循项目的 typed error helper(types.ClaudeError)+ body parser(common.UnmarshalBodyReusable)。

📸 运行证明 / Proof of Work

1. 单元测试 (12 cases passed)

$ go test ./service/ -run 'TestEstimateClaude|TestNormalizeRequestTools' -v
=== RUN   TestEstimateClaudeInputTokens
    --- PASS: empty messages (0.00s)                                  → 0
    --- PASS: single short user message (0.00s)                       → 4
    --- PASS: string system + user (0.00s)                            → 9
    --- PASS: CLI-probe shape: trivial message + bash tool schema     → 43
    --- PASS: system as array of text blocks (0.00s)                  → 12
    --- PASS: CJK content (0.00s)                                     → 20
    --- PASS: tool_use block on assistant turn (0.00s)                → 10
    --- PASS: tool_result block on user turn (0.00s)                  → 9
    --- PASS: web-search tool (distinguished by type field)           → 7
    --- PASS: tools array with already-typed entries                  → 18
=== RUN   TestEstimateClaudeInputTokens_NilSafety       — PASS (2 cases)
=== RUN   TestNormalizeRequestTools                     — PASS (3 cases)
PASS    ok  github.com/QuantumNous/new-api/service  0.6s

2. 端到端: 不带 PR 时 SDK 行为 (实测自我们生产环境的事故)

CLI 检测到 /v1/messages/count_tokens 返 404,退化为发送伪请求到 /v1/messages。截取一个真实的 53KB 伪请求体(已脱敏,源自我们的 OSS 归档):

{
  "model": "claude-haiku-4-5-20251001",
  "max_tokens": 1,
  "messages": [{"role": "user", "content": "count"}],
  "tools": [
    /* 18 个完整 tool schema,~52KB,含 Bash / AskUserQuestion / ... */
  ]
}

请求头 user-agent: claude-cli/2.1.111 (external, claude-desktop-3p, agent-sdk/0.2.111)。同一 device_id + session_id 在 60 秒内连发 250 个,149 个被上游返 429 rate limit reached for RPM。

3. 带 PR 时端点行为 (实测自本地 build)

$ curl -sX POST http://127.0.0.1:3000/v1/messages/count_tokens \
    -H "Authorization: Bearer sk-..." \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d @cli-probe-body.json
{"input_tokens":43}

$ # SDK 接受 200,停止发送伪请求

错误路径 (malformed body):

$ curl -sX POST http://127.0.0.1:3000/v1/messages/count_tokens \
    -H "Authorization: Bearer sk-..." \
    -H "content-type: application/json" \
    -d 'not json'
{"type":"error","error":{"type":"invalid_request_error","message":"invalid JSON body: ..."}}

维护者可能的问题 / Anticipated reviewer questions

Q: 为什么不直接转发到上游? A: 大部分 Claude 兼容上游(Qiniu QNAIGC / OpenRouter / 等)自己也没实现这个端点 (实测 Qiniu 返 404)。即使是 Anthropic 官方端点,虽免费但仍占 RPM 配额,pass-through 不解决我们这个 PR 要解的问题。

Q: 为什么不用真 tokenizer (tiktoken / anthropic-tokenizer)? A: 项目已有 EstimateTokenByModel(model, text) 带 Claude-tuned multipliers (Word 1.13, CJK 1.21, MathSymbol 4.52, ...),用在 service/token_counter.go 等多处。本 PR 不引入新依赖,复用已有实现,估算与 /v1/messages 自身计费一致。

Q: normalizeRequestTools 是否应该改 dto.ProcessTools 而不是在 estimator 自己 normalize? A: 改 ProcessTools 是更彻底的 fix,但会影响所有 caller(distributor / handler / 其他 future code paths)的行为,scope 太大、回归风险也大。本 PR 只改自己 reach 到的代码,把 latent bug 在 estimator 边界处兜住。如果维护者倾向把 normalize 提到 ProcessTools,欢迎反馈,我可以再开一个 PR 单独处理。

Q: 图片 token 不算合理吗? A: Anthropic 规范说 count_tokens 应当包含图片。我们权衡的是:(1) getImageToken 需要 RelayInfo + http.Request,本路由刻意不走 channel pipeline;(2) 触发本 PR 的 CLI probe 失败模式不带图片;(3) 真要加图片可后续 PR,需要把 image-token 计算从 service/token_counter.go 中抽成 standalone helper。

Summary by CodeRabbit

  • New Features
    • Added POST /v1/messages/count_tokens to return an estimated input-token count for Claude-style messages.
    • Added a local token estimator that normalizes diverse message shapes and tool representations (including web-search variants) before estimating.
  • Tests
    • Added comprehensive tests for estimator accuracy, tool normalization, routing of web-search vs non-web-search tools, and nil-safety.

Review Change Stack

daymade avatar Apr 24 '26 12:04 daymade

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 19e8d99b-6354-4923-b073-6582ea8a41b4

📥 Commits

Reviewing files that changed from the base of the PR and between 5a9421fc293096b3c6904a3b112662dcdbb4c62a and 7a657443f7ea2baf0df752f1ecdc81b3ef2529f5.

📒 Files selected for processing (4)
  • controller/claude_count_tokens.go
  • router/relay-router.go
  • service/claude_token_estimator.go
  • service/claude_token_estimator_test.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • controller/claude_count_tokens.go
  • router/relay-router.go
  • service/claude_token_estimator_test.go
  • service/claude_token_estimator.go

Walkthrough

Adds a Claude-compatible POST /v1/messages/count_tokens endpoint with a Gin handler and relay route, a local estimator that normalizes request tools and computes input token estimates, and unit tests for estimator and normalization behavior.

Changes

Claude count_tokens

Layer / File(s) Summary
HTTP handler and route
controller/claude_count_tokens.go, router/relay-router.go
New Gin handler ClaudeCountTokens and relay route POST /v1/messages/count_tokens. Handler unmarshals into dto.ClaudeRequest, returns 400 with types.ClaudeError on invalid JSON, otherwise calls estimator and returns { "input_tokens": N }.
Estimator core
service/claude_token_estimator.go
Added EstimateClaudeInputTokens(req *dto.ClaudeRequest) int: nil-safe, obtains combined text via GetTokenCountMeta().CombineText, and delegates to EstimateTokenByModel.
Tool normalization
service/claude_token_estimator.go
normalizeRequestTools mutates req.Tools in-place, preserves already-typed tools, converts map[string]any entries into *dto.Tool or *dto.ClaudeWebSearchTool by marshal/unmarshal, filters malformed entries, and routes web_search_* types to web-search tool struct.
Tests
service/claude_token_estimator_test.go
Table-driven tests for various request shapes, nil-safety, and normalization edge cases (malformed, pre-typed tools, web-search routing).

Sequence Diagram

sequenceDiagram
    participant Client as Client
    participant Handler as ClaudeCountTokens
    participant Service as EstimateClaudeInputTokens
    participant Estimator as EstimateTokenByModel

    Client->>Handler: POST /v1/messages/count_tokens with body
    Handler->>Handler: Unmarshal body -> dto.ClaudeRequest
    alt Unmarshal fails
        Handler-->>Client: 400 Bad Request (invalid_request_error)
    else Success
        Handler->>Service: EstimateClaudeInputTokens(&req)
        Service->>Service: normalizeRequestTools(&req)
        Service->>Service: meta := req.GetTokenCountMeta().CombineText
        Service->>Estimator: EstimateTokenByModel(req.Model, meta)
        Estimator-->>Service: token count
        Service-->>Handler: input_tokens
        Handler-->>Client: 200 OK { "input_tokens": N }
    end

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Suggested reviewers

  • seefs001

Poem

🐰 I hopped through requests with cheer,
Tools sorted tidy, tokens near,
I combined the words and gave a count—
Soft thumps, small math, no large amount.
I sniffed the bytes and danced in cheer.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main feature: adding support for the /v1/messages/count_tokens endpoint with local token estimation, which is the core change across the 4 modified files.
Linked Issues check ✅ Passed The PR fulfills all three linked issues: implements Claude-compatible /v1/messages/count_tokens endpoint [#1694, #2847] with local estimation avoiding upstream requests, and prevents 429 errors from SDK fallback probes [#1979].
Out of Scope Changes check ✅ Passed All changes are scoped to implementing the count_tokens endpoint: new controller handler, router registration, token estimation logic with tool normalization, and comprehensive tests. No unrelated alterations to adaptor/distributor/RelayFormat/autoban as confirmed.

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

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

[!TIP]

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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[bot] avatar Apr 24 '26 12:04 coderabbitai[bot]

Round 3 已处理 CodeRabbit Round 2 的 encoding/json duplicate(commit 5dfd360):

  • service/claude_token_estimator.go:3 处 json.Marshal / json.Unmarshal → common.Marshal / common.Unmarshal
  • service/claude_token_estimator_test.go:1 处同步

Round 2 已修的几条复核(相关 reviewer 可略过):

  • Router 挂在 relayV1Router 上(router/relay-router.go:82),bypass Distribute(),注释明说
  • Controller 用 common.UnmarshalBodyReusable,body 可重读给下游 + 隐式 size 防御
  • tool_use / tool_result 的 char 抽取复用 ClaudeRequest.GetTokenCountMeta()(dto/claude.go:306-318),通过 common.Marshal(media.Input) / common.Marshal(media.Content) 展开,CLI 事故场景(53KB tool schema body)不会 undercount

所有 15 个单测仍然全过:

``` go test ./service/ -run 'TestEstimateClaude|TestNormalizeRequestTools' -v ```

Image token 精算 + docstring coverage 如需要可另开 follow-up issue。

daymade avatar Apr 25 '26 02:04 daymade

@6639835 谢谢反馈。评估过 7 种替代方案,列一下结论供参考:

方案 为什么不优于本 PR
A. 透传上游官方 count_tokens 第三方代理(Qiniu / StepFun / Kimi / OpenRouter)99% 自己不实现,即便透传也要占上游 RPM
B. Middleware 拦截 max_tokens=1 伪请求 污染 /v1/messages 语义,合法 max_tokens=1(canary probe / token 价格校验)会被误杀;SDK 版本变化时脆弱
C. 真 tokenizer 库(tiktoken-go / claude-tokenizer-go) Anthropic 2026 起不再公开 tokenizer,社区逆向库精度 80-95%,license 存疑;count_tokens 本就是 estimate,没必要为 ±5% 引入维护债
D. 返 501 Not Implemented 实测 SDK 对 404/501 同一 fallback,无效
E. 限制 SDK retry 次数 治标不治本,首轮 250 个伪请求仍会发
F. Two-tier pass-through + fallback 需要 channel 声明 capability 字段;目前 0 channel 支持,纯 dead code
G. 请求指纹缓存(SHA256(system+tools) + 5s TTL) 与本 PR 正交的性能增量,可作 follow-up issue,不是替代

count_tokens 按 Anthropic spec 本就是 estimate,SDK 拿它决定是否触发 context 压缩,不是精确计费,±20-30% 偏差是业内共识。

至于 "SDK 会不会 cache 上游不支持 endpoint、永远走 max_tokens=1 fallback" 这种担忧——我验证过 Claude Code CLI 每次调用 count_tokens 都是独立的,失败只返回 null,不设任何全局状态。所以本 PR 的本地估算覆盖 100% 事故场景,已退化 session 也会重新 probe。

如果你有具体的其他方向,欢迎补充——尤其是:(1) 精度提升对哪个实际调用链有影响?(2) 外部 tokenizer 跟版本漂移怎么维护?

daymade avatar Apr 25 '26 02:04 daymade

非常好 PR!我们也急需这个功能,希望可以尽快合并😊

B1F030 avatar May 14 '26 07:05 B1F030

现在是不是 /v1/messages/count_tokens现在都不支持? 然后我发现了用cc有个降级逻辑,没有count_tokens就导致降级成了60多个非流请求。然后打爆上游的接口429了。

SilentFlower avatar Jun 15 '26 10:06 SilentFlower

现在是不是 /v1/messages/count_tokens现在都不支持? 然后我发现了用cc有个降级逻辑,没有count_tokens就导致降级成了60多个非流请求。然后打爆上游的接口429了。

我的分支 已经实现了这个接口,不过目前仅限 AWS bedrock 渠道,你可以试试,直接基于这份代码构建 docker 镜像就行了

B1F030 avatar Jun 15 '26 11:06 B1F030

现在是不是 /v1/messages/count_tokens现在都不支持? 然后我发现了用cc有个降级逻辑,没有count_tokens就导致降级成了60多个非流请求。然后打爆上游的接口429了。

我的分支 已经实现了这个接口,不过目前仅限 AWS bedrock 渠道,你可以试试,直接基于这份代码构建 docker 镜像就行了

我也写了,不过是透传上游。最近一直在排查相关非流请求循环的BUG,最后发现问题在这

SilentFlower avatar Jun 15 '26 11:06 SilentFlower