@@ -13,12 +13,12 @@ import { translateToOpenAI } from "./non-stream-translation"
13
13
*/
14
14
export async function handleCountTokens ( c : Context ) {
15
15
try {
16
+ const anthropicBeta = c . req . header ( "anthropic-beta" )
17
+
16
18
const anthropicPayload = await c . req . json < AnthropicMessagesPayload > ( )
17
19
18
- // Convert to OpenAI format for token counting
19
20
const openAIPayload = translateToOpenAI ( anthropicPayload )
20
21
21
- // Find the selected model
22
22
const selectedModel = state . models ?. data . find (
23
23
( model ) => model . id === anthropicPayload . model ,
24
24
)
@@ -30,17 +30,39 @@ export async function handleCountTokens(c: Context) {
30
30
} )
31
31
}
32
32
33
- // Calculate token count
34
33
const tokenCount = await getTokenCount ( openAIPayload , selectedModel )
35
- consola . debug ( "Token count:" , tokenCount )
36
34
37
- // Return response in Anthropic API format
35
+ if ( anthropicPayload . tools && anthropicPayload . tools . length > 0 ) {
36
+ let mcpToolExist = false
37
+ if ( anthropicBeta ?. startsWith ( "claude-code" ) ) {
38
+ mcpToolExist = anthropicPayload . tools . some ( ( tool ) =>
39
+ tool . name . startsWith ( "mcp__" ) ,
40
+ )
41
+ }
42
+ if ( ! mcpToolExist ) {
43
+ if ( anthropicPayload . model . startsWith ( "claude" ) ) {
44
+ // https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/overview#pricing
45
+ tokenCount . input = tokenCount . input + 346
46
+ } else if ( anthropicPayload . model . startsWith ( "grok" ) ) {
47
+ tokenCount . input = tokenCount . input + 480
48
+ }
49
+ }
50
+ }
51
+
52
+ let finalTokenCount = tokenCount . input + tokenCount . output
53
+ if ( anthropicPayload . model . startsWith ( "claude" ) ) {
54
+ finalTokenCount = Math . round ( finalTokenCount * 1.15 )
55
+ } else if ( anthropicPayload . model . startsWith ( "grok" ) ) {
56
+ finalTokenCount = Math . round ( finalTokenCount * 1.03 )
57
+ }
58
+
59
+ consola . info ( "Token count:" , finalTokenCount )
60
+
38
61
return c . json ( {
39
- input_tokens : tokenCount . input ,
62
+ input_tokens : finalTokenCount ,
40
63
} )
41
64
} catch ( error ) {
42
65
consola . error ( "Error counting tokens:" , error )
43
- // Return default value on error
44
66
return c . json ( {
45
67
input_tokens : 1 ,
46
68
} )
0 commit comments