Skip to content

Commit 030d436

Browse files
committed
Token count endpoint: handle non-anthropic models by using default model and adding 30% tokens
1 parent 1f89575 commit 030d436

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

web/src/app/api/v1/token-count/_post.ts

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { AnalyticsEvent } from '@codebuff/common/constants/analytics-events'
2-
import { toAnthropicModelId } from '@codebuff/common/constants/claude-oauth'
2+
import {
3+
isClaudeModel,
4+
toAnthropicModelId,
5+
} from '@codebuff/common/constants/claude-oauth'
36
import { getErrorObject } from '@codebuff/common/util/error'
47
import { env } from '@codebuff/internal/env'
58
import { NextResponse } from 'next/server'
@@ -115,6 +118,9 @@ export async function postTokenCount(params: {
115118
}
116119
}
117120

121+
// Buffer to add to token count for non-Anthropic models since tokenizers differ
122+
const NON_ANTHROPIC_TOKEN_BUFFER = 0.3
123+
118124
async function countTokensViaAnthropic(params: {
119125
messages: TokenCountRequest['messages']
120126
system: string | undefined
@@ -128,9 +134,12 @@ async function countTokensViaAnthropic(params: {
128134
const anthropicMessages = convertToAnthropicMessages(messages)
129135

130136
// Convert model from OpenRouter format (e.g. "anthropic/claude-opus-4.5") to Anthropic format (e.g. "claude-opus-4-5-20251101")
131-
const anthropicModelId = model
132-
? toAnthropicModelId(model)
133-
: 'claude-opus-4-5-20251101'
137+
// For non-Anthropic models, use the default Anthropic model for token counting
138+
const DEFAULT_ANTHROPIC_MODEL = 'claude-opus-4-5-20251101'
139+
const isNonAnthropicModel = !model || !isClaudeModel(model)
140+
const anthropicModelId = isNonAnthropicModel
141+
? DEFAULT_ANTHROPIC_MODEL
142+
: toAnthropicModelId(model)
134143

135144
// Use the count_tokens endpoint (beta) or make a minimal request
136145
const response = await fetch(
@@ -167,7 +176,14 @@ async function countTokensViaAnthropic(params: {
167176
}
168177

169178
const data = await response.json()
170-
return data.input_tokens
179+
const baseTokens = data.input_tokens
180+
181+
// Add 30% buffer for non-Anthropic models since tokenizers differ
182+
if (isNonAnthropicModel) {
183+
return Math.ceil(baseTokens * (1 + NON_ANTHROPIC_TOKEN_BUFFER))
184+
}
185+
186+
return baseTokens
171187
}
172188

173189
export function convertToAnthropicMessages(

0 commit comments

Comments
 (0)