MCPcopy Create free account
hub / github.com/Noumena-Network/code / countTokensWithFallback

Function countTokensWithFallback

src/utils/analyzeContext.ts:78–110  ·  view source on GitHub ↗
(
  messages: Anthropic.Beta.Messages.BetaMessageParam[],
  tools: Anthropic.Beta.Messages.BetaToolUnion[],
)

Source from the content-addressed store, hash-verified

76export const TOOL_TOKEN_COUNT_OVERHEAD = 500
77
78async function countTokensWithFallback(
79 messages: Anthropic.Beta.Messages.BetaMessageParam[],
80 tools: Anthropic.Beta.Messages.BetaToolUnion[],
81): Promise<number | null> {
82 try {
83 const result = await countMessagesTokensWithAPI(messages, tools)
84 if (result !== null) {
85 return result
86 }
87 logForDebugging(
88 `countTokensWithFallback: API returned null, trying haiku fallback (${tools.length} tools)`,
89 )
90 } catch (err) {
91 logForDebugging(`countTokensWithFallback: API failed: ${errorMessage(err)}`)
92 logError(err)
93 }
94
95 try {
96 const fallbackResult = await countTokensViaHaikuFallback(messages, tools)
97 if (fallbackResult === null) {
98 logForDebugging(
99 `countTokensWithFallback: haiku fallback also returned null (${tools.length} tools)`,
100 )
101 }
102 return fallbackResult
103 } catch (err) {
104 logForDebugging(
105 `countTokensWithFallback: haiku fallback failed: ${errorMessage(err)}`,
106 )
107 logError(err)
108 return null
109 }
110}
111
112interface ContextCategory {
113 name: string

Callers 5

countSystemTokensFunction · 0.85
countMemoryFileTokensFunction · 0.85
countCustomAgentTokensFunction · 0.85
approximateMessageTokensFunction · 0.85

Calls 5

logForDebuggingFunction · 0.70
errorMessageFunction · 0.70
logErrorFunction · 0.70

Tested by

no test coverage detected