nanocoder
nanocoder copied to clipboard
[Feature] Create only the tokenizer in use: `tokenizer-factory` loads all four tokenizer packages at startup
Description
source/tokenization/tokenizer-factory.ts imports every tokenizer wrapper statically, and useAppState.tsx imports the factory. So llama-tokenizer-js (661 KB of source with an embedded vocabulary), @anthropic-ai/tokenizer (681 KB, with tiktoken lite) and tiktoken (WASM) all load for every provider, although a session uses one.
Environment
- OS: Windows 11 (10.0.26300), host loaded
- Node version: 22.22.3
- Nanocoder version: 1.31.0 (main at 5c2e6935)
Evidence
- Chain:
app/App.js -> hooks/useAppHandlers.js(anduseAppState.tsx:13)-> tokenization/index.js -> tokenizer-factory.js -> tokenizers/{anthropic,generic,llama,openai}-tokenizer.js(tokenizer-factory.ts:7-10). - Standalone import cost (min of 5):
tiktoken56 ms,@anthropic-ai/tokenizer68 ms,llama-tokenizer-js145 ms. Median RSS above a bare Node process: +17, +5 and +27 MB (single-process medians, noisy). - Blocking these packages in the import graph removes only 7 modules (few, large files), so the saving is parse time and memory, not module count.
- On disk:
tiktoken22.5 MB, and@anthropic-ai/tokenizerbundles@types/node@18(2.0 MB) as a production dependency.
Proposed Change
- Load each tokenizer module on first
countTokens(). KeepcreateTokenizersynchronous by usingcreateRequirefor the CommonJS tokenizers, or return a thin object that loads lazily. - Separate follow-up (needs design): evaluate pure-JS counters to drop the 22.5 MB
tiktokeninstall.
Expected Behavior
- An Ollama session loads only the llama tokenizer; an OpenAI session loads only
tiktoken. - Token counts for a fixed sample text are identical before and after, for each provider.
Additional Context
- Effort: M. Start with
source/tokenization/tokenizer-factory.ts,source/tokenization/tokenizers/,source/hooks/useAppState.tsx. - Estimated saving: roughly 100-250 ms and 20-40 MB at startup (derived from the standalone figures, noisy). Confidence medium.
- Callers that assume a synchronous tokenizer:
auto-compact.ts,compact-handler.ts,commands/usage.tsx. Specs:source/tokenization/**/*.spec.ts.
I’d like to take this. I’ll lazy-load each tokenizer on first countTokens() and add specs checking token counts are unchanged per provider.