
Token counts affect context limits, latency and cost, but they are not the only factors. A token is a unit in the model’s vocabulary, not necessarily a whole word or character. Count with the tokenizer and revision used by your deployment, and distinguish a local text estimate from usage for the complete server request.
Record the model, tokenizer and request format used by the application. Use representative inputs when checking token estimates and observed usage.
Try Compute: Launch a vLLM endpoint on Compute. Pick the model you use in production and measure input and output token counts with streaming on. Keep the endpoint in the chosen region and set an appropriate output limit for each route.
Tokenization sits at the heart of how language models work. When you send text to a model, it can't read words the way you do—it needs to break your input into smaller pieces called tokens first. Think of tokenization as the bridge between human language and what the machine can actually process. These tokens might be whole words, parts of words, or even single characters, depending on how the system is set up.
BPE and WordPiece are tokenization algorithms. SentencePiece is a toolkit that supports both BPE and unigram models, not a separate algorithm opposed to BPE. Vocabulary, normalization and special-token rules also affect the result; use the tokenizer supplied for the pretrained model.
Understanding how text becomes tokens helps you investigate unexpected counts and set request budgets. It does not by itself guarantee better prompts or the intended answer.
| Pitfall | Possible effect | What to check |
|---|---|---|
| Counting with the wrong tokenizer | Local estimates can differ from request usage reported by the server | Use the deployed model’s tokenizer and revision; compare equivalent inputs and measurements |
| CRLF vs LF line endings | Different strings can produce different token splits | Preserve original line endings unless the application deliberately transforms them; count the text actually sent |
| NBSP (\u00A0) and ZWJ (\u200D) | These characters can change counts without always increasing them | Preserve their linguistic or typographic role; test any deliberate transformation before counting |
| Smart quotes and curly apostrophes | Punctuation can change tokenization results | Preserve the source language and text; do not automatically convert punctuation to ASCII |
| Emoji & skin tones | Multi-codepoint sequences can change token counts | Test the exact Unicode sequences with the deployment’s tokenizer; do not remove them solely to reduce counts |
| Markdown fences (…) | Long code blocks can reach context or output limits | Preserve delimiters and meaningful whitespace; test truncation and use the output limit supported by the endpoint |
| Duplicated system prompts | Same instructions repeated per turn | Remove duplicates during assembly and keep one versioned source for system instructions |
| Mixed languages | Token counts can vary by language and writing system | Specify the desired output language and test representative multilingual inputs |
Make preprocessing an explicit, tested application choice. Unicode normalization can change representation; compatibility normalization can remove distinctions. Counting alone is not a reason to rewrite each sentence.
Check the available instance configuration and current product documentation before starting a test. Measure the behavior of your own model and workload.
Keep a tokenizer baseline for each model and revision. The sketches below compare local plain-text counts; they do not count a complete chat request or demonstrate equivalent behavior across models. Add representative regression tests before relying on them in CI.
Scope of these sketches: Python explicitly loads cl100k_base and a local SentencePiece file named llama.model; that file is required and is not a tokenizer for every Llama generation. The JavaScript sketch selects gpt-4o-mini, whose documented encoding is o200k_base, and uses different samples. These are not a matched Python/JavaScript comparison. Align the tokenizer and inputs before comparing results; neither sketch was runtime-tested for this article.
Python (sketch)
# pip install tiktoken sentencepiece
import tiktoken
import sentencepiece as spm
# Loading the tokenizer: make sure to load the correct encoding or model for your use case.
enc_gpt = tiktoken.get_encoding("cl100k_base")
sp = spm.SentencePieceProcessor(model_file="llama.model") # use your model's spm
# Each entry in TEXTS is an instance or example sentence to be tokenized.
TEXTS = [
"l’été dernier à Zürich — café & résumé",
"Schadenfreude und Lebensversicherung",
"اللغة العربية جميلة جدًا",
"I typed :shrug: and got 🤷🏽♂️",
"""```
print('big code block that should be truncated...')
```"""
]
for s in TEXTS:
# The text is tokenized using both libraries/tools.
gpt_tokens = len(enc_gpt.encode(s))
sp_tokens = len(sp.encode(s))
print({"text": s[:32] + "…", "gpt": gpt_tokens, "spm": sp_tokens})
Node (rough sketch)
// npm i js-tiktoken
import { encodingForModel } from "js-tiktoken";
// Loading the tokenizer for the desired model.
const enc = encodingForModel("gpt-4o-mini");
// Each sample is an instance or example sentence.
const samples = [
"l’été à Paris",
"Schweizer Rückversicherung",
"emoji 🤷🏽♂️",
];
for (const s of samples) {
// Output how many tokens each sentence is tokenized into.
console.log(s.slice(0,24)+"…", enc.encode(s).length);
}
Building effective LLM applications isn't just about feeding text into a model—it's about understanding context and how it shapes the quality and speed of what you get back. Context-aware development means designing systems that use your model's strengths while managing the real challenges of token limits and context windows.
RAG adds retrieved material to the input and can help when that material is relevant. It does not guarantee a smaller prompt, lower latency or a more accurate answer. Measure retrieval quality, context length, response quality and latency together on representative requests.
When you understand how context, tokens, and model performance work together, you can design applications that get the most from LLMs. This means carefully choosing your input data, watching token usage, and using context-aware techniques so every token delivers value for your specific task. Context-aware development comes down to finding the right balance—give the model enough information to understand what you need while keeping things efficient for real-world use.
Note: It is critical to monitor how many tokens are used in each request to avoid budget overruns and unexpected costs.
Try Compute: Run a vLLM endpoint on Compute with input and output usage logs, TTFT, and TPS. Record the tokenizer and its revision for each deployed model, then check estimates in CI.
Track tokenizer and template revisions, deliberate preprocessing and server usage. Retest representative languages and tasks after changes. These checks help explain count drift; they do not guarantee stable time to first token (TTFT) or tokens per second.
For a pretrained model, use its compatible tokenizer rather than independently choosing BPE, WordPiece or a SentencePiece model. Evaluate model quality, latency and cost together before changing the deployment.
When evaluating a tokenizer or model change, compare the same representative inputs and keep the version information with the results. Use measured differences rather than assuming that a newer option is more efficient.
Evaluate context-management changes on your own tasks. More retrieved material or a newer tokenizer does not by itself establish better answers; retain measured comparisons and the exact model configuration.
Keep these checks in the application’s test process and repeat them when the model, input handling or request format changes.
Use the tokenizer and template for the deployed model and revision. Compare local estimates with the provider’s request-level counting or usage information where available.
Separate estimated tokens, reported usage and billed cost. Investigate differences before using a local estimate for billing or alerts.
For supported models, tiktoken can estimate plain-text tokens locally. Counting a string alone does not include the complete structured request.
Models can use different vocabularies, normalization rules and special tokens, including when they share a tokenization algorithm. SentencePiece can implement BPE; it is not an opposing algorithm.
To compare a sentence, run the exact same text through each named tokenizer and revision and record the token IDs and count. Do not infer a token split from the displayed words or present an unmeasured segmentation as a result.
Note: Always plan for variance in token counts between models, and set token caps accordingly.
Yes. Whitespace, combining characters, emoji sequences and punctuation can affect the result, but they do not always increase it. Test the exact Unicode string with the deployment’s tokenizer.
Count after any intentional application preprocessing, and keep the original text for comparison where appropriate. Do not normalize solely to force a lower count.
To explain, Unicode characters can split words or sentences into additional tokens because tokenizers may treat them differently from standard spaces or punctuation. This can affect how sentences are processed and the total token count.
No. A word count is not a token count, and the relationship varies with language, text and tokenizer. Measure the actual input instead of applying a fixed words-to-tokens conversion.
To explain, word counts are misleading because tokenizers may divide a single word into multiple tokens or merge parts of different words, depending on the language model. This affects both cost and latency calculations.
Note: Always use token counts instead of word or sentence counts when estimating usage or costs.
Log language tags per request to accurately track usage and manage token allocation. Different tasks, such as translation, summarization, or dialogue generation, may require different budgeting strategies depending on their complexity and language. Measure token count for each request to determine how many tokens are used, ensuring you stay within model context limits.
Set multilingual budgets from measured input and output distributions for each task and language, including longer cases. A multilingual tokenizer label does not guarantee equal token efficiency or answer quality across languages.
Measure TTFT and TPS by language.
Streaming changes how output is delivered; it is not a token discount. Compare usage for the actual completed or canceled request, not the amount of text displayed so far.
A Stop button should request cancellation through the supported client/server path. Hiding output or closing the display does not prove generation has stopped; cancellation can race with work already in progress. Do not promise that every token after the click is unbilled.
For OpenAI Chat Completions, requesting stream_options.include_usage adds a final usage chunk. An interrupted stream may not deliver it. Record that usage is unavailable rather than treating a missing total as zero.
Use the output-limit parameter supported by the endpoint and model, such as max_output_tokens or max_completion_tokens where applicable. Allow for non-visible output categories when relevant; test truncation and cancellation behavior before setting tight limits.
Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.