Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 15 min · revision 2

Tokenizers in Practice: Counting Tokens and Cost

Estimate what an LLM feature will cost before you build it: count tokens with tiktoken, see how language and formatting change the count, get an exact count from the provider, turn counts into money with prices you pass in, and reconcile the estimate with the usage block the provider bills from.

Contentsand lesson path

What you will learn

  • Count tokens for a prompt and response with a tokenizer and estimate the cost of a request.

01. The problem

Your support team wants every ticket thread summarised for the next agent who picks it up: the problem, what has been tried and the next step, in at most 120 words. Before anyone writes the feature, two people want numbers. The finance lead asks what 4,000 tickets a day will cost. The engineering lead asks whether the longest threads will fit in the model's context.

Both answers are counts of tokens, and both depend on details that are easy to get wrong: which tokenizer, which parts of the request count, and which price applies to which tokens. You will work through it in six steps: look at real tokens, see what changes the count, estimate the request, get an exact count, price it, and check the estimate against what the provider actually billed.

02. Step 1: Look at the tokens

In a new folder with a virtual environment (Python 3.12 or later), install OpenAI's open-source tokenizer library with python -m pip install tiktoken. The examples were run with tiktoken 0.14. The first call to get_encoding downloads the encoding file and caches it, so it needs network access once.

Python · explore.py
import tiktoken

enc = tiktoken.get_encoding('o200k_base')

text = 'Refund requested: order #48213 arrived damaged.'
ids = enc.encode(text)
print(len(ids), 'tokens:', ids)
print([enc.decode([i]) for i in ids])
print(enc.decode(ids) == text)  # decoding gives back the exact text
Expected output (python explore.py)
10 tokens: [70182, 17222, 25, 2569, 1069, 41522, 1311, 18157, 27435, 13]
['Refund', ' requested', ':', ' order', ' #', '482', '13', ' arrived', ' damaged', '.']
True

This is byte-pair encoding (BPE) at work. The tokenizer was trained by starting from single bytes and repeatedly merging the pairs that occurred most often in a large body of text, so frequent strings became single tokens. Three details from the output matter in practice:

  • The leading space belongs to the token: requested and order are single pieces, spaces included.
  • In these encodings numbers are split into chunks of up to three digits (482 and 13), so long ids, phone numbers and amounts cost more than their length suggests.
  • Decoding the ids gives back exactly the original text. Tokenization is lossless; it is a compact, reversible encoding, not a summary.

03. Step 2: See what changes the count

Now compare two encodings, four languages and two ways of writing the same JSON record. cl100k_base is the older OpenAI encoding with about 100,000 entries; o200k_base has about 200,000.

Python · compare.py
import json

import tiktoken

ENCODINGS = [tiktoken.get_encoding(name) for name in ('cl100k_base', 'o200k_base')]

SAMPLES = {
    'English': 'Your parcel will arrive on Thursday between 9 and 12.',
    'German': 'Ihr Paket kommt am Donnerstag zwischen 9 und 12 Uhr an.',
    'Vietnamese': 'Bưu kiện của bạn sẽ đến vào thứ Năm, từ 9 đến 12 giờ.',
    'Japanese': 'お荷物は木曜日の9時から12時の間に届きます。',
}
record = {'order_id': 48213, 'status': 'damaged', 'items': ['kettle', 'mug']}
SAMPLES['JSON indented'] = json.dumps(record, indent=2)
SAMPLES['JSON compact'] = json.dumps(record, separators=(',', ':'))

print(f'{"sample":<14}{"chars":>6}{"cl100k":>8}{"o200k":>7}')
for name, text in SAMPLES.items():
    counts = [len(enc.encode(text)) for enc in ENCODINGS]
    print(f'{name:<14}{len(text):>6}{counts[0]:>8}{counts[1]:>7}')

o200k = ENCODINGS[1]
for word in ('Hello', ' Hello', 'hello', 'HELLO'):
    print(repr(word), o200k.encode(word))
Expected output (python compare.py)
sample         chars  cl100k  o200k
English           53      13     13
German            55      18     14
Vietnamese        53      28     20
Japanese          23      23     19
JSON indented     88      36     36
JSON compact      62      20     21
'Hello' [13225]
' Hello' [32949]
'hello' [24912]
'HELLO' [111642, 2699]

