MCPcopy
hub / github.com/claude-code-best/claude-code / countTokensWithFallback

Function countTokensWithFallback

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

Source from the content-addressed store, hash-verified

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