What Are Tokens in AI?
The tiny pieces of text that every AI model reads, writes, and charges you for. Learn what they are, how they are made, and why they quietly control the cost, speed, and memory of every AI tool you use.
Type a question into an AI chatbot and an answer appears in a few seconds. It feels as if the machine reads your words the way you do. It does not. Before the AI sees anything, your text is chopped into small pieces called tokens, and those pieces are the only thing the model ever works with.
Tokens decide how much you can paste into a chat, why a long answer sometimes stops in the middle, how much an AI product costs to run, and even why some models struggle to count the letters in a word. If you are a student, a developer, an architect, or just someone who uses AI tools every day, tokens are one of the most useful ideas you can learn.
This guide starts from zero. Every new word is explained when it first appears, every big idea gets an everyday comparison, and real companies and real numbers are used wherever possible. By the end, you will know what a token is, how text becomes tokens, what the model does with them, and how to control them in real projects.
1What Is a Token?
A token is the smallest unit of text that an AI model treats as one single thing.
The simple definition
A token is a small chunk of text. It might be a whole word like cat, a piece of a longer word like believ or able, a single character, a punctuation mark such as !, or even a space attached to the front of a word. The AI model does not see sentences or words. It sees a long row of tokens, one after another.
Take the word “unbelievable”. A human sees one word. A typical AI tokenizer might split it into three pieces: “un”, “believ”, and “able”. The word “cat” is so common that it usually stays as one token. The exact split depends on the tokenizer, which is the tool that does the chopping, and we will meet it properly in a later chapter.
Why tokens exist
Computers only understand numbers. They cannot do math on the letter “a” or on the word “apple”. So before a model can learn from text or answer a question, the text must be turned into numbers. Tokens are the middle step. First, text is cut into tokens. Then each token is swapped for a number. The model only ever handles those numbers.
Where tokens are used
Every modern language model works this way. ChatGPT from OpenAI, Gemini from Google, Claude from Anthropic, and Llama from Meta all read and write tokens. The same idea is also used for code, images, and sound, which we will cover later. Whenever an AI product shows a limit such as “128,000 tokens”, or a price “per million tokens”, it is talking about these pieces.
Think of LEGO. You never build a toy house out of one giant block of plastic. You build it from small bricks that snap together. Language models treat text the same way: every sentence is built from a fixed set of small bricks called tokens. A model can build any sentence in the world, even one it has never seen, by snapping its bricks together in a new order.
A handy rule of thumb
For normal English, one token is roughly four characters, or about three quarters of a word. So 100 tokens is about 75 words. A short paragraph of 75 words is about 100 tokens, and a full page of text is often somewhere near 500 to 700 tokens. These are only averages, but they are good enough for quick planning.
In security, the word “token” has a different meaning. A login token or an API token is a secret key that proves who you are. In this guide, a token always means a piece of text that an AI model reads. The two ideas share a name and nothing else.
2A Short History: From Words to Pieces
Tokens did not appear overnight. Researchers tried several ideas before settling on today’s approach.
Early language software was simple. It split text on spaces and treated every word as one unit. This worked for small projects, but it had a big problem. Any word that was not in the program’s word list, such as a new slang term, a name, or a spelling mistake, became an “unknown” and was thrown away. The model could not read it at all.
The fix came from an unexpected place: file compression. The story below shows how an old compression trick became the foundation of modern AI text handling.
1994: Byte pair encoding is born
Philip Gage describes a compression method that repeatedly replaces the most common pair of neighboring symbols with one new symbol. It was made to shrink files, not to help AI.
2012: WordPiece at Google
Mike Schuster and Kaisuke Nakajima build a method to split words into smaller pieces for Japanese and Korean voice search, languages where spaces do not mark word boundaries.
2015 and 2016: Subwords for translation
Rico Sennrich and colleagues show that applying byte pair encoding to text lets translation models handle rare and brand-new words by building them from smaller parts.
2018: BERT and SentencePiece
Google’s BERT model uses WordPiece with a vocabulary of about 30,000 pieces. In the same year, Taku Kudo and John Richardson release SentencePiece, a tool that works on raw text in any language.
2019 onward: Byte-level tokenizers
OpenAI’s GPT-2 uses a byte-level version of byte pair encoding. Because it starts from raw bytes, it can represent any text at all, including emoji and rare scripts, without an “unknown” bucket.
Today almost every major language model uses some form of subword tokenization. The details differ between companies, but the big idea stays the same: break text into reusable pieces that are bigger than letters and often smaller than words.
3Words, Letters, or Pieces? The Trade-offs
There are three ways to cut text. Each one has a cost, and subword pieces strike the best balance.
Option one: one token per word
This feels natural, but English alone has hundreds of thousands of words, plus names, typos, and new slang every week. A word-based list would be enormous, and any word missing from the list would be lost. Languages that build long words by gluing parts together, such as German, make the problem even worse.
Option two: one token per character
Here the list is tiny. A few hundred symbols cover almost everything, and no word can ever be “unknown”. The catch is length. A single sentence becomes a very long row of tokens, and a model has to work much harder to learn that the letters c-a-t together mean a small furry animal.
Option three: subword pieces
Subword tokenizers keep common words whole and break rare words into familiar parts. The word “the” stays as one token. A rare word such as “photosynthesizing” might become a few pieces. This keeps the vocabulary at a manageable size, keeps sentences reasonably short, and still handles brand-new words.
| Approach | Vocabulary size | Length of a sentence | Handles new words? |
|---|---|---|---|
| Whole words | Very large | Short | No, creates unknowns |
| Single characters | Very small | Very long | Yes |
| Subword pieces | Medium (30,000 to 250,000) | Medium | Yes |
Imagine packing for a house move. If you carry every single item loose, like one sock and one spoon at a time, you will make hundreds of trips. If you only use giant pre-made boxes, you will not have a box for odd items. Subword tokens are like a set of boxes in several sizes: big boxes for common things, small ones for the odd leftovers. Everything fits, and the number of trips stays sensible.
Advantages of subword tokens
- No true “unknown” words, because anything can be built from smaller parts.
- A vocabulary of a manageable size, which keeps the model smaller and faster.
- Related words share pieces, so the model can see that “play”, “playing”, and “player” are cousins.
- Works for many languages with one method.
Disadvantages and trade-offs
- Splits can look strange to humans and hide letters inside chunks.
- Languages that were rare in the tokenizer’s training data get cut into many tiny pieces, which costs more.
- Numbers and spelling tasks become harder, because the model does not see individual digits or letters directly.
- Each model has its own tokenizer, so counts cannot be compared directly between models.
4How Text Becomes Tokens, Step by Step
The tokenizer is a small program that sits at the front door of every language model.
A tokenizer is the tool that turns text into tokens and turns tokens back into text. It is not the AI model itself. It is a separate piece of software that follows fixed rules learned in advance. The same tokenizer must be used when the model is trained and when it is used, or the numbers would mean different things.
Clean and prepare the text
Some tokenizers tidy the text first, for example by making sure special characters are stored in a standard way. Modern ones try to change as little as possible so no information is lost.
Split into rough chunks
The text is first divided into large chunks, such as words with their leading spaces, numbers, and punctuation. This stops pieces from merging across word borders in odd ways.
Break chunks into known pieces
Each chunk is matched against the tokenizer’s list of learned pieces. Common chunks stay whole. Rare chunks are cut into smaller parts that exist in the list.
Swap each piece for a number
Every piece has a fixed ID in the tokenizer’s vocabulary. The text now becomes a list of whole numbers, which is the form the model can actually use.
Hand the numbers to the model
The model converts each ID into a long list of numbers that describes its meaning, processes everything, and later produces new IDs that are converted back into text.
flowchart LR
A["Your text"] --> B["Tokenizer splits text into pieces"]
B --> C["Token IDs: a list of whole numbers"]
C --> D["Embedding layer: each ID becomes a vector"]
D --> E["Transformer layers: attention and processing"]
E --> F["Scores for every token in the vocabulary"]
F --> G["One token is chosen"]
G --> H["Detokenizer turns IDs back into text"]
The diagram shows a one-way trip with a return ticket. On the way in, the tokenizer and embedding layer prepare your words. In the middle, the transformer, which is the main engine of modern language models, does the thinking. On the way out, the model scores every possible next token, one is chosen, and the detokenizer joins the pieces back into normal text.
A worked example
Here is how a typical tokenizer might handle a short sentence. The exact splits differ from model to model, so treat this table as an illustration, not as the output of any one product.
| Text | Possible tokens | Count |
|---|---|---|
| cat | cat | 1 |
| unbelievable | un | believ | able | 3 |
| Hello, world! | Hello | , | world | ! | 4 |
| chatbots | chat | bots | 2 |
| 2025 | 202 | 5 | 2 |
Most AI companies offer a free online tokenizer tool or a counting library. Paste your text in, and it shows exactly how it will be split and how many tokens it uses. Make a habit of checking before you send long prompts.
5How a Tokenizer Is Built: Byte Pair Encoding
The pieces are not chosen by hand. They are discovered automatically from huge amounts of text.
The most popular method is byte pair encoding, usually shortened to BPE. The word “byte” here simply means a basic unit of computer data, and a “pair” means two neighbors sitting next to each other. The method is surprisingly simple, and you can understand it without any math.
Start with the smallest pieces
At the beginning, every character (or every byte) is its own token. The vocabulary is tiny, and every word is a long string of single letters.
Count neighboring pairs
The program reads a huge pile of text and counts which two pieces appear side by side most often. In English text, the pair “t” and “h” is extremely common.
Merge the winner into a new piece
The most common pair is glued together and added to the vocabulary as one new token, such as “th”. The merge is written down in a list.
Repeat tens of thousands of times
Next, “th” and “e” might merge into “the”. Later, “the” and a space might merge too. This continues until the vocabulary reaches the planned size, such as 50,000 or 100,000 pieces.
Replay the merges at use time
When new text arrives, the tokenizer starts from single characters and replays the saved merges in the same order. Common words quickly become single tokens, while rare words stop merging early and stay in pieces.
Think about how people shorten phrases in text messages. “Be right back” becomes “BRB”, and “laugh out loud” becomes “LOL”. The phrases people use most are the ones that earn a short nickname. BPE does the same thing automatically: the most common letter combinations earn their own short token, and rare combinations are left spelled out.
Why “byte-level” matters
A plain character-based version of BPE can still run into trouble with strange symbols. The byte-level version starts from the 256 possible values of a computer byte instead. Since every piece of text on a computer is stored as bytes, nothing can ever be “unknown”. Emoji, rare alphabets, and even broken text can always be represented. GPT-2 made this approach famous, and many models use it today.
Other tokenizer families
Byte pair encoding
Builds the vocabulary by repeatedly merging the most frequent neighbors. Used in the GPT family and in many open models.
WordPiece
Similar idea, but it chooses merges that best improve how well the model predicts the training text. Made popular by Google’s BERT.
SentencePiece
A toolkit that treats text as one raw stream, spaces included, so it does not rely on spaces between words. Useful for languages written without spaces.
Unigram
Starts with a very large list of candidate pieces and removes the least useful ones until the list is the right size. Often offered inside SentencePiece.
The tokenizer is trained separately and before the language model itself. After that it is frozen. The model then learns from text that was already cut by that tokenizer and never changes how the cutting is done.
6Token IDs, Vocabularies, and Special Tokens
Every token has a number, and every tokenizer has a fixed list of all the tokens it knows.
What a vocabulary is
The vocabulary is the complete list of tokens a tokenizer knows, and each one has a fixed number called its token ID. The model never sees the word “cat”. It sees a number, such as 9246 in one tokenizer and a completely different number in another. The numbers have no meaning on their own. They are just labels, like seat numbers.
In a school, every student has a roll number. The teacher can call “roll number 27” without saying the name, and the register links the number back to the child. A vocabulary is the register, and token IDs are the roll numbers. Another school has a different register, so roll number 27 means someone else there. That is why token IDs from one model cannot be used with another.
How big are real vocabularies?
Vocabulary size is a design choice, and it has changed over time. Newer models tend to use bigger lists, which helps compress text into fewer tokens, especially for languages other than English.
| Model or family | Tokenizer style | Approximate vocabulary size |
|---|---|---|
| BERT (Google, 2018) | WordPiece | 30,522 |
| Llama 2 (Meta, 2023) | SentencePiece BPE | 32,000 |
| GPT-2 and GPT-3 (OpenAI) | Byte-level BPE | 50,257 |
| GPT-4 generation (OpenAI) | Byte-level BPE | About 100,000 |
| Llama 3 (Meta, 2024) | Byte-level BPE | 128,256 |
| GPT-4o generation (OpenAI) | Byte-level BPE | About 200,000 |
The vocabulary-size trade-off
A larger vocabulary means common words and phrases fit into fewer tokens, so the same text takes less space in the context window and costs less to process. The price is that the model needs a bigger table of meanings and a bigger final scoring step. Designers pick a size that balances compression against the extra memory and training cost.
Special tokens
Besides normal text pieces, every vocabulary includes a few special tokens. They are never typed by a user. They are control signals that help the model understand structure.
Start and end markers
Mark where a text begins and ends. GPT-2, for example, uses an end-of-text marker written as <|endoftext|> so the model knows a document is finished.
Padding token
Fills empty space when several texts of different lengths are processed together. The model is told to ignore it.
Role markers
Chat models use special tokens to separate the system instructions, the user’s message, and the assistant’s reply, so each part is clearly labeled.
Unknown token
Used by older tokenizers when a word could not be found. Byte-level tokenizers rarely need it, because every byte can be represented.
Never compare token counts across different models as if they were the same. The same paragraph can be 900 tokens in one model and 1,100 in another. Always count with the tokenizer of the model you actually plan to call.
7What the Model Does With Tokens
A language model has one core job: look at the tokens so far and guess the next one.
From an ID to a meaning
The first thing the model does with a token ID is look it up in a big table called the embedding table. An embedding is a long list of numbers, often hundreds or thousands of them, that describes what a token means and how it behaves. Tokens with similar meanings end up with similar lists. The embedding of “king” sits closer to “queen” than to “banana”.
Paying attention
Next, the tokens pass through many layers of the transformer, the design behind almost every modern language model. Its key trick is called attention. Attention lets each token look back at all the other tokens and decide which ones matter most for understanding it. In the sentence “The trophy did not fit in the suitcase because it was too big”, attention helps the model work out that “it” points to the trophy.
Guessing the next token
At the end, the model produces a score for every single token in its vocabulary. If the vocabulary has 100,000 tokens, it produces 100,000 scores. These scores are turned into chances, so “Paris” might get a very high chance after “The capital of France is”, while “banana” gets almost none. One token is then picked from those chances.
One token at a time
The chosen token is added to the end of the text, and the whole process runs again to pick the next one. This loop continues until the model picks a special end token or hits the maximum length it was allowed. An answer of 300 tokens means the model went around this loop 300 times.
flowchart TD
A["Prompt tokens go in"] --> B["Model reads all tokens so far"]
B --> C["Model scores every token in the vocabulary"]
C --> D["Sampler picks one token"]
D --> E{"End token or length limit reached?"}
E -->|No| F["Add the new token to the sequence"]
F --> B
E -->|Yes| G["Stop and return the finished answer"]
The diagram makes one important fact visible: the model does not write the whole answer at once. It writes a token, then reads everything again including that new token, then writes the next one. This is why answers appear on screen word by word, and why longer answers take more time.
You have seen the suggestion bar on a phone keyboard that offers the next word as you type. A language model is that idea at a giant scale. It was trained on an enormous amount of text, so its suggestions are far better, and it can keep going for pages. Each suggestion is picked, added to the message, and then used to make the next suggestion.
Why the same question can give different answers
The picking step usually has a little randomness. A setting called temperature controls it. With a low temperature, the model almost always picks the highest-chance token, so answers are steady and repeatable. With a higher temperature, it sometimes picks less likely tokens, so answers are more varied and creative. This is why asking the same question twice can give two different replies.
8Context Windows and Token Budgets
A model can only look at a limited number of tokens at one time. That limit is called the context window.
The context window is the maximum number of tokens a model can handle in a single request. It is the model’s working memory. Everything has to fit inside it: the instructions you give, the earlier chat messages, any documents you attach, your new question, and the answer the model is about to write.
flowchart LR
subgraph W["Context window: one shared token budget"]
A["System instructions"]
B["Earlier chat history"]
C["Documents or retrieved facts"]
D["Your new question"]
E["Room reserved for the answer"]
end
A --> B --> C --> D --> E
Look at the figure again: the answer is not free space outside the window. It lives inside the same budget. If you fill the window almost completely with a giant document, the model has very little room left to reply, and the answer may be cut short.
How context windows have grown
Early models could only see a few pages. The original GPT-3 handled 2,048 tokens. When GPT-4 launched in 2023, it came in 8,192-token and 32,768-token versions. In 2024, Google introduced Gemini 1.5 with a window of up to one million tokens, enough for several books at once. Many recent models offer hundreds of thousands of tokens. The trend is clear, but bigger windows come with their own costs.
Why a longer chat gets forgotten
When you use an AI model through a programming interface, it does not remember earlier turns by itself. The application must send the whole conversation again with every new message. A long chat therefore grows with each turn. When it reaches the limit, the application has to drop or shorten the oldest parts, and the model seems to “forget” them.
Bigger is not always better
A large window does not mean the model uses every part of it equally well. Research from 2023, often called the “lost in the middle” study, found that some models were better at using facts placed at the very beginning or end of a long input than facts buried in the middle. Also, the standard attention method gets more expensive as the input grows, because every token looks at every other token. Doubling the input can more than double the work. Engineers keep inventing ways to reduce this cost, but it never completely disappears.
The context window is like a school desk. A bigger desk lets you spread out more books at once. But the more books you spread, the harder it is to find the one page you need, and the more time you spend looking. A smart student keeps only the books that matter for today’s question on the desk.
The advertised window size is a ceiling, not a target. Filling it to the brim makes requests slower and more expensive, and it can reduce answer quality. Send what is needed, not everything you have.
9Tokens, Money, and Speed
Tokens are the unit of billing, the unit of speed, and the unit of limits for almost every AI service.
You pay per token
Most AI companies charge by the token, usually quoted as a price per million tokens. Input tokens (what you send) and output tokens (what the model writes) are priced separately, and output tokens usually cost more. That is because each output token needs one full trip around the generation loop from the last chapter, while input tokens can be processed together in one go.
A mobile data pack works the same way. You buy a number of megabytes, and every video you watch or page you open uses some. You do not pay per app or per minute, you pay for the data moved. Tokens are the data pack of AI: every question and every answer uses some, and the meter keeps running until the pack is empty.
What counts as a token on the bill
| Part of the request | Counts? | Note |
|---|---|---|
| System instructions | Yes | Sent with every request, so long ones add up fast. |
| Earlier chat history | Yes | Re-sent each turn, so cost grows as a chat grows. |
| Attached documents | Yes | The full text is converted into tokens. |
| The model’s answer | Yes | Usually the higher price. |
| Hidden thinking steps | Usually yes | Models that “think” before answering often bill those thinking tokens as output. |
Tokens and speed
Speed has two parts. The wait before the first word appears depends mostly on how many input tokens must be read. After that, the answer streams out one token at a time, so the total time depends on how many output tokens are written. A request with a huge input and a short answer feels different from a short input with a very long answer.
Limits are counted in tokens too
Providers also limit how fast you can use their service, often as a number of tokens per minute along with a number of requests per minute. If your app suddenly sends much longer prompts, you can hit a limit even though the number of requests stayed the same. There is usually a separate setting for the maximum length of a single answer as well.
A back-of-envelope example
Suppose a company runs a support chatbot that handles 100,000 conversations a day, and each conversation uses about 1,500 tokens in total. That is 150 million tokens every day. Trimming just 20 percent of the tokens by shortening instructions and history saves 30 million tokens daily. Small habits become big savings at this scale.
Several providers offer discounted pricing when the beginning of your prompt is the same across many requests, a feature often called prompt caching. Keep long, unchanging instructions at the start and put the changing parts at the end to benefit from it.
10Why Tokens Make AI Behave Oddly
Many strange AI mistakes come from the fact that the model sees pieces, not letters.
When an AI model fails at something that seems easy to a child, tokens are often the reason. The model never looks at the individual letters of a word if that word is stored as one or two big pieces. Here are the most common surprises.
Letter counting is hard
A famous example is asking how many times the letter “r” appears in “strawberry”. If the word is stored as a few chunks, the model has no direct view of the letters inside them, so it can guess wrong.
Digits are split oddly
Some tokenizers cut long numbers into groups of digits that do not match place value. That makes arithmetic on large numbers harder unless the model uses a calculator tool.
Spaces and capitals matter
In many tokenizers, “hello”, ” hello”, and “Hello” are different tokens with different IDs. A tiny change in spacing or capitalization can change how the text is cut.
Some languages cost more
Hindi, Tamil, Telugu, and other non-English scripts often need noticeably more tokens than an English sentence with the same meaning, especially on older tokenizers. Newer ones with larger vocabularies narrow the gap.
Glitch tokens
Researchers found that some early models had tokens in the vocabulary that barely appeared in training. Asking about them could trigger strange or off-topic replies.
Structure takes space
Indentation, brackets, quotation marks, and repeated field names in data formats all use tokens. A neat-looking data file can be much more expensive than its plain-text summary.
If you are building a product for users who write in Indian languages, always measure real token counts on real sample text. The same feature can cost two or more times as much per message as the English version, and you will want to know that before you set prices or limits.
The good news is that many of these problems are being reduced. Larger vocabularies, better training data for more languages, and tools such as code execution all help. But understanding the root cause, that the model reads pieces, helps you predict where mistakes will happen and design around them.
11Tokens Beyond Text: Images, Audio, and Code
The token idea is not limited to words. It is a general way of turning anything into a row of small units.
Modern models are multimodal, which means they handle more than one kind of data, such as text, pictures, and sound. To do this, each kind of data is converted into token-like units that the same model can process.
Image tokens
An image is usually cut into a grid of small square patches. Each patch becomes one or more units for the model. Many services convert image size into a token count, so a large, detailed picture costs more than a small one.
Audio tokens
Speech is sliced into very short time frames, and each frame is converted into a unit. Longer recordings mean more tokens, just as longer text does.
Code tokens
Source code is text, so it is tokenized too. Common keywords become single tokens, while long custom names are split into several. Many code models use tokenizers tuned for programming.
Embedding inputs
Tools that turn text into vectors for search also have token limits. A very long document must be split into smaller chunks before it can be embedded.
Picture a mosaic made of small colored tiles. From far away you see a face, but the artist only ever handled individual tiles. A model looking at an image works the same way: it reads a grid of tiny tiles, not the whole picture at once, and builds its understanding from how the tiles relate to each other.
12Security, Monitoring, and Cost Control
Once an AI feature is live, tokens become something you must protect, measure, and cap.
Security concerns tied to tokens
Denial of wallet
An attacker, or a bug, sends huge prompts or triggers very long answers again and again. Nothing crashes, but the bill explodes. Always cap input size, output size, and usage per user.
Crowding the context
Hidden text inside a web page or document can try to push instructions into the model’s window. Treat retrieved text as untrusted, and keep your own rules clearly separate from it.
Sensitive data in prompts
Everything you send becomes tokens that travel to the provider and may appear in logs. Remove passwords, keys, and personal data before sending, and think carefully before logging full prompts.
Splits can hide patterns
Because the same text can be cut in different ways, simple word-matching filters can be fooled. Use proper safety tools and check the meaning of text, not just exact words.
What to measure
You cannot control what you do not measure. Good teams log token counts for every request and watch them on a dashboard, just as they watch response time and errors.
| Metric | What it tells you | Why it matters |
|---|---|---|
| Input tokens per request | How big your prompts are | Spots bloated instructions or history. |
| Output tokens per request | How long answers are | Output is usually the pricier part. |
| Cost per user or feature | Who or what drives the bill | Guides pricing and limits. |
| Truncation rate | How often answers are cut off | Signals a limit set too low. |
| Cache hit rate | How often repeated prompts are reused | Shows how much you are saving. |
| Rate-limit errors | How often you hit provider limits | Warns you before users feel it. |
flowchart LR
U["User app"] --> G["API gateway with rate limits"]
G --> T["Token counter and budget check"]
T -->|Within budget| L["Language model service"]
T -->|Over budget| R["Reject or shorten the request"]
L --> M["Usage logger"]
M --> D["Dashboard and alerts"]
L --> U
In this design, nothing reaches the model without passing a budget check. The gateway limits how fast each user can send requests. The counter estimates the size of the prompt and decides whether it fits the allowed budget. After the model answers, the logger records the real usage, and the dashboard raises an alert if numbers jump unexpectedly.
Your home has an electricity meter and a fuse box. The meter tells you how much you use, and the fuse stops a fault from burning down the house. A token-aware system needs both: the dashboard is the meter, and the budget caps are the fuse.
13Best Practices, Patterns, and Common Mistakes
A few simple habits will keep your AI features fast, cheap, and reliable.
Patterns that work
Count before you send
Use the model’s own tokenizer to check prompt size. Reject or trim anything that will not fit instead of waiting for an error.
Sliding window
Keep only the most recent messages of a long chat, plus the important instructions. Old messages fall off the back.
Summarize old history
Replace many old messages with a short summary. You keep the key facts and free up a lot of space.
Retrieve, do not dump
Split big document sets into chunks, find the few that match the question, and send only those. This approach is often called retrieval-augmented generation.
Stable prefix, changing tail
Put fixed instructions first and variable content last, so repeated prompts can benefit from caching discounts.
Ask for short answers
Tell the model the format and length you want. A clear request for three bullet points beats a long essay you will not read.
Mistakes to avoid
What people do
They estimate size by counting words or characters and assume it is close enough for every language and every model.
Why it hurts
Token counts vary by model and by language. A text that looks short in words can be long in tokens, which leads to surprise errors, cut-off answers, and bills that do not match the plan.
Do this instead
Count with the real tokenizer for the exact model, and keep a safety margin of ten to twenty percent.
What people do
They paste the entire knowledge base or the whole chat history into every request, just because the window is big enough to allow it.
Why it hurts
Cost and delay rise with every request, the important facts get buried, and answer quality can drop. It also makes it easier to leak private data.
Do this instead
Select only the relevant pieces, summarize older material, and set a clear token budget for each part of the prompt.
What people do
They set no limit on the length of the answer and no limit on usage per user.
Why it hurts
One careless or malicious request can produce an enormous answer, use up your rate limit, and cost real money.
Do this instead
Always set a maximum output length, per-user daily budgets, and alerts for unusual spikes.
14Tokens in the Real World
Here is how the ideas in this guide show up in everyday products.
Customer support assistants
Companies that put AI chat on their websites must fit instructions, the customer’s messages, and relevant help articles into the window. Teams track tokens per conversation to understand cost, and they trim history to keep each chat affordable even when customers write long messages.
Chatting with your documents
Tools that answer questions about a company’s PDFs rarely send the whole file. They cut documents into chunks of a few hundred tokens, find the chunks that match the question, and send only those. Chunk size is a careful balance: too small loses context, too large wastes tokens.
Coding assistants
Assistants such as GitHub Copilot must decide which parts of your project to show the model. Your whole codebase will not fit in any window, so the tool picks the open file, nearby code, and the most related files. Choosing well is a token budgeting problem.
Large-window research and analysis
Models with very large windows, such as the Gemini 1.5 family, can take entire reports or long videos as input. Even then, teams still watch token counts, because a request that fills a huge window is slower and costs more than a focused one.
Multilingual products in India
Apps that serve users in Hindi, Tamil, Bengali, and other languages measure tokens on real local text before launch. Because the same message can need far more tokens than in English on some models, teams compare tokenizers and choose models whose vocabularies handle their languages efficiently.
15Controlling Output: Limits, Sampling, and Stop Signals
You cannot change how a model thinks, but you can control how many tokens it writes and how it picks them.
Every time you call a language model, you can adjust a few settings. These settings do not change what the model knows. They change how the next-token guessing loop behaves. Learning them gives you far more control over cost, length, and style, and most of them are measured in tokens or in chances between tokens.
The maximum output length
The most important setting is the maximum output tokens limit. It tells the model to stop after a certain number of new tokens, no matter what. If the answer is not finished by then, it is simply cut off, sometimes in the middle of a sentence. Many services also report a “finish reason” with each reply, which says whether the model stopped naturally or was stopped by the length limit. Checking that reason is the easiest way to detect cut-off answers in your own app.
Stop sequences
A stop sequence is a short piece of text that tells the model to halt as soon as it writes it. For example, you might ask for a list and tell the model to stop when it reaches a special marker. This is a neat way to prevent rambling and to save tokens, because generation ends immediately instead of running to the length limit.
Choosing among likely tokens
Remember that at every step the model gives a chance to every token in its vocabulary. Settings called sampling controls decide how the final pick is made from those chances.
| Setting | What it does | When you might change it |
|---|---|---|
| Temperature | Makes the pick more predictable when low, more varied when high. | Low for facts and code, higher for brainstorming and stories. |
| Top-k | Only the k most likely tokens are allowed to be chosen. | To cut off very unlikely, odd words. |
| Top-p | Only the smallest group of tokens whose chances add up to p is allowed. | To keep variety while avoiding nonsense. |
| Maximum output tokens | Hard limit on answer length. | Always, to control cost and delay. |
| Stop sequence | Ends the answer when a chosen text appears. | For structured outputs and tidy endings. |
Picture a mixing desk in a music studio. The singer’s voice, which is the model’s knowledge, stays the same. But the engineer has sliders for volume, echo, and where to stop the track. Temperature is the echo, the maximum length is the end-of-track mark, and the stop sequence is the engineer’s hand on the stop button. You are not changing the singer, only how the song is delivered.
Streaming makes tokens visible
Because the model produces one token at a time, many services let you receive the answer as a stream, token by token, instead of waiting for the full reply. This is what makes chat apps feel quick: the first words appear almost immediately while the rest is still being written. Streaming does not reduce the total number of tokens. It only lets people start reading earlier, which greatly improves how fast the product feels.
Practical settings advice
Keep temperature low
When accuracy and repeatability matter, such as summarizing a contract or extracting fields from an invoice, a low temperature gives steadier results.
Allow more variety
For naming ideas, story drafts, or marketing copy, a higher setting lets the model explore less obvious word choices.
Set a sensible length cap
Choose a maximum that is comfortably above a normal answer but far below a runaway one. Review how often replies hit the cap.
Use stop sequences for formats
When your app expects one short item, a stop marker prevents extra explanation you would only throw away.
Setting the length cap very low to save money can silently cut answers in half. Always check whether replies end naturally, and raise the cap or ask for a shorter format if they do not.
16Where Tokens Come From: Training at Massive Scale
Tokens are not only what you type. They are also how the size of a model’s training library is counted.
Before a model can answer your question, it has to learn language. This first big learning stage is called pretraining. The model reads an enormous collection of text, split into tokens, and practices one simple game over and over: look at the tokens so far and predict the next one. When it guesses wrong, its internal numbers are adjusted a tiny bit. After trillions of these small corrections, it becomes surprisingly good at language.
Imagine a student who is locked in a giant library and given one exercise: read a few words of any sentence, cover the next word, and guess it. Check the answer, learn from the mistake, and move on to the next sentence. After doing this billions of times, the student starts to pick up grammar, facts, and even writing styles without anyone explaining the rules. Pretraining is that exercise, and tokens are the sentences in the library.
How training data is measured
Companies describe the size of training data in tokens, not in pages or books, because tokens are what the model actually consumes. The numbers have grown dramatically. The original GPT-3 was trained on roughly 300 billion tokens. DeepMind’s Chinchilla model, a well-known 2022 research result, used 1.4 trillion tokens. Meta said that its Llama 3 models were pretrained on more than 15 trillion tokens.
Tokens versus parameters
People often mix up tokens with parameters. Parameters are the adjustable numbers inside the model, the “knobs” that get tuned during training. Tokens are the text the model reads while tuning those knobs. The Chinchilla research suggested that, for a fixed training budget, many earlier models had too many knobs and had read too little text. A commonly quoted guideline from that work is roughly 20 training tokens per parameter. Since then, many teams have trained smaller models on far more tokens than that guideline, because a model that has read more is cheaper to run afterward.
The main stages
Collect and clean text
Teams gather text from books, websites, code, and other sources, then remove duplicates, spam, and low-quality material. Quality matters at least as much as quantity.
Train the tokenizer
The vocabulary is learned from a sample of this text using a method such as byte pair encoding, then frozen.
Convert everything to tokens
The whole collection is turned into long rows of token IDs, which are fed to the model in batches.
Pretrain on next-token prediction
The model practices the prediction game across trillions of tokens. This step needs huge computing power and takes weeks or months.
Teach it to follow instructions
Further training, using much smaller sets of carefully written examples and human feedback, turns a raw text predictor into a helpful assistant.
The model’s knowledge stops at the end of its training data, which is why every model has a knowledge cutoff date. It also explains why tokenizers are frozen: changing the way text is cut after training would make the model’s learned patterns meaningless.
Clearing up four easily confused terms
| Term | Simple meaning | Where you meet it |
|---|---|---|
| Token | A piece of text the model reads or writes | Prompts, answers, pricing, limits |
| Parameter | An adjustable number inside the model | Model size, such as “70 billion parameters” |
| Context window | Maximum tokens in one request | The input plus output limit |
| Training tokens | Total tokens read while the model was learning | Model release notes and research papers |
17Following One Request From Start to Finish
Let us put every idea together by tracing a single, ordinary chatbot request and counting its tokens.
Imagine a study-help app. A student types a short question. Behind the scenes, the app builds a full request from several parts, sends it to a language model, and shows the answer. The numbers below are invented for practice, but they follow the same pattern as real systems.
sequenceDiagram
participant U as Student
participant A as App backend
participant T as Tokenizer
participant M as Language model
U->>A: Types a question
A->>T: Send full prompt text
T-->>A: Token IDs and a count
A->>M: Request with limits set
M-->>A: Streams output tokens
A-->>U: Shows the answer as it arrives
Notice that the app talks to the tokenizer before it talks to the model. This is the budget check from the earlier chapter in action. If the count were too large, the app could trim the history or refuse the request before spending any money.
The token ledger
Here is the accounting for one turn of the conversation. Think of it like a receipt that lists where every token went.
| Part | Tokens | Type |
|---|---|---|
| System instructions (rules for the tutor) | 200 | Input |
| Earlier chat history | 600 | Input |
| Student’s new question | 12 | Input |
| Total input | 812 | Input |
| Answer actually written (cap was 300) | 180 | Output |
| Total used in this request | 992 | Both |
If the model’s window is 8,192 tokens, this request uses only a small slice of it. But the history part will keep growing with every turn, and after many turns it could become the largest item on the receipt. That is why apps shorten or summarize old messages.
Turning tokens into money
To see how cost works, use made-up prices just for practice: one dollar per million input tokens and three dollars per million output tokens. These are not real prices from any company. With these numbers, the input costs 812 divided by one million, multiplied by one dollar, which is about $0.0008. The output costs 180 divided by one million, multiplied by three dollars, which is about $0.0005. The whole request costs roughly $0.0014.
That looks tiny, but scale it up. If the app handles 100,000 such requests every day, the daily cost is around $135. Over a month, that is more than $4,000. If a design change cut the input by a quarter, the saving would be noticeable on every single bill. This is why experienced teams care about even small amounts of wasted tokens.
What the team would do next
They would shorten the system rules, summarize history after every few turns, and ask the tutor to answer in a compact format. They would then compare the average tokens per request before and after the change, using the usage numbers returned by each call. The improvement is measured, not guessed.
Take a prompt you use often and rebuild this ledger by hand with a real token counter. Seeing your own numbers is the quickest way to find waste, and it builds the habit of thinking in tokens instead of words.
18Frequently Asked Questions
Quick answers to the questions people ask most about tokens.
19Summary and Key Takeaways
Key Takeaways
- A token is a piece of text that a model treats as one unit. It can be a word, part of a word, a character, a space, or a symbol, and about 100 tokens equal 75 English words.
- A tokenizer turns text into token IDs using a fixed vocabulary learned in advance, most often with byte pair encoding. The same tokenizer must be used for training and for use.
- Models write one token at a time. Each new token is picked from scores over the whole vocabulary, added to the text, and fed back in, which is why long answers take longer.
- The context window is a shared budget. Instructions, history, documents, your question, and the answer all compete for the same space, so bigger is not always better.
- Tokens drive cost, speed, and limits. You pay per token, output usually costs more than input, and providers cap tokens per minute, so measuring usage is essential.
- Token quirks explain odd AI behavior, such as miscounting letters, struggling with long numbers, and using more tokens for many non-English languages.
- Good habits save money and prevent trouble: count with the right tokenizer, send only what is needed, cap answer length, monitor usage, and treat all outside text as untrusted.