Skip to main content
Module 1 · Lesson 1 of 41/48 in the course~15 min
Module lessons (1/4)

How LLMs Process Text: The Tokenizer Deep Dive

How LLMs Read Text: The Subword Tokenizer

Large Language Models do not process characters or words directly. Instead, they ingest sequences of discrete integer Token IDs generated by a subword tokenizer (most commonly Byte-Pair Encoding, or BPE).

A common rule of thumb for English text is:

  • 1 token ≈ 4 characters (or ~0.75 words).
  • 1,000 tokens ≈ 750 words.

However, this ratio diverges significantly when processing source code, JSON keys, numbers, or non-Latin alphabets (such as Arabic, Hindi, or Japanese), where single characters often split into multiple UTF-8 byte tokens.

Modality / ContentTypical Ratio (Chars / Token)Why It Matters
Standard English prose~4.0 chars / tokenBaseline cost for prompts
Python / JS Source Code~2.5 - 3.0 chars / tokenIndentation and punctuation expand
JSON API Payloads~2.2 - 2.8 chars / tokenRepeated keys & quotes consume TPM
Non-Latin Scripts~1.2 - 1.8 chars / tokenUTF-8 multibyte fragmentation

Interactive Tokenizer & Compression Lab

Experiment with real-time Byte-Pair Encoding subword segmentation across prose, source code, JSON payloads, and multibyte Unicode:

Token Counting & Budget Estimation in Python

In production systems, estimating token counts before dispatching requests to LLM APIs is essential to prevent context_length_exceeded runtime errors and manage Rate Limits (Tokens Per Minute — TPM).

Python
def estimate_tokens(text: str, chars_per_token: float = 4.0) -> int:
    """Fast pre-flight token estimate before calling model APIs."""
    if not text:
        return 0
    return max(1, int(len(text) / chars_per_token))

prompt = "Explain the difference between dense and sparse vector embeddings in detail."
print(estimate_tokens(prompt))  # ~19 tokens

Check Your Understanding

Quiz#ai-engineering.m1.l1.q1

Why do non-Latin alphabets (like Japanese or Arabic) consume more tokens per sentence than English?

Answer options

Practice: Subword Token Counting & Sliding Windows

Practice Stage

Warmup — Estimate token budgets

Exercise#ai-engineering.m1.l1.e1
Attempts: 0Loading…

Write estimate_prompt_cost(num_chars, rate_per_million, chars_per_token=4.0) that calculates the dollar cost of processing a prompt. Round the cost to 6 decimal places.

Loading editor…
Show hint

Compute tokens as num_chars / chars_per_token, then multiply (tokens / 1_000_000) by the rate per million.

Solution available after 3 attempts

Practice Stage

Practice — Safe token truncation

Exercise#ai-engineering.m1.l1.e2
Attempts: 0Loading…

Write truncate_to_budget(text, max_tokens, chars_per_token=4.0) that truncates text so estimated tokens never exceed max_tokens. Return the truncated string.

Loading editor…
Show hint

Compute max_chars = int(max_tokens * chars_per_token) and slice text[:max_chars].

Solution available after 3 attempts

Practice Stage

Mastery — Multi-document token allocator

Exercise#ai-engineering.m1.l1.e3
Attempts: 0Loading…

Write allocate_token_budget(scores, total_budget) that accepts a list of positive float relevance scores and returns a list of integer token budgets proportional to each score, summing to total_budget.

Loading editor…
Show hint

Normalize scores to sum to 1.0, multiply by total_budget, and assign any rounding remainder to the highest-scoring document.

Solution available after 3 attempts