(params: {
req: NextRequest
getUserInfoFromApiKey: GetUserInfoFromApiKeyFn
logger: Logger
loggerWithContext: LoggerWithContextFn
trackEvent: TrackEventFn
fetch: typeof globalThis.fetch
})
| 35 | const DEFAULT_ANTHROPIC_MODEL = 'claude-opus-4-6' |
| 36 | |
| 37 | export async function postTokenCount(params: { |
| 38 | req: NextRequest |
| 39 | getUserInfoFromApiKey: GetUserInfoFromApiKeyFn |
| 40 | logger: Logger |
| 41 | loggerWithContext: LoggerWithContextFn |
| 42 | trackEvent: TrackEventFn |
| 43 | fetch: typeof globalThis.fetch |
| 44 | }) { |
| 45 | const { |
| 46 | req, |
| 47 | getUserInfoFromApiKey, |
| 48 | logger: baseLogger, |
| 49 | loggerWithContext, |
| 50 | trackEvent, |
| 51 | fetch, |
| 52 | } = params |
| 53 | |
| 54 | // Authenticate user |
| 55 | const userResult = await requireUserFromApiKey({ |
| 56 | req, |
| 57 | getUserInfoFromApiKey, |
| 58 | logger: baseLogger, |
| 59 | loggerWithContext, |
| 60 | trackEvent, |
| 61 | authErrorEvent: AnalyticsEvent.TOKEN_COUNT_AUTH_ERROR, |
| 62 | }) |
| 63 | |
| 64 | if (!userResult.ok) { |
| 65 | return userResult.response |
| 66 | } |
| 67 | |
| 68 | const { userId, logger } = userResult.data |
| 69 | |
| 70 | // Parse request body |
| 71 | const bodyResult = await parseJsonBody({ |
| 72 | req, |
| 73 | schema: tokenCountRequestSchema, |
| 74 | logger, |
| 75 | trackEvent, |
| 76 | validationErrorEvent: AnalyticsEvent.TOKEN_COUNT_VALIDATION_ERROR, |
| 77 | }) |
| 78 | |
| 79 | if (!bodyResult.ok) { |
| 80 | return bodyResult.response |
| 81 | } |
| 82 | |
| 83 | const { messages, system, model, tools } = bodyResult.data |
| 84 | |
| 85 | try { |
| 86 | const useOpenAI = model != null && false // isOpenAIProviderModel(model) |
| 87 | const inputTokens = useOpenAI |
| 88 | ? await countTokensViaOpenAI({ messages, system, model, fetch, logger }) |
| 89 | : await countTokensViaAnthropic({ |
| 90 | messages, |
| 91 | system, |
| 92 | model, |
| 93 | tools, |
| 94 | fetch, |
no test coverage detected