Loading...
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Tokenization is the process of splitting raw text into discrete chunks — called tokens — before feeding that text into a language model. Every LLM (GPT-4, Claude, Gemini, LLaMA…) operates exclusively on token sequences, never on raw strings or individual characters.
A token is typically a word fragment, a full common word, a punctuation mark, or a whitespace signal. The vocabulary of a modern model usually contains between 32 000 and 100 000 unique tokens, each mapped to an integer ID.
The tokenization pipeline
Most modern LLMs use Byte-Pair Encoding (BPE), originally a data-compression algorithm, adapted for NLP by Sennrich et al. (2016). The core idea:
The result: common words become single tokens (THE → ID 1), while rare words split into recognizable sub-pieces (TOKENIZATION → ["token", "ization"]).
Ġ (GPT-2) or represented as a flag on the token. This lets the model distinguish WORD when sentence-initial from WORD after a space — both common but semantically distinct positions.Type any text below to see how a simplified BPE-style tokenizer splits it. Each color represents a distinct token. Toggle Show token IDs to see the integer mapping.
Token → ID mapping (first 12 shown)
Several production-grade npm packages expose tokenization directly in JavaScript/TypeScript. Here are the three most widely used.
Official OpenAI tokenizer, compiled from Rust via WASM. Supports cl100k_base (GPT-4), p50k_base (Codex), and o200k_base (GPT-4o).
Anthropic's official SDK. Claude models use a similar BPE scheme; the SDK's countTokens() helper lets you estimate cost before sending a request.
Port of HuggingFace Transformers for JS. Provides AutoTokenizer which supports hundreds of models and handles padding, truncation, and special tokens.
Every LLM call has a context window — the maximum number of tokens the model can process in one request (input + output combined). Understanding token counts is essential for:
LLM APIs charge per token. A 10 000-token prompt at $3/M tokens costs $0.03 per call.
Longer context isn't always better. Irrelevant tokens dilute attention and increase latency.
When indexing documents, chunk at token boundaries — not character limits — to preserve meaning.
APIs enforce tokens-per-minute limits. Counting tokens before batching prevents 429 errors.