MCPcopy
hub / github.com/coder/mux / countTokensInternal

Function countTokensInternal

src/node/utils/main/tokenizer.ts:146–178  ·  view source on GitHub ↗
(modelName: ModelName, text: string)

Source from the content-addressed store, hash-verified

144}
145
146async function countTokensInternal(modelName: ModelName, text: string): Promise<number> {
147 assert(typeof text === "string", "Tokenizer countTokens expects string input");
148 if (text.length === 0) {
149 return 0;
150 }
151
152 const key = buildCacheKey(modelName, text);
153 const cached = tokenCountCache.get(key);
154 if (cached !== undefined) {
155 return cached;
156 }
157
158 let pending = inFlightCounts.get(key);
159 if (!pending) {
160 const payload: CountTokensInput = { modelName, input: text };
161 pending = run<number>("countTokens", payload)
162 .then((value: unknown) => {
163 assert(
164 typeof value === "number" && Number.isFinite(value) && value >= 0,
165 "Tokenizer must return a non-negative finite token count"
166 );
167 tokenCountCache.set(key, value);
168 inFlightCounts.delete(key);
169 return value;
170 })
171 .catch((error) => {
172 inFlightCounts.delete(key);
173 throw error;
174 });
175 inFlightCounts.set(key, pending);
176 }
177 return pending;
178}
179
180export function loadTokenizerModules(
181 modelsToWarm: string[] = Array.from(DEFAULT_WARM_MODELS)

Callers 3

getTokenizerForModelFunction · 0.85
countTokensFunction · 0.85
countTokensBatchFunction · 0.85

Calls 6

runFunction · 0.90
buildCacheKeyFunction · 0.85
setMethod · 0.80
getMethod · 0.65
assertFunction · 0.50
deleteMethod · 0.45

Tested by

no test coverage detected