snug pre-wired with tiktoken. Token counting for OpenAI models with no setup.
import { fit } from '@jeremysnr/snug-tiktoken';
const result = fit(
[
{ id: 'system', content: systemPrompt, priority: 100 },
{ id: 'history', content: chatHistory, priority: 60 },
{ id: 'rag', content: retrievedDocs, priority: 40 },
],
{ budget: 8192, reserve: 1024, model: 'gpt-4o' },
);- With no
model, text is counted with thecl100k_baseencoding (the one used bygpt-4andgpt-3.5-turbo). - Pass
modelto get the exact encoding for that OpenAI model.gpt-4oand newer models useo200k_base, which produces different counts fromcl100k_base, so pass the model name whenever you know it.
fit(items, { budget: 4096, model: 'gpt-4o' });
fit(items, { budget: 4096, model: 'gpt-3.5-turbo' });Anthropic models are not covered by tiktoken. Claude uses its own tokenizer and tiktoken counts for it are approximate. For exact numbers call Anthropic's count_tokens endpoint and pass the result through each item's tokens field, which bypasses the tokenizer:
{ id: 'msg', content: msg, priority: 50, tokens: input_tokens }Otherwise treat the count as an estimate and keep a generous reserve.
tiktoken encoders are WASM objects and are slow to construct. This package creates one per model or encoding and keeps it for the life of the process. If you need to release that memory (for example in a long-running worker after a burst of work), call freeEncoders(); the next fit() recreates encoders as needed.
import { freeEncoders } from '@jeremysnr/snug-tiktoken';
freeEncoders();npm install @jeremysnr/snug-tiktoken
@jeremysnr/snug is zero-dependency and requires you to supply a tokenizer. This package removes that step for the common OpenAI case.
MIT