Repository navigation
feat(api): add Anthropic /v1/messages/count_tokens endpoint - #83
Conversation
Forward Anthropic-compatible token counting requests to upstream providers. The endpoint accepts the same loose schema we use for /v1/messages so newer content block shapes pass through unchanged, and reuses provider/model resolution and failover so a count_tokens call benefits from the same retry/multi-provider behavior as the chat path. Implementation notes: - Dedicated COUNT_TOKENS_FAILOVER_CONFIG with a tighter 30s timeout and 404/405 added to retriable status codes — many providers either don't implement the endpoint or expose it under a slightly different path, so failing over to another mapped provider is the right default. - normalizeAnthropicBaseUrl strips a trailing /v1 from baseUrl before appending /v1/messages/count_tokens, since some providers' baseUrl already includes the /v1 segment. - Upstream JSON / error parsing goes through parseJsonResponse to keep the same defensive parsing the rest of the messages route uses. Verification: scripts/verify-anthropic-count-tokens.sh probes Kimi Coding / DashScope-Anthropic / Volcengine-Ark gateways for count_tokens support using env-supplied API keys (never written to disk). It auto-discovers a working model via /v1/models then sends a real /v1/messages and /v1/messages/count_tokens probe and classifies the result as SUPPORTED / NOT_SUPPORTED / INCONCLUSIVE.
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 59 minutes. View limit details
Walkthrough
🚥 Pre-merge checks | ✅ 4 | ❌ 1
Finishing Touches
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. 🐰 一只小兔跳过故障线, |
There was a problem hiding this comment.
Code Review
This pull request introduces a new /messages/count_tokens endpoint to the messages API, providing token counting capabilities for Anthropic-compatible models. The implementation includes request schema validation, provider selection with failover support, and a set of utility functions for request construction and response parsing. A verification script is also added to test the functionality across different providers. Feedback suggests refactoring the manual failover loop to use the existing executeWithFailover service for better consistency and masking raw upstream error messages to avoid exposing internal implementation details.
| type: "error", | ||
| error: { | ||
| type: "api_error", | ||
| message: text, |
There was a problem hiding this comment.
In API error handlers, log the full error details on the server for debugging, but return only a generic, structured error message to the client to avoid leaking internal implementation details. Returning raw upstream error bodies (even truncated) can expose internal infrastructure details or sensitive information from proxies/gateways.
| message: text, | |
| message: "An unexpected error occurred while processing the upstream response.", |
References
- In API error handlers, log the full error details on the server for debugging, but return only a generic, structured error message to the client to avoid leaking internal implementation details.
| let lastResponse: Response | undefined; | ||
| let lastError: Error | undefined; | ||
|
|
||
| for (const candidate of candidates) { | ||
| const { url, init, proxy } = buildAnthropicCountTokensRequest( | ||
| upstreamBody, | ||
| candidate, | ||
| extraHeaders, | ||
| ); | ||
|
|
||
| try { | ||
| const response = await fetchWithTimeout( | ||
| url, | ||
| init, | ||
| COUNT_TOKENS_FAILOVER_CONFIG.timeoutMs, | ||
| proxy, | ||
| ); | ||
|
|
||
| if (response.ok) { | ||
| return await parseUpstreamJsonBody( | ||
| response, | ||
| "Anthropic count_tokens", | ||
| ); | ||
| } | ||
|
|
||
| lastResponse = response; | ||
| const shouldTryNext = | ||
| COUNT_TOKENS_FAILOVER_CONFIG.retriableStatusCodes.includes( | ||
| response.status, | ||
| ) && candidate !== candidates[candidates.length - 1]; | ||
|
|
||
| logger.warn("count_tokens upstream request failed", { | ||
| provider: candidate.provider.name, | ||
| providerType: candidate.provider.type, | ||
| status: response.status, | ||
| shouldTryNext, | ||
| }); | ||
|
|
||
| if (!shouldTryNext) { | ||
| set.status = response.status; | ||
| return await parseUpstreamErrorBody(response); | ||
| } | ||
| } catch (error) { | ||
| const err = | ||
| error instanceof Error ? error : new Error(String(error)); | ||
| lastError = err; | ||
| const shouldTryNext = | ||
| isRetriableNetworkError(err, COUNT_TOKENS_FAILOVER_CONFIG) && | ||
| candidate !== candidates[candidates.length - 1]; | ||
|
|
||
| logger.warn("count_tokens upstream network error", { | ||
| provider: candidate.provider.name, | ||
| providerType: candidate.provider.type, | ||
| error: err.message, | ||
| shouldTryNext, | ||
| }); | ||
|
|
||
| if (!shouldTryNext) { | ||
| set.status = 502; | ||
| return { | ||
| type: "error", | ||
| error: { | ||
| type: "api_error", | ||
| message: `Count tokens request failed: ${err.message}`, | ||
| }, | ||
| }; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if (lastResponse) { | ||
| set.status = lastResponse.status; | ||
| return await parseUpstreamErrorBody(lastResponse); | ||
| } | ||
|
|
||
| set.status = 502; | ||
| return { | ||
| type: "error", | ||
| error: { | ||
| type: "api_error", | ||
| message: | ||
| lastError?.message || | ||
| "All upstream providers failed for token counting", | ||
| }, | ||
| }; |
There was a problem hiding this comment.
The manual failover loop duplicates logic that is already encapsulated in the executeWithFailover service. Using the centralized service ensures that the request benefits from standard features like exponential backoff and consistent logging. This refactoring also correctly differentiates between non-retriable upstream errors (which are forwarded) and true failover exhaustion (which returns a 502), adhering to repository standards.
const result = await executeWithFailover(
candidates,
(candidate) =>
buildAnthropicCountTokensRequest(upstreamBody, candidate, extraHeaders),
COUNT_TOKENS_FAILOVER_CONFIG,
);
if (result.success && result.response) {
return await parseUpstreamJsonBody(
result.response,
"Anthropic count_tokens",
);
}
if (result.response) {
set.status = result.response.status;
return await parseUpstreamErrorBody(result.response);
}
set.status = 502;
return {
type: "error",
error: {
type: "api_error",
message:
result.finalError ||
"All upstream providers failed for token counting",
},
};References
- When handling failover results, differentiate between non-retriable upstream errors (which should be forwarded to the client) and true failover exhaustion due to retriable errors (which may warrant a 502 Bad Gateway response).
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@backend/src/api/v1/messages.ts`:
- Around line 685-701: The response body isn't being released when a retriable
upstream error will cause failover; before skipping to the next candidate (where
you compute shouldTryNext using COUNT_TOKENS_FAILOVER_CONFIG and candidates),
call await response.body?.cancel() to free the undici/Node fetch
socket/resources; do this just after deciding shouldTryNext is true and before
returning or continuing, keeping existing logic around lastResponse,
logger.warn, set.status and parseUpstreamErrorBody unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI (base), Organization UI (inherited)
Review profile: CHILL
Plan: Pro
Run ID: c36135db-cace-4e7d-8bd4-708263e2f1c2
📒 Files selected for processing (2)
backend/src/api/v1/messages.tsscripts/verify-anthropic-count-tokens.sh
Select only Anthropic mappings, carry the per-attempt deadline through the response body, and validate counts before returning success. Preserve terminal statuses, release discarded responses, and keep raw upstream diagnostics private.
Summary
POST /v1/messages/count_tokensto the Anthropic-compatible API surface, forwarding to upstream providers using the existing model resolution and failover infrastructure.tLooseObject) so newer Anthropic content block shapes pass through transparently — same approach used by/v1/messages./v1/messages), and404/405added to retriable codes since not every Anthropic-compatible gateway implements the endpoint, and we want failover to a mapped sibling provider to kick in instead of returning the first 404.normalizeAnthropicBaseUrltrims a trailing/v1frombaseUrlbefore appending/v1/messages/count_tokens, since some providers configurebaseUrlalready with/v1.parseJsonResponsefor the defensive parsing the rest of the messages route uses.Verification
scripts/verify-anthropic-count-tokens.shis a black-box probe across three Anthropic-compatible coding gateways (Kimi Coding, DashScope-Anthropic, Volcengine-Ark). It:/v1/models/v1/messagesand/v1/messages/count_tokensprobeSUPPORTED/NOT_SUPPORTED/INCONCLUSIVE/LIKELY_SUPPORTED_BUT_REQUEST_SCHEMA_DIFF/AUTH_OR_PERMISSION_ISSUE_ON_COUNT_TOKENSRun with:
The script's verdicts give us a real read on which upstreams need
404failover (the reason 404 is in the retriable set) versus which we can route to confidently.Test plan
bun run lintcleanbun run checkcleanapi-helpers.test.ts(15 cases, from fix(api): restore SSE Content-Type for streaming responses #82) still passesverify-anthropic-count-tokens.shagainst at least one real coding gatewaySummary by CodeRabbit
发布说明
新功能
测试