Tokens in AI: A Practical Guide

When an AI application sends a prompt to a language model, the model does not read a string of words in the same way a person does. It receives a sequence of numbers called token IDs. Those IDs represent pieces of text from a model-specific vocabulary.

Tokens are the unit behind several practical limits and measurements:

  • how much text fits in a model's context window;
  • how long a prompt or response takes to process;
  • how many output steps a model can generate; and
  • how much a metered API request costs.

Tokenization is not just an implementation detail. It is part of the model's input contract, so the tokenizer must match the model that will consume the token IDs.

1. What Is a Token?

A token is a piece of text selected by a tokenizer. Depending on the tokenizer and the input, it might be a whole word, part of a word, punctuation, whitespace, or a special control marker.

For example, a tokenizer might split this sentence conceptually like this:

Tokenization makes language computable.
["Token", "ization", " makes", " language", " comput", "able", "."]

The exact pieces above are illustrative. Different tokenizers can split the same sentence differently. A token ID is an integer assigned to one entry in a model's vocabulary, so the model receives something like:

[18492, 321, 925, 1840, 7132, 421, 13]

The IDs have no universal meaning. ID 18492 in one model may represent an entirely different token in another model.

Tokens are not words

There is no fixed conversion from words to tokens. As a rough planning estimate, English text often uses about 1 token for every 3 to 4 characters, or about 1.3 tokens per word. That estimate varies with punctuation, whitespace, spelling, and the language.

Code, JSON, URLs, identifiers, and text with many uncommon symbols can use substantially more tokens than ordinary prose. A short variable name may be one token in one model and several tokens in another.

2. How Tokenization Works

Most current language-model tokenizers use a subword vocabulary. During tokenizer training, frequent pieces are kept as useful units and less common words can be represented by combining smaller pieces. This gives the model a practical vocabulary size without requiring one entry for every possible word.

A simplified input path is:

text -> tokenizer -> token IDs -> model -> logits -> selected token ID -> decoded text

The tokenizer can also add special tokens. These may mark the beginning or end of a sequence, padding, or the boundary between messages in a chat template. Special tokens count toward the model's context in the same way as other input positions.

A tokenizer is paired with a model

The tokenizer and model must agree on at least:

  • the vocabulary and token-to-ID mapping;
  • normalization rules, such as casing or Unicode handling;
  • special-token IDs;
  • the chat or prompt template; and
  • truncation and padding conventions.

Using a tokenizer from a different model family can produce valid-looking integers that the model interprets incorrectly. Always load the tokenizer recommended by the model's documentation or API.

3. Counting Tokens with Python

For a local Hugging Face model, inspect the exact tokenizer used by that model:

from transformers import AutoTokenizer

model_name = "distilgpt2"
tokenizer = AutoTokenizer.from_pretrained(model_name)

text = "Token counts depend on the model and the input."
encoded = tokenizer(text, add_special_tokens=False)

print(encoded["input_ids"])
print("count:", len(encoded["input_ids"]))
print("pieces:", tokenizer.convert_ids_to_tokens(encoded["input_ids"]))

For a chat model, count the fully formatted request when possible, not only the visible user message. System instructions, role markers, chat-template tokens, and previous conversation turns all contribute to the input count.

messages = [
		{"role": "system", "content": "Answer concisely."},
		{"role": "user", "content": "Explain tokenization."},
]

prompt = tokenizer.apply_chat_template(
		messages,
		tokenize=False,
		add_generation_prompt=True,
)
encoded = tokenizer(prompt, add_special_tokens=False)
print(len(encoded["input_ids"]))

For a hosted model, use the provider's tokenizer or usage metadata when available. A third-party estimate is useful for planning, but it is not a billing record.

4. Why Counts Vary by Model

Tokenization is learned or configured separately for each model family. Two models can receive the same text and produce different token sequences because they use different vocabularies, merge rules, normalization, and special tokens.

Consider the text:

Transformers tokenize `data_pipeline_v2`.

One tokenizer might represent Transformers as one common piece and split the identifier into several pieces. Another might split the word itself differently but keep the underscore-separated identifier more efficiently. Neither count is universally correct; each is correct for its own model.

The variation is even more visible outside common English prose:

  • Code: indentation, punctuation, operators, and long identifiers create many boundaries.
  • JSON: quotation marks, braces, property names, and repeated structure consume tokens.
  • URLs: uncommon strings and separators are often split into many pieces.
  • Languages other than English: a tokenizer's training mix affects how efficiently it represents each language.
  • Emoji and Unicode: a single visible character may map to multiple tokens.
  • Long numbers: digits may be grouped differently depending on the vocabulary.

This is why a context limit described as “128K” means approximately 128,000 model-specific token positions, not 128,000 words or characters.

5. Context Window and Token Budgets

The context window is the maximum number of tokens a model can consider in one request. A request normally contains both the input and the generated output:

input tokens + requested output tokens <= model context limit

