Tokens in AI Explained: Mechanics, Costs & Speed (2026)
Master tokens in AI: Byte-Pair Encoding vs SentencePiece, multimodal vision and audio math, prompt caching discounts, reasoning billing, and Python counting.
Tokens in AI act as the atomic mathematical currency behind every prompt, context window limit, cloud invoice, and GPU memory transfer in modern language systems. Whether an application calls GPT-6.1 Sol, Claude Sonnet 5.5, or Gemini 3.8 Flash, every input string, image patch, and audio frame converts into integer token identifiers before neural attention layers evaluate a single relationship.
Understanding how AI tokens work is essential for controlling API budgets, preventing silent truncation errors, and diagnosing inference latency bottlenecks. Engineers studying how Large Language Models work quickly learn that tokenizer behavior dictates both multilingual cost multipliers and hardware throughput.
Key Takeaways
- Tokens in AI are subword, byte, or multimodal patch units mapped to integer IDs inside a fixed model vocabulary spanning 100,000 to over 256,000 entries, where 1,000 English tokens equal roughly 750 words.
- Frontier providers tokenize text with Byte-Level BPE (such as OpenAI
o200k_base) or SentencePiece variants, eliminating out-of-vocabulary errors while inflating non-Latin UTF-8 token counts by 1.5x to 3x.- Output tokens and hidden reasoning tokens cost 4x to 5x more than input tokens because sequential autoregressive decoding reloads model weights and KV cache tensors from GPU memory on every generated token.
- Prompt prefix caching cuts repeated static input expenses by 75% to 90% ($0.20 vs $2.00 per million tokens on frontier tiers) and drops time-to-first-token latency when static schemas sit first in the payload.
- Multimodal models convert media into shared context budgets, with Google Gemini billing 258 tokens per 768x768 image tile, 32 tokens per second of audio, and 263 tokens per second of video.
What Are Tokens in AI and Why Do Models Use Subwords?
What is a token in AI, and why do neural networks avoid raw words or individual letters? A token is a standardized chunk of text (a common word, syllable, punctuation mark, or raw UTF-8 byte) mapped to a unique integer ID inside a model’s fixed vocabulary, balancing sequence length against dictionary size.
Transformer neural networks cannot compute matrix multiplications on raw strings. During preprocessing, a tokenizer splits incoming characters into discrete integers that index an embedding lookup table. Those integers expand into dense high-dimensional vectors inside the first model layer.
Word-Level vs. Character-Level vs. Subword Tokenization
Early natural language pipelines experimented with splitting text strictly on whitespace or strictly into single characters. Both extremes fail at production scale for mathematical and memory reasons.
Word-level vocabularies explode past millions of entries once you account for typos, domain jargon, camelCase identifiers, and inflections (deploy, deployed, deploying). Any unseen string triggers an out-of-vocabulary (<UNK>) error, destroying downstream accuracy.
Character-level tokenization eliminates unknown words using a tiny alphabet, yet it stretches sequence lengths fourfold to sixfold. Because standard self-attention scales quadratically with sequence length, longer character streams exhaust GPU memory and collapse context window working memory limits.
| Tokenization Strategy | Typical Vocabulary Size | Sequence Length Impact | Out-of-Vocabulary Handling | Production Viability |
|---|---|---|---|---|
| Word-Level | 500,000 to 2,000,000+ | Shortest (1 token per word) | Fails on typos, code, and slang (<UNK>) |
Legacy statistical NLP only |
| Character-Level | 256 to 1,000 | Longest (4x to 6x longer) | Zero unknown words | Fails quadratic attention scaling |
| Subword Tokenization | 32,000 to 256,000 | Balanced (~0.75 words/token) | Splits rare strings into known syllables or bytes | Universal standard across frontier LLMs |
The English Rule of Thumb vs. Code and Data Payloads
In everyday English prose, 1 token averages roughly 4 characters or 0.75 words. Answering a frequent developer benchmark, how many tokens is 1,000 words in standard English prose? That document spans roughly 1,300 to 1,400 tokens.
That ratio shifts dramatically outside clean prose. Source code, minified JSON schemas, UUID strings, and Base64 blobs lack common English word boundaries, expanding 1,000 word-equivalents to 1,600 or 2,500+ tokens.
| Input String | Subword Token Split | Token Count | Why the Count Shifts |
|---|---|---|---|
"developer" |
["developer"] |
1 | High-frequency English noun kept intact |
"unbelievable" |
["un", "bel", "ievable"] |
3 | Rare adjective decomposed into reusable affixes |
"const apiKey = " |
["const", " api", "Key", " ="] |
4 | Leading whitespace and camelCase split cleanly |
"2026-11-12T19:58" |
["202", "6", "-", "11", "-", "12", "T", "19", ":", "58"] |
10 | Timestamps fragment into 1-to-3 digit chunks |
Notice how leading spaces attach directly to the start of words (" api"). Tokenizers treat "api" and " api" as completely separate integer IDs inside the model vocabulary.
How Tokenization Algorithms Work: BPE vs. WordPiece vs. SentencePiece vs. Unigram
LLM tokenization relies on four primary subword algorithms: Byte-Pair Encoding (BPE), Byte-Level BPE, WordPiece, and Unigram (often wrapped inside Google SentencePiece). Each algorithm constructs its vocabulary differently, shaping cross-lingual fairness, inference speed, and prompt compression.
Figure 1: End-to-end LLM tokenization and inference pipeline from UTF-8 byte ingestion and image tiling through parallel KV cache prefill and sequential decode.
Byte-Pair Encoding and Byte-Level BPE (o200k_base vs. cl100k_base)
Byte-Pair Encoding (BPE) began as a lossless compression algorithm before becoming the backbone of modern generative models. During training, BPE starts with a base alphabet, counts every adjacent symbol pair across trillions of training bytes, and greedily merges the most frequent pair into a new token until reaching the target vocabulary size.
Standard character-level BPE still failed on rare Unicode emojis or corrupted encodings. Byte-Level BPE solves that gap by treating the 256 raw UTF-8 bytes as its base alphabet, guaranteeing zero <UNK> failures for any byte sequence on earth.
Comparing o200k_base vs cl100k_base illustrates how vocabulary size improves compression. OpenAI expanded cl100k_base (a 100,000-token vocabulary) to o200k_base (a 200,000 token vocabulary), packing longer multilingual roots and common programming keywords into single IDs and reducing sequence length before transformer self-attention architecture layers execute.
WordPiece Likelihood Merging vs. Unigram Probabilistic Pruning
WordPiece powers encoder architectures such as BERT and DistilBERT. Like BPE, WordPiece builds tokens bottom-up, yet instead of merging the single most frequent pair, it scores pairs by mutual information likelihood (P(AB) / (P(A) * P(B))).
That formula prioritizes pairs whose combined occurrence exceeds random chance, marking continuation subwords with ## prefixes (such as ##ing). As detailed in the Hugging Face Transformers Tokenizer Summary, WordPiece produces strong morphological splits for classification tasks, though it remains bound to pre-tokenized word boundaries.
Unigram operates in the exact opposite direction through top-down probabilistic pruning. It initializes a massive seed vocabulary of substrings, runs an Expectation-Maximization loop to evaluate corpus probability loss if each token vanished, and discards the lowest-impact 10% to 20% per step until reaching target size.
SentencePiece Language-Agnostic Streams and Non-English UTF-8 Tax
Developed by Google, Google SentencePiece GitHub Repository wraps either BPE or Unigram without relying on whitespace pre-tokenization. It treats raw text as a continuous UTF-8 stream and encodes spaces explicitly using the visible meta-symbol _ (U+2581), making round-trip decoding lossless for whitespace-free scripts such as Japanese, Chinese, and Thai.
| Algorithm | Build Direction | Merge or Prune Metric | Whitespace Handling | Representative Model Families |
|---|---|---|---|---|
| Byte-Level BPE | Bottom-Up | Greedy adjacent byte-pair frequency | Regex pre-tokenization (" word") |
GPT-6.1 Sol, Llama 4, Qwen 3.8, Claude 5.5 |
| WordPiece | Bottom-Up | Pair likelihood ratio (P(AB)/(P(A)P(B))) |
Regex split plus ## suffix markers |
BERT, RoBERTa, DistilBERT |
| Unigram | Top-Down | Probabilistic corpus likelihood loss | Often paired with SentencePiece _ |
T5, mT5, ALBERT, XLNet |
| SentencePiece | Wrapper (BPE/Unigram) | Frequency or likelihood over raw stream | Explicit _ character in stream |
Gemini family, Gemma 4, Mistral |
Even with 200K+ vocabularies, non-English token inflation UTF-8 overhead remains a major production tax. Because UTF-8 encodes Latin ASCII characters in 1 byte and Hindi, Arabic, or Japanese characters in 3 bytes, predominantly English-trained Byte-Level BPE tables fall back to single-byte splits on non-Latin scripts.
Identical semantic prompts in Hindi, Indonesian, or Arabic routinely consume 1.5x to 3x more tokens than English equivalents. That expansion shrinks usable context windows and multiplies API invoices proportionally.
Multimodal Tokenization: Vision, Audio, and Video Token Budgets
Multimodal tokens unify text, images, audio, and video inside a single transformer context window by projecting sensory patches and acoustic frames into the exact same embedding dimensionality as text subwords. Knowing how visual tiling and acoustic sampling translate into token counts prevents silent context exhaustion when ingesting UI screenshots or call recordings.
Patch and Tile Encoding for Images (Vision Transformers)
Modern vision-language models process images through Vision Transformer (ViT) encoders rather than calling external OCR tools. The encoder slices each image into fixed pixel patches (typically 14x14 or 16x16 pixels), flattens each patch into a vector, and projects those patches into visual tokens.
Vision tokens per image calculation depends directly on image resolution and detail flags. According to the Google Gemini API Tokens Documentation, images measuring 384 pixels or less on both sides map to a flat 258 tokens per image.
Larger images automatically divide into 768x768 pixel tiles, where each tile consumes 258 tokens. A 1920x1080 desktop screenshot splits into a 3x2 grid of 6 tiles, consuming 1,548 tokens before a single word of prompt text is added.
Acoustic Frame and Temporal Video Token Rates
Native audio-language models bypass speech-to-text transcription pipelines by feeding downsampled audio spectrograms directly into acoustic encoder towers. Gemini downsamples incoming audio streams to 16 Kbps and allocates a fixed rate of 32 tokens per second, which equals 1,920 tokens per minute of audio.
Temporal video processing combines sampled video frames alongside the synchronized audio track. Under standard Gemini static ingestion rules, video consumes 263 tokens per second (roughly 15,780 tokens per minute).
| Media Modality | Encoding Unit | Tokenization Rate | Example Payload Budget |
|---|---|---|---|
| English Text | Subword / UTF-8 BPE | ~1.33 tokens per word | 750-word spec = ~1,000 tokens |
Small Image (<=384px) |
Fixed ViT patch grid | 258 tokens per image | Mobile icon or thumbnail = 258 tokens |
HD Screenshot (1920x1080) |
768x768 pixel tiles | 258 tokens per image tile | 6 tiles = 1,548 tokens |
| Native Audio | Acoustic spectrogram frames | 32 tokens per second | 10-minute support call = 19,200 tokens |
| Standard Video | Sampled frames + audio | 263 tokens per second | 2-minute screencast = 31,560 tokens |
[!TIP] Downscale high-resolution UI screenshots to 768px or 1024px before API upload unless your workflow reads tiny 8-pixel spreadsheet fonts. Cutting a 4K screenshot down to a single 768x768 tile reduces vision token spend by over 75% without degrading layout comprehension.
Token Economics: Input, Output, Reasoning Tokens, and Prompt Caching
Commercial LLM APIs price input, cached input, and output tokens on separate tiers because transformer prefill and autoregressive decode place asymmetric loads on GPU clusters. Managing input vs output token pricing, hidden reasoning chains, and prefix caches separates profitable AI features from runaway cloud spend.
Why Output Tokens Cost 4x to 5x More Than Input Tokens
Why output tokens cost more than input tokens comes down to GPU compute utilization versus memory bandwidth saturation. During prompt ingestion (the prefill phase), GPUs process all input tokens simultaneously in large, compute-bound matrix multiplications across every transformer layer.
During generation (the decode phase), the model produces one token at a time sequentially. Each generated token forces the GPU to stream billions of model weights and the accumulated Key-Value (KV) attention cache from High Bandwidth Memory (HBM) into SRAM, starving arithmetic units of work.
Because each output token ties up accelerator memory bandwidth across sequential passes, providers price output tokens 4x to 5x higher than input tokens.
Hidden Reasoning Tokens and Thinking Budgets
Frontier reasoning models such as GPT-6 Astra, o3-mini, Claude Opus 5.5, and Gemini 4 Argon allocate test-time compute before emitting a single character to the user. The model generates hidden chain-of-thought reasoning tokens internally to verify math, trace code branches, and discard flawed hypotheses.
According to the OpenAI Reasoning Models Documentation, hidden reasoning tokens are billed uniformly at the full output token rate and count toward the request’s max_output_tokens limit. Providers expose these hidden costs in response metadata under output_tokens_details.reasoning_tokens (OpenAI) or thoughts_token_count (Gemini). A short 150-token JSON answer can easily mask 3,500 billed reasoning tokens underneath.
Prompt Caching Mechanics: Anthropic, OpenAI, and Gemini
Prompt caching cost reduction eliminates redundant prefill work by storing precomputed KV cache tensors for static prompt prefixes on provider servers. Placing unchanging system instructions, few-shot examples, and MCP tool schemas at the exact start of your payload maximizes prefix hit rates.
| Model / Tier Family | Context Window | Input Cost (per 1M) | Cached Input (per 1M) | Output Cost (per 1M) | Caching Activation & Minimum Floor |
|---|---|---|---|---|---|
| GPT-6.1 Sol (OpenAI) | 200K tokens | $2.00 | $0.20 (90% off) | $10.00 | Automatic at >=1,024 tokens (128-token blocks) |
| Claude Sonnet 5.5 (Anthropic) | 200K - 1M tokens | $3.00 | $0.30 (90% off) | $15.00 | Explicit cache_control (1,024+ tokens; 1.25x write) |
| Gemini 3.8 Flash (Google) | 1M - 2M tokens | $0.15 - $0.35 | $0.04 - $0.09 (75% off) | $0.60 - $1.50 | Explicit context cache (>=4,096 tokens, TTL fee) |
| GPT-6 Luna (OpenAI) | 128K tokens | $0.15 | $0.02 (87% off) | $0.60 | Automatic prefix caching |
| DeepSeek-V4.1-Flash (API / Open) | 128K - 1M tokens | $0.28 | $0.03 (89% off) | $0.84 | Automatic disk KV prefix caching |
As documented in the Anthropic Prompt Caching Documentation, reusing cached prefixes slashes read token expenses by 90% ($0.30 vs $3.00 per million on standard enterprise tiers) while cutting time-to-first-token latency by up to 80%. Anthropic requires explicit cache_control breakpoints and charges a 1.25x write premium for 5-minute TTLs (or 2.0x for 1-hour TTLs).
Conversely, the OpenAI Prompt Caching Guide notes that OpenAI triggers KV cache reuse automatically with zero extra API flags once static prefixes reach 1,024 tokens, scaling in 128-token increments. Teams deploying multi-turn agent loops should review our prompt caching implementation guide to prevent dynamic timestamps from busting prefix hits.
Hardware Inference Performance: Tokens Per Second and KV Cache Bandwidth
When self-hosting open-weight models via vLLM, Ollama, or llama.cpp, per-token API billing disappears and tokens per second (tok/s) becomes the primary operational metric. Understanding memory bus bandwidth, quantization footprints, and KV cache growth prevents catastrophic latency spikes on local GPUs and dedicated inference servers.
Prefill Time-to-First-Token vs. Decode Intertoken Latency
Inference latency splits into two distinct phases with opposite hardware bottlenecks:
- Prefill Phase (Time to First Token, TTFT): Evaluates the entire input prompt in parallel to populate the initial KV cache. Prefill is compute-bound (FLOPS-limited), meaning tensor core throughput dictates how quickly the first token appears on screen.
- Decode Phase (Intertoken Latency, ITL): Generates output tokens sequentially, where
tokens per second = 1 / ITL. Decode is strictly memory-bandwidth-bound, because every single token requires reading all active model weights plus the growing KV cache from VRAM.
To estimate theoretical maximum decode speed on a single GPU, divide memory bandwidth (GB/s) by active model size in GB. An RTX 4090 with 1,008 GB/s memory bandwidth running a 14B Q4 model (~8.5 GB footprint) yields a practical ceiling around 65 to 85 tokens per second after kernel and KV cache overhead.
VRAM Capacity, Memory Bandwidth, and PCIe Spill Penalties
The steepest performance cliff in local serving occurs when model weights plus the active KV context cache exceed physical GPU VRAM. Once llama.cpp or Ollama spills even a handful of transformer layers across the PCIe bus into system DDR5 RAM, memory bandwidth plunges from 300–1,000 GB/s down to ~50 GB/s.
| GPU Hardware Profile | VRAM & Memory Bandwidth | Model Fit (14B Q4 ~8.8 GB) | Observed Decode Speed (tok/s) |
Operational Bottleneck |
|---|---|---|---|---|
| RTX 4060 / RTX 5060 (8GB) | 8GB (272 - 448 GB/s) | Partial PCIe offload to RAM | 5 - 8 tok/s | PCIe bus saturation; run 8B Q4 instead (~42 tok/s) |
| RTX 3060 (12GB) | 12GB GDDR6 (360 GB/s) | Full VRAM residency | 18 - 24 tok/s | Comfortable interactive speed with 4K-8K context |
| RTX 4090 (24GB) | 24GB GDDR6X (1,008 GB/s) | Full VRAM + large KV cache | 65 - 85 tok/s | Production single-user decode & batched serving |
Multi-tenant serving engines like vLLM eliminate memory fragmentation across concurrent users through PagedAttention, which allocates KV cache blocks in non-contiguous virtual memory pages. Hardware buyers sizing workstations for quantized models can inspect card-level curves in our local LLM GPU memory benchmarks.
Step-by-Step Python Implementation: Counting Tokens Across Providers
Token counting in LLMs cannot rely on len(text.split()) approximations in production pipelines. Counting tokens locally or via provider pre-flight endpoints prevents context overflow errors, validates cache_control thresholds, and enforces hard per-user spending limits.
Local BPE Counting with tiktoken and Hugging Face Tokenizers
OpenAI maintains its Rust-accelerated BPE library in the OpenAI Tiktoken GitHub Repository. For frontier OpenAI models, specify o200k_base rather than legacy cl100k_base, while open-weight deployments (Llama 4, Qwen 3.8, Gemma 4) use Hugging Face tokenizers (AutoTokenizer).
The following Python function calculates exact OpenAI token counts, verifies o200k_base vs cl100k_base compression deltas, and computes standard versus cached input spend before dispatching a request:
import tiktoken
def count_openai_tokens_and_cost(
prompt: str,
encoding_name: str = "o200k_base",
input_rate_per_1m: float = 2.00,
cached_rate_per_1m: float = 0.20,
) -> dict:
"""Count BPE tokens locally and compute uncached vs cached input cost."""
encoding = tiktoken.get_encoding(encoding_name)
token_ids = encoding.encode(prompt)
token_count = len(token_ids)
standard_cost = (token_count / 1_000_000) * input_rate_per_1m
cached_cost = (token_count / 1_000_000) * cached_rate_per_1m
return {
"encoding": encoding_name,
"token_count": token_count,
"token_ids_preview": token_ids[:8],
"standard_input_usd": round(standard_cost, 6),
"cached_input_usd": round(cached_cost, 6),
}
sample = "Analyze KV cache eviction across multi-turn MCP agent loops."
print(count_openai_tokens_and_cost(sample, "o200k_base"))
print(count_openai_tokens_and_cost(sample, "cl100k_base"))
Because tiktoken executes compiled Rust bindings locally in microseconds, applications can run this pre-flight gate on every incoming user message with negligible latency overhead. Notice that tiktoken.encode() strips special tokens by default unless allowed_special is configured explicitly, preventing accidental control-token parsing.
Pre-Flight Anthropic count_tokens and Gemini Multimodal countTokens
Anthropic and Google do not publish standalone offline BPE tables matching every model revision and multimodal tile rule. Instead, both labs expose free pre-flight token counting APIs that evaluate exact message arrays, tool schemas, cache_control breakpoints, and binary media attachments.
As documented in the Anthropic Token Counting API Documentation, passing your exact system, tools, and messages payload to client.messages.count_tokens() verifies whether static prefixes satisfy the 1,024-token prompt caching floor before paying for inference:
import anthropic
from google import genai
def count_anthropic_payload(system_prompt: str, user_query: str) -> int:
"""Verify exact Claude token budget including cache_control blocks."""
client = anthropic.Anthropic()
response = client.messages.count_tokens(
model="claude-5-5-sonnet-20260928",
system=[
{
"type": "text",
"text": system_prompt,
"cache_control": {"type": "ephemeral"},
}
],
messages=[{"role": "user", "content": user_query}],
)
return response.input_tokens
def count_gemini_multimodal_payload(image_path: str, prompt_text: str) -> int:
"""Measure exact text + tiled vision tokens via Gemini countTokens SDK."""
client = genai.Client()
uploaded_image = client.files.upload(file=image_path)
response = client.models.count_tokens(
model="gemini-3.8-flash",
contents=[prompt_text, uploaded_image],
)
return response.total_tokens
Pair pre-flight token checks with post-response usage logging from API payloads (input_tokens, cached_tokens, and reasoning_tokens). Teams building multi-tenant dashboards can combine these exact fields with automated spend circuit breakers by tracking per-user LLM token costs in Langfuse and Redis.
Production Security and Troubleshooting: Token Bugs, Injection, and Overflow
Treating tokenization as an invisible black box causes silent cache failures, context overflow crashes, and prompt injection vulnerabilities. Production AI gateways must enforce deterministic normalization, boundary sanitization, and output headroom before dispatching payloads to model endpoints.
Figure 2: Five-layer production token engineering stack protecting against special token injection, cache misses, and runaway reasoning costs.
Trailing Whitespace Cache Misses and Chat Template Drift
Modern BPE tokenizers use pre-tokenization regex rules with negative lookaheads (\s+(?!\S)) to separate trailing whitespace from following words. If a frontend editor appends a single trailing space to a cached system prompt ("You are a SQL analyst. " vs "You are a SQL analyst."), the final token ID boundary shifts completely.
That invisible 1-byte shift triggers a trailing whitespace prompt cache miss, forcing full-price prefill across a 20,000-token prefix and breaking semantic Redis caches. Always call .rstrip() on static prompt blocks and chat template segments before hashing or sending payloads.
Special Token Injection and Glitch Tokens (SolidGoldMagikarp)
Chat models rely on reserved control tokens such as <|im_start|>, <|im_end|>, <|endoftext|>, or [INST] to separate system instructions from untrusted user messages. If a backend concatenates raw user strings directly into a template without escaping or passing structured role arrays, an attacker can inject literal <|im_start|>system strings to hijack role boundaries.
To enforce special token prompt injection prevention, never format raw prompts via f-strings on self-hosted vLLM or llama.cpp endpoints without calling tokenizer.encode(user_text, add_special_tokens=False) or passing OpenAI-compatible messages arrays that escape control tokens at the engine layer.
A subtler failure involves glitch tokens such as solidgoldmagikarp or TheNitrome. Because these rare Reddit usernames appeared in tokenizer training dumps yet were filtered out or under-trained during model weight pretraining, their embedding vectors remain uninitialized outliers. Feeding them to an LLM can trigger infinite repetition loops, refusal bypasses, or sudden garbage output; gateway regex filters should quarantine known glitch strings and anomalous non-printable Unicode characters.
Context Overflow, Reasoning Exhaustion, and Payload Compression
Two recurring runtime crashes trace directly back to miscalculated token budgets:
| Production Failure Symptom | Root Tokenization Cause | Deterministic Engineering Fix |
|---|---|---|
| HTTP 400 Context Window Overflow Error | Input prompt + max_output_tokens + hidden chat wrapper overhead exceeds model context limit. |
Subtract max_output_tokens plus a 1,500-token template safety buffer before running pre-flight count_tokens. |
Empty Response (finish_reason: length) |
Hidden reasoning_tokens consumed 100% of max_output_tokens before any visible answer began. |
Raise max_output_tokens to >=16,000 for reasoning tiers or lower reasoning_effort for simple tasks. |
| 0% Prompt Cache Hit Rate | Dynamic timestamps, UUIDs, or trailing whitespace placed above static instructions. | Move dynamic variables to the final user message and .rstrip() all static prefix blocks. |
| 3x Higher Latency on Non-English or Tables | UTF-8 byte-level BPE fragmentation and repeated JSON keys inflating prompt length. | Convert wide JSON arrays into compact Markdown tables and strip Base64 blobs before prompting. |
| Character Counting & Spelling Errors (“Strawberry Problem”) | Subword BPE chunks "strawberry" into ["str", "aw", "berry"], hiding individual letter boundaries. |
Offload exact string length, regex matching, and arithmetic to deterministic Python or MCP tools. |
Enforcing these five guardrails at the API gateway turns tokenization from a silent failure source into a predictable performance lever. Audit your highest-volume endpoints first by comparing local tiktoken estimates against actual provider usage metadata, then align static prefixes for 90% cache discounts.
Frequently Asked Questions
How many tokens is 1,000 words in English?
In standard English prose, 1,000 words equal roughly 1,300 to 1,400 tokens, matching the 0.75-words-per-token rule of thumb. Source code, minified JSON payloads, and non-Latin scripts frequently expand 1,000 word-equivalents to 1,600 or over 2,500 tokens.
Why do LLMs use tokens instead of whole words?
Subword tokens prevent out-of-vocabulary failures on typos, code symbols, and newly coined terminology without bloating the embedding table to millions of entries. Character-level sequences also avoid unknown words, yet quadratic self-attention complexity makes long character streams computationally prohibitive.
Why do output tokens cost more than input tokens?
Input prompt tokens execute through transformer layers in a single parallel matrix pass during the compute-bound prefill phase. Output tokens generate sequentially one token at a time, forcing GPUs to reload full model weights and growing KV cache tensors from memory on every step.
Are hidden reasoning tokens billed as output tokens?
Yes, internal chain-of-thought tokens generated by reasoning models such as GPT-6 Astra, Claude Opus 5.5, and Gemini 4 Argon are billed at the full output token rate. Providers itemize them in response usage metadata under reasoning_tokens or thoughts_token_count while deducting them from max_output_tokens.
How many tokens does an image or minute of audio consume?
Under Google Gemini API tokenization rules, images at or below 384 pixels consume 258 tokens, while larger images tile into 768x768 chunks at 258 tokens per tile. Native audio consumes 32 tokens per second (1,920 tokens per minute), and standard video consumes 263 tokens per second.
How do you count tokens accurately before calling an LLM API?
Use OpenAI’s local tiktoken library with the o200k_base encoding for GPT models, and call Anthropic’s count_tokens endpoint for Claude payloads containing cache_control blocks. For multimodal Google Gemini requests, pass text, images, and audio directly to client.models.count_tokens().
Why do non-English prompts use more tokens than English prompts?
Most Byte-Level BPE vocabularies train predominantly on English and source code, so non-Latin UTF-8 scripts split into multi-byte fragments with fewer merged subwords. Consequently, Hindi, Arabic, Japanese, or Indonesian prompts routinely consume 1.5x to 3x more tokens than equivalent English text.
What is a good tokens per second speed for AI inference?
Single-user interactive chat feels responsive at 25 to 45 tokens per second, comfortably exceeding human reading speeds. High-throughput agent pipelines and speculative decoding endpoints commonly target 70 to over 300 tokens per second on dedicated GPU memory bandwidth.