The same delivery message costs 13 tokens in English but 20 in Vietnamese with the newer encoding, and 28 with the older one. Vocabularies are learned from training text, so languages that were less common in it get fewer merged pieces and need more tokens for the same meaning. A larger vocabulary narrows the gap but does not close it. For your users this means higher cost and less room in the context for the same conversation. The common rule of thumb of about four characters per token holds only for English prose.

Formatting counts too: indentation and line breaks made the JSON record about 70% more expensive, with no extra information for the model. Finally, Hello, Hello, hello and HELLO are four different token sequences. That is why counts are always taken on the exact text you will send.

04. Step 3: Estimate the request

Write the system prompt and a typical thread for the summariser, plus one summary of the kind you want back, and count each part. A thread of 18 messages is simulated by repeating three lines.

Python · estimate.py
import tiktoken

enc = tiktoken.get_encoding('o200k_base')

SYSTEM = (
    'You summarise customer-support tickets for the next agent. Reply with: '
    'the problem in one sentence, what has been tried, and the next step. '
    'Use at most 120 words. Never invent order numbers or dates.'
)
TICKET = (
    'Customer: My kettle (order #48213) arrived with a cracked lid.\n'
    'Agent: Sorry to hear that! Could you send a photo of the damage?\n'
    'Customer: Photo attached. I would prefer a replacement, not a refund.\n'
) * 6  # a typical thread runs to about 18 messages
SAMPLE_SUMMARY = (
    'Problem: kettle from order #48213 arrived with a cracked lid. '
    'Tried: the customer sent a photo of the damage as requested. '
    'Next step: ship a replacement kettle and confirm the dispatch date; '
    'the customer does not want a refund.'
)


def count(text: str) -> int:
    return len(enc.encode(text))


if __name__ == '__main__':
    print('system prompt  ', count(SYSTEM))
    print('ticket thread  ', count(TICKET))
    print('sample summary ', count(SAMPLE_SUMMARY))
Expected output (python estimate.py)
system prompt   44
ticket thread   282
sample summary  48

So a typical request sends about 326 tokens of text and receives about 48. That is an estimate, for two reasons. First, the request carries more than your text: chat formats wrap each message in role markers, and tool definitions, images and documents all count as input. Second, o200k_base is the tokenizer of OpenAI models from GPT-4o to the GPT-5 family; tiktoken 0.14 has no mapping for newer models such as gpt-6-luna. If the feature runs on another provider's model, its tokenizer will split the same text differently, so the count can be off by a fair margin. tiktoken is fine for quick comparisons like the ones above; for numbers you commit to, ask the provider.

05. Step 4: Get an exact count from the provider

Anthropic, for example, offers a token-counting endpoint that takes the same system prompt, messages and tools as a real request and returns the input token count for the model you name. It is free to call, has its own rate limit and generates nothing. Install the SDK with python -m pip install anthropic, put your key in the ANTHROPIC_API_KEY environment variable and choose the model with ANTHROPIC_MODEL (for example claude-sonnet-5-5). Save the script next to estimate.py, which it imports.

Python · count_claude.py
import os

import anthropic

from estimate import SYSTEM, TICKET

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
result = client.messages.count_tokens(
    model=os.environ.get('ANTHROPIC_MODEL', 'claude-sonnet-5-5'),
    system=SYSTEM,
    messages=[{'role': 'user', 'content': TICKET}],
)
print('input tokens (Claude):', result.input_tokens)
Example output (illustrative; the count depends on the model)
input tokens (Claude): 402

The count is model-specific even within one provider: Claude models from Opus 4.7 onwards use a newer tokenizer that produces approximately 30% more tokens for the same text than earlier Claude models; the exact increase depends on the content. Recount whenever you change models, and never reuse a count measured on one model to price another. Other providers offer similar endpoints or publish their tokenizers; check the documentation of the one you use.

06. Step 5: Turn tokens into money

Providers price input and output tokens separately, per million tokens, and prices change often. Keep them out of your logic: pass them in, and copy the figures from the provider's pricing page into configuration. The figures below are examples, not a quote.

Python · cost.py
from dataclasses import dataclass


@dataclass(frozen=True)
class Prices:
    """US dollars per million tokens, copied from your provider's pricing page."""

    input: float
    output: float
    cache_write: float = 0.0
    cache_read: float = 0.0


def request_cost(
    prices: Prices,
    input_tokens: int,
    output_tokens: int,
    cache_write_tokens: int = 0,
    cache_read_tokens: int = 0,
) -> float:
    total = (
        input_tokens * prices.input
        + output_tokens * prices.output
        + cache_write_tokens * prices.cache_write
        + cache_read_tokens * prices.cache_read
    )
    return total / 1_000_000