For example, if a model supports 8,192 tokens and the prompt uses 6,000 tokens, there may be room for at most about 2,192 output tokens. API-specific system tokens or formatting can reduce the remaining space further.

A useful application budget tracks these separately:

  • input_tokens: instructions, documents, tools, and conversation history;
  • max_output_tokens: the upper bound requested for generation; and
  • total_tokens: input tokens plus tokens actually generated.

max_output_tokens is a ceiling, not a promise that the model will use all of them. The model can stop earlier because it reaches an end marker, completes the answer, or hits another stop condition.

Long conversations grow because previous turns are sent again as context. Common ways to control growth include summarizing old turns, retrieving only relevant documents, trimming tool results, and setting explicit output limits.

6. How Token Generation Works

An autoregressive language model generates one token at a time. Given the current sequence, it calculates a score, called a logit, for every possible next token. A decoding strategy turns those scores into the next token choice.

The simplified loop is:

1. Tokenize the prompt.
2. Run the model on the current token sequence.
3. Read the next-token logits.
4. Choose one next token using a decoding strategy.
5. Append it to the sequence.
6. Stop or repeat from step 2.

With greedy decoding, the highest-scoring next token is selected. Sampling introduces controlled variation. Common controls include:

  • temperature: changes how concentrated or varied the probability distribution is;
  • top-p: samples from the smallest group of tokens whose cumulative probability reaches a threshold; and
  • stop sequences or end tokens: tell generation when to finish.

These settings change which token is selected, not the tokenizer or the price of each token. More sampling can make output varied, but it does not guarantee more accurate output.

Input and output tokens are different work

The model must process the prompt before it can generate. It then performs additional generation steps for each output token. A long prompt can therefore cost time and input tokens even when the response is short; a long response consumes more output tokens and generation steps.

Streaming changes when tokens are delivered to the client, not how many tokens the model generates. A streamed response still has the same underlying token usage.

7. Token Counts and API Cost

Many hosted APIs price input and output tokens separately. A general calculation is:

input cost  = input tokens  / 1,000,000 * input price per million
output cost = output tokens / 1,000,000 * output price per million
total cost  = input cost + output cost

Suppose an illustrative model charges $2 per million input tokens and $8 per million output tokens. A request with 12,000 input tokens and 1,500 output tokens costs:

input:  12,000 / 1,000,000 * $2 = $0.024
output:  1,500 / 1,000,000 * $8 = $0.012
total:                             $0.036

These prices are examples for the calculation only. Provider prices, cached-input discounts, batch rates, fine-tuning rates, and model names change, so use the current pricing page and the usage fields returned by the API for production accounting.

Estimating a monthly budget

For a rough forecast, multiply the average request volume by average token usage:

monthly cost = requests per month *
	(average input tokens * input rate + average output tokens * output rate)

Keep the units consistent. If rates are per million tokens, divide the token totals by one million before multiplying by the rates. Measure real traffic after launch because prompts often grow through conversation history, retrieved documents, or tool output.

Local inference has a different cost shape. You may avoid a per-token provider charge, but still pay for GPU or CPU time, memory, electricity, hosting, observability, engineering, and model downloads. A local model is not automatically cheaper; compare total cost at the expected utilization and quality level.

8. Practical Ways to Reduce Token Usage

Token optimization should preserve the information the model needs. Useful techniques include:

  1. Remove repeated instructions and unnecessary examples.
  2. Summarize old conversation turns instead of resending them verbatim.
  3. Retrieve a small, relevant set of document chunks rather than an entire corpus.
  4. Return only the fields needed from tools and databases.
  5. Use concise structured formats when they are easier for the model to parse.
  6. Set a reasonable output limit and stop generation when the task is complete.
  7. Measure quality before and after shortening prompts; the cheapest incorrect answer is still expensive.

Do not optimize only for the visible character count. A shorter prompt in a model's tokenizer may be cheaper than a similarly sized prompt in another model, and a compact prompt that causes retries can cost more overall.

9. A Small Diagnostic Checklist

When an application exceeds a token limit or costs more than expected, inspect:

  • which tokenizer or provider usage field produced the count;
  • whether system prompts and chat-template markers are included;
  • how much conversation history is being resent;
  • whether retrieved documents or tool responses are unexpectedly large;
  • whether input and output rates are being applied separately;
  • whether retries, failed requests, and streaming reconnections are counted; and
  • whether the model's context limit is being confused with its output limit.

Log token counts alongside request IDs, latency, model names, and application features. Avoid logging sensitive prompt content merely to measure size; token counts and redacted metadata are often enough.

Conclusion

Tokens are model-specific pieces of text represented as integer IDs. A tokenizer converts input text into those IDs, the model predicts one next token at a time, and a decoder converts the resulting IDs back into text. Counts depend on the model, language, formatting, code, chat template, and special tokens.

The most reliable workflow is to count with the exact tokenizer or API associated with the model, reserve context for both input and output, and calculate input and output costs separately. Once those measurements are part of application telemetry, context limits and token bills become engineering values that can be planned and improved rather than surprises discovered after deployment.