11import { 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'
36import { getErrorObject } from '@codebuff/common/util/error'
47import { env } from '@codebuff/internal/env'
58import { 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+
118124async 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
173189export function convertToAnthropicMessages (
0 commit comments