if __name__ == '__main__':
    prices = Prices(input=2.00, output=10.00)  # example figures, not a quote
    per_request = request_cost(prices, input_tokens=44 + 282, output_tokens=48)
    tickets_per_day = 4_000
    print(f'per request: ${per_request:.6f}')
    print(f'per 30 days: ${per_request * tickets_per_day * 30:,.2f}')
    worst = request_cost(prices, input_tokens=44 + 2_000, output_tokens=300)
    print(f'long thread, long answer: ${worst:.6f}')
Expected output (python cost.py)
per request: $0.001132
per 30 days: $135.84
long thread, long answer: $0.007088

At these example prices the feature costs about $136 a month, and the long case is six times the typical one. Two price rules change estimates in real projects:

  • Output is the expensive side. Here 48 output tokens cost about three quarters as much as 326 input tokens. Reasoning models also write thinking tokens before the answer, and those are billed as output even when you never see them.
  • Some input is cheaper or dearer. Input served from a prompt cache is billed at a fraction of the normal price, writing to the cache can cost more, and batch processing is often discounted. Prices has fields for cache writes and reads; the cost-control skill covers when caching pays off.

07. Step 6: Reconcile with the usage block

Every response reports what the request actually consumed in a usage block, and that is what the provider bills. The JSON below has the shape of an Anthropic Messages API response, saved to a file so the step runs without a key; its numbers are illustrative.

response.json (illustrative)
{
  "id": "msg_example",
  "type": "message",
  "role": "assistant",
  "model": "claude-sonnet-5-5",
  "content": [{"type": "text", "text": "Problem: kettle from order #48213 ..."}],
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 402,
    "output_tokens": 61,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0
  }
}
Python · billed.py
import json

from cost import Prices, request_cost

with open('response.json', encoding='utf-8') as f:
    response = json.load(f)

usage = response['usage']
prices = Prices(input=2.00, output=10.00, cache_write=2.50, cache_read=0.10)
billed = request_cost(
    prices,
    input_tokens=usage['input_tokens'],
    output_tokens=usage['output_tokens'],
    cache_write_tokens=usage.get('cache_creation_input_tokens') or 0,
    cache_read_tokens=usage.get('cache_read_input_tokens') or 0,
)
print('stop reason:', response['stop_reason'])
print('input / output tokens:', usage['input_tokens'], '/', usage['output_tokens'])
print(f'billed cost: ${billed:.6f}')
Expected output (python billed.py)
stop reason: end_turn
input / output tokens: 402 / 61
billed cost: $0.001414

The billed request used 402 input tokens where tiktoken estimated 326, so this request cost about 25% more than the Step 5 estimate. That gap is exactly why you log usage for every call and recalibrate estimates from real traffic. Field names differ between APIs: OpenAI's Chat Completions API, for instance, reports prompt_tokens and completion_tokens. Also check the stop reason: max_tokens means the answer was cut off at your output limit, and you still paid for every token of it.

08. Common mistakes

09. Check your understanding

Practice check · 3 questions

Counting and pricing tokens

Three situations from the worked example.

Q1. In compare.py, 'Hello' and ' Hello' get different token ids. Why?
Q2. A report writer reads a 300-token note and writes a 2,000-token report, and the provider charges five times more per output token than per input token. Which change saves the most money?
Q3. You put 500 order records into a prompt as JSON indented with two spaces. What does switching to compact JSON do?
Practice only: not graded, not saved, not evidence.

10. Apply it

Prepare the measuring tools for this skill's practice project, the budgeted request builder:

  1. Write count_parts(system, history, passages, question) that returns the token count of each part and the total, using o200k_base or, if your provider offers one, its counting endpoint.
  2. Build three sample conversations, short (3 turns), medium (30 turns) and very long (300 turns), and print the counts for each.
  3. Put your provider's current prices in a configuration file, read them into Prices, and print the cost per request and per 1,000 requests for each sample.
  4. If you already have API access, send the medium sample once and record how far your estimate was from the usage block.

Keep the code: the lab later in this skill builds on the same counting functions.

11. Review prompt

Without looking back, explain why the same sentence can have different token counts under two tokenizers and in two languages. List four things besides the user's message that count as input tokens, write the cost formula for one request with prices per million tokens, and name the part of a response that tells you what was actually billed.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check