LevelUpWith

Explore / Context Engineering and Memory for LLM Agents / Lesson 1

Lesson 1: Tokens: What the Model Actually Reads

Learn how text, code and JSON become tokens, why each provider's tokenizer counts the same input differently, and why the context window is a limited budget and not free space.

Free to read, no account needed. Part of Context Engineering and Memory for LLM Agents.

By the end of this level you'll be able to

  • Count tokens for the same prompt with the token-counting tools or endpoints of Claude, OpenAI, Gemini and an open-weight model, in Python or TypeScript
  • Explain why code, JSON and non-English text use tokens at different rates than prose
  • Tell the difference between a model's maximum context size and the amount of context it handles well

Why start with tokens?

Every later lesson in this course comes back to one question: what should the model read? To answer it you need the unit the model reads in. That unit is the token, not the character or the word. You pay per token, limits are set in tokens, and a long prompt is long in tokens. If you can't count them, you can't budget them.

A tokenizer splits text into pieces from a fixed vocabulary. Common English words are often one token each. Rare words, odd identifiers, punctuation runs and many non-Latin scripts get split into several pieces. Think of it like gzip with a dictionary trained mostly on one kind of data: input that looks like the training data compresses well, and everything else costs more.

The key point is that each model family has its own tokenizer, so the same string gives different counts on Claude, OpenAI, Gemini and an open-weight model. Counts can even change within one vendor. Anthropic's docs say Claude Opus 4.7 and later models use a newer tokenizer that produces roughly 30% more tokens for the same text than earlier Claude models. Never reuse a count measured on one model for another.

Walkthrough: count one prompt four ways

Use one shared prompt that mixes prose, code and JSON, the way agent inputs usually do.

# count_tokens.py  (pip install anthropic openai google-genai transformers tiktoken)
PROMPT = '''Summarise this function and its config.
def retry(fn, attempts=3):
    for i in range(attempts):
        try:
            return fn()
        except TimeoutError:
            pass
{"service": "billing", "retries": 3, "timeout_ms": 2500}'''

# 1. Claude: the server-side count endpoint is free, but it has its own rate limit
import anthropic
c = anthropic.Anthropic()
r = c.messages.count_tokens(
    model="claude-opus-5-5",  # check the current models list
    messages=[{"role": "user", "content": PROMPT}],
)
print("claude", r.input_tokens)

# 2. OpenAI: POST /responses/input_tokens takes the same payload as responses.create
from openai import OpenAI
o = OpenAI()
r = o.responses.input_tokens.count(model="gpt-6.2-astra", input=PROMPT)  # use a current model ID
print("openai", r.input_tokens)

# 3. Gemini: the field is total_tokens, not input_tokens
from google import genai
g = genai.Client()
r = g.models.count_tokens(model="gemini-4-hydrogen", contents=PROMPT)  # use a current model ID
print("gemini", r.total_tokens)

# 4. Open-weight: the tokenizer ships with the weights, so counting is local and offline
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-7B-Instruct")
raw = len(tok.encode(PROMPT))
chat = len(tok.apply_chat_template([{"role": "user", "content": PROMPT}], tokenize=True))
print("qwen raw", raw, "with chat template", chat)  # the template adds role/boundary tokens

The TypeScript SDKs use the same calls with camelCase names:

const a = await anthropic.messages.countTokens({ model, messages });      // a.input_tokens
const o = await openai.responses.inputTokens.count({ model, input });     // o.input_tokens
const g = await genai.models.countTokens({ model, contents: PROMPT });    // g.totalTokens
// Open-weight in Node: AutoTokenizer.from_pretrained(...) from @huggingface/transformers

Gotcha: local counts are approximate. You can count OpenAI-style text offline with tiktoken.get_encoding("o200k_base"). OpenAI's own guide warns that local tokenizers miss the tokens added for message roles and boundaries, tool schemas, images and files. Use local counting for quick loops and the provider endpoint when the number matters. The Qwen example above shows the same thing: the chat template adds tokens that a raw encode does not count.

Gotcha: the count is the whole request. Tool definitions, system prompts and earlier turns all count. Anthropic's docs show one small get_weather tool turning a one-line question into a count of about 400 tokens.

Why code, JSON and non-English text cost more

Try this experiment. Count the same data written as a prose sentence, as pretty-printed JSON and as minified JSON:

import json, tiktoken
enc = tiktoken.get_encoding("o200k_base")
rec = {"service": "billing", "retries": 3, "timeout_ms": 2500}
for label, s in [
    ("prose", "The billing service retries 3 times with a 2500 ms timeout."),
    ("pretty", json.dumps(rec, indent=4)),
    ("minified", json.dumps(rec, separators=(",", ":"))),
]:
    print(f"{label:9} chars={len(s):3} tokens={len(enc.encode(s))}")

Here is what you will see, and why:

  • JSON spends tokens on structure: quotes, braces, colons, repeated key names and, when pretty-printed, indentation. None of that is content, but all of it is billed. Run the script to see how much indentation alone adds.
  • Code is full of identifiers like timeout_ms or getUserByIdAsync that are split into several pieces, plus operators and whitespace. A 400-line file can cost much more than 400 lines of prose.
  • Non-English text depends on how much of each language the tokenizer's vocabulary covers. Research on OpenAI's o200k_base tokenizer measured Hindi at about 1.5× as many tokens as the same content in English, with larger gaps for some other Indic languages. The newer tokenizer narrowed the gap but did not close it.

Rules of thumb such as Google's "about 4 characters per token" for Gemini are fine for a quick estimate of English prose. They are wrong for code, JSON and other languages, which is where agents spend most of their tokens.

Maximum context vs. usable context

A model's context window is a hard limit: everything in the request, and the output, must fit. If the input alone is too large, Claude's API returns a 400 error. Advertised windows are now large; many current Claude models offer 1M tokens.

Treat that number like a credit limit, not a balance you should spend. Anthropic's own documentation says that as token count grows, accuracy and recall degrade. NVIDIA's RULER benchmark measured this directly: every model tested claimed at least 32K of context, yet only about half could still pass at 32K, and almost all dropped below the pass threshold before reaching their advertised length. The size a model handles well for your task is something you measure, not something you read on a spec sheet. Later lessons cover why this happens and what it costs.

Hands-on exercise

  1. Run count_tokens.py against all four providers and record the counts in a table.
  2. Add three variants of the prompt: minified JSON, the same content as a markdown bullet list, and a German or Hindi translation. Count each one on every provider.
  3. For the open-weight model, record both the raw count and the chat-template count, and explain the difference in one sentence.
  4. Write down the largest and smallest ratios between providers that you saw. Note which content type varied most.

Key takeaways

  • Models read tokens, and each provider's tokenizer counts the same text differently, sometimes even between versions from the same vendor.
  • Use the provider's count endpoint when the number matters. Local tokenizers miss role, tool and template overhead.
  • Code, JSON and non-English text use more tokens per character than English prose, so characters ÷ 4 is only a rough guess.
  • The advertised context window is a ceiling, not a target. Usable context is smaller, and you have to measure it.

A 6-question knowledge check follows this lesson in the app, free and without an account.

More like this