Skip to content

Commit 654eb9b

Browse files
committed
Include model in token count api. Default to opus. track token count in event
1 parent 494e476 commit 654eb9b

File tree

2 files changed

+20
-12
lines changed

2 files changed

+20
-12
lines changed

packages/agent-runtime/src/run-agent-step.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -767,6 +767,7 @@ export async function loopAgentSteps(
767767
const tokenCountResult = await callTokenCountAPI({
768768
messages: messagesWithStepPrompt,
769769
system,
770+
model: agentTemplate.model,
770771
fetch,
771772
logger,
772773
env: { clientEnv, ciEnv },

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

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { AnalyticsEvent } from '@codebuff/common/constants/analytics-events'
2+
import { toAnthropicModelId } from '@codebuff/common/constants/claude-oauth'
23
import { getErrorObject } from '@codebuff/common/util/error'
34
import { env } from '@codebuff/internal/env'
45
import { NextResponse } from 'next/server'
@@ -70,17 +71,6 @@ export async function postTokenCount(params: {
7071

7172
const { messages, system, model } = bodyResult.data
7273

73-
trackEvent({
74-
event: AnalyticsEvent.TOKEN_COUNT_REQUEST,
75-
userId,
76-
properties: {
77-
messageCount: messages.length,
78-
hasSystem: !!system,
79-
model: model ?? 'claude-sonnet-4-20250514',
80-
},
81-
logger,
82-
})
83-
8474
try {
8575
const inputTokens = await countTokensViaAnthropic({
8676
messages,
@@ -90,6 +80,18 @@ export async function postTokenCount(params: {
9080
logger,
9181
})
9282

83+
trackEvent({
84+
event: AnalyticsEvent.TOKEN_COUNT_REQUEST,
85+
userId,
86+
properties: {
87+
messageCount: messages.length,
88+
hasSystem: !!system,
89+
model: model ?? 'claude-opus-4-5-20251101',
90+
inputTokens,
91+
},
92+
logger,
93+
})
94+
9395
return NextResponse.json({ inputTokens })
9496
} catch (error) {
9597
logger.error(
@@ -125,6 +127,11 @@ async function countTokensViaAnthropic(params: {
125127
// Convert messages to Anthropic format
126128
const anthropicMessages = convertToAnthropicMessages(messages)
127129

130+
// 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'
134+
128135
// Use the count_tokens endpoint (beta) or make a minimal request
129136
const response = await fetch(
130137
'https://api.anthropic.com/v1/messages/count_tokens',
@@ -137,7 +144,7 @@ async function countTokensViaAnthropic(params: {
137144
'content-type': 'application/json',
138145
},
139146
body: JSON.stringify({
140-
model: model ?? 'claude-opus-4-5-20251101',
147+
model: anthropicModelId,
141148
messages: anthropicMessages,
142149
...(system && { system }),
143150
}),

0 commit comments

Comments
 (0)