Tokens

In One Sentence (TL;DR)

The sub-word units LLMs actually read, count, and bill against—roughly 3–4 English characters per token.

What It Is

Before an LLM processes text, a tokenizer (such as Byte-Pair Encoding / BPE) splits words, punctuation, whitespace, and code into integer IDs called tokens. Common words like 'function' are 1 token, while rare words, JSON keys, UUIDs, and non-English scripts break into multiple tokens—and both API latency and billing scale directly with total input + output tokens.

Software Engineering Analogy

Tokens are like serialized protobuf frames or byte blocks: your code writes human-readable strings, but the model's parser reads and meters token chunks.

How It Works (Step-by-Step)

  1. 01Text enters the model's tokenizer before touching the neural network.
  2. 02Frequent sequences (' the', 'return', 'ing') map to single integer IDs in a vocabulary of ~50k–250k tokens.
  3. 03Output tokens are generated sequentially one by one, making output tokens ~3–5x slower and more expensive than input tokens.

Real-World Scenario

Sending a 2,000-line JSON payload with deeply nested keys and UUIDs can consume 3x more tokens than a compact Markdown table containing the exact same facts—tripling your API bill and slowing time-to-first-token.

When to Use vs. When NOT to Use

When to Use

Always count tokens before chunking documents, truncating chat history, or projecting unit economics per user.

When NOT to Use

Never estimate context limits by character count alone when dealing with code, JSON, or multilingual text.

Common Beginner Mistakes

  • Assuming 1 word = 1 token (in practice, 100 words is roughly 130–150 tokens, and verbose JSON is much higher).
  • Ignoring output token costs when letting models write long essays for simple yes/no decisions.
  • Forgetting that system prompts and tool JSON schemas are billed on every single turn.

Code Example

Pre-flight token counting & cost guard · python
from google import genai

client = genai.Client()

system_prompt = "Summarize git diffs in 3 bullet points."
diff_payload = "+ const ttlSeconds = 300; // cache API responses\n" * 40

token_info = client.models.count_tokens(
    model="gemini-2.5-flash",
    contents=[system_prompt, diff_payload],
)

MAX_INPUT_TOKENS = 4000
if token_info.total_tokens > MAX_INPUT_TOKENS:
    raise ValueError(f"Prompt too large: {token_info.total_tokens} tokens")

print(f"Safe to send: {token_info.total_tokens} input tokens")