LearnWithExamples
A language model never actually sees your sentence. It sees a stream of numbered fragments, and it can only hold so many of them at once. Understand those two facts and almost every strange AI behaviour you have ever run into suddenly has an explanation.
I have been building things on top of language models since the days when “context window” meant 512 fragments and you budgeted them like a family budgets grocery money. The hardware got better. The models got enormous. And yet, in workshop after workshop, the same two questions come up first — and they are almost always asked in the wrong order.
People ask “why did the AI forget what I told it?” before they ask “what exactly is the AI storing in the first place?” That is like asking why your suitcase won’t close before checking what you packed. So let’s do it properly. First we’ll open up a token — see it, split it, count it. Then we’ll build the window it lives inside, and watch what happens when the window fills up.
By the end you’ll be able to look at a prompt and estimate its cost in your head, explain why the model insists “strawberry” has two Rs, know why Hindi or Tamil text costs nearly triple what English does, and — most usefully — know exactly what to trim when a system tells you your input is too long.
Tokens and context windows, defined
A token is the smallest chunk of text a language model actually reads. Usually it’s a piece of a word — roughly ¾ of an English word on average. The model converts every token into a number before it does anything else. Text in, numbers out.
A context window is the maximum number of tokens the model can have in front of it at one time — your instructions, the uploaded file, the entire chat history, plus the reply it is currently writing. It’s a hard ceiling, not a soft suggestion. Nothing outside it exists as far as the model is concerned.
Tokens are the units. The context window is the container. Everything else in this article is a consequence of those two sentences.
Part 1 — A token is not a word
Here is the first mental model most beginners build, and it is wrong: “the AI reads word by word, like I do.” Reasonable guess. Also the source of about half the confusion I see.
Think about why splitting on words fails. English alone has well over a million distinct word forms once you include names, typos, plurals, brand names, hashtags, and the thing your colleague types when they mean “definitely.” A model would need a lookup table with a million-plus entries, and the moment somebody typed Kanniyakumari or ngrok or bruhhhh, the table would shrug and return “unknown.”
Now try the opposite extreme: split on characters. Only about a hundred symbols to memorise — clean, complete, nothing is ever unknown. But now the word “encyclopedia” costs twelve slots instead of one, and the model has to learn spelling from scratch before it learns meaning. Sequences get impossibly long, and long sequences are expensive (we’ll get to why).
So the field landed in the middle. Subword tokenization: keep whole tokens for the text fragments that show up constantly, and break rare things into smaller pieces that can be reassembled. Common stuff is cheap. Weird stuff still works, just costs more.
Split by words
Tiny sequences, impossible vocabulary. Any unseen word breaks it. Rejected.
Split by characters
Tiny vocabulary, endless sequences. Nothing breaks, but everything is slow. Rejected.
Split by subwords
Frequent chunks stay whole, rare chunks get split. This is what every major model uses today.
Watch it happen
Reading about tokenization is far less convincing than watching a sentence get shredded. Type into the box below — or hit one of the preset buttons — and see the fragments appear. Each coloured block is one token. Notice the little spaces sitting inside the blocks: in most tokenizers a leading space is part of the token, which is why the and the are two different entries entirely.
Live token splitter
estimate · type to updateGrey <byte> blocks are the extra tokens spent on characters outside the basic Latin set. This tool approximates real byte-pair encoding closely enough to build intuition — exact counts vary a little between model families.
How the splitting rules get invented
Nobody sits down and hand-writes the list of fragments. It’s learned from data, most often with an algorithm called Byte Pair Encoding (BPE). The idea is almost embarrassingly simple, and you can run it on paper.
Suppose your entire training corpus is these three words, repeated a lot:
| Round | What the algorithm sees | Most frequent adjacent pair | New merged token |
|---|---|---|---|
| Start | l o w · l o w e r · l o w e s t | l + o | lo |
| 2 | lo w · lo w e r · lo w e s t | lo + w | low |
| 3 | low · low e r · low e s t | e + r | er |
| 4 | low · low er · low e s t | e + s | es |
| 5 | low · low er · low es t | es + t | est |
Five rounds and the algorithm has independently discovered the root low and the suffixes er and est — real English morphology, learned purely by counting. Run this for millions of rounds on a slice of the internet and you get a vocabulary of roughly 50,000 to 200,000 fragments, ordered by how useful they are.
Two consequences fall straight out of this, and both matter in practice:
- Frequency decides price. Text that looked like the training data gets packed efficiently. Text that didn’t gets shredded into crumbs. Your name is probably one token if you’re called
Davidand five tokens if you’re calledDevanshi. - The vocabulary is frozen at training time. A model trained mostly on English carries an English-shaped tokenizer forever. It can still read Hindi, Swahili, or Korean — it just pays a heavier toll per sentence.
Type “Learning is fun” into the splitter above, then type the same sentence in Hindi. English: about 3–4 tokens. Hindi: often 15–25. Same meaning, four to six times the cost. If you build a product for an Indian audience and price it per token, this single detail can decide whether your unit economics work.
Part 2 — Token maths you can do in your head
You will rarely need an exact count. You will constantly need a fast estimate: will this fit? These are the ratios I have used for years, and they hold up well enough for planning.
| Rule of thumb | Approximate value | How to use it |
|---|---|---|
| English words → tokens | 1 word ≈ 1.3 tokens | Multiply your word count by 4/3. |
| Characters → tokens | 4 characters ≈ 1 token | Fastest check: divide character count by 4. |
| A typical page of prose | ≈ 600 tokens | 450 words per double-spaced page. |
| Source code | 1 line ≈ 8–12 tokens | Indentation and punctuation are surprisingly costly. |
| Meeting transcript | 1 minute ≈ 200 tokens | Speech runs near 150 words per minute. |
| Non-Latin scripts | 2–4× the English cost | Devanagari, Tamil, Thai, Arabic, Korean. |
| Emoji | 1 emoji ≈ 2–4 tokens | Skin-tone and family emoji are the worst offenders. |
Let’s apply them to things you actually handle:
A WhatsApp message
~25 words → ≈ 33 tokens. You could send 6,000 of these before filling a 200K window.
A one-page résumé
~600 words → ≈ 800 tokens. Screening 100 résumés at once is genuinely feasible.
A 12-page contract
~6,000 words → ≈ 8,000 tokens. Comfortable in any modern window.
A 90-minute meeting
~13,500 words → ≈ 18,000 tokens. Fine alone; painful if you also attach the slides.
A 300-page novel
~100,000 words → ≈ 133,000 tokens. Fits in a large window, with room to spare for questions.
A mid-size codebase
40,000 lines → ≈ 400,000 tokens. This is where retrieval stops being optional.
Part 3 — The five places tokenization gets weird
This is the part of the article I’d tell my past self to read first. Almost every “the AI is stupid” complaint I have investigated turned out to be a tokenizer artefact, not a reasoning failure.
1. The model cannot reliably count letters
Ask a model how many times the letter R appears in “strawberry” and you may get “two.” People post screenshots of this as proof that AI is a parlour trick. What actually happened is subtler: the model never received the letters. It received something like str + aw + berry — three opaque ID numbers. Asking it to count Rs is like asking you to count the letters in a word someone spelled out in Morse code, at speed, without writing anything down. Not impossible, but a genuinely awkward task given the input.
Force the letters apart before asking: s-t-r-a-w-b-e-r-r-y. Hyphenating breaks the word into single-character tokens and accuracy jumps immediately. Same trick works for reversing words, counting syllables, and checking palindromes.
2. Numbers split in unhelpful places
Depending on the tokenizer, 148392 might become 148+392, or 1+48+39+2. The digits do not line up in neat place-value columns the way they do on paper, which is a large part of why models were historically shaky at long arithmetic. It also means an invoice number, a PAN, an order ID, or a phone number can be far more expensive than its length suggests — and is easier to mis-copy.
3. A trailing space quietly poisons your prompt
If your prompt ends with "The answer is " — with a space after “is” — you have handed the model a dangling space token and asked it to continue. But the natural next token is " 42", which already includes its own leading space. You’ve created a conflict the model must work around, and quality drops for no visible reason. Fifteen years in, and I still occasionally lose twenty minutes to a stray space at the end of a template string.
4. Whitespace is a real line item in code
Deeply indented code, four-space tabs, blank lines between functions — every bit of that costs tokens. A well-formatted 500-line Python file can cost noticeably more than the same logic minified. This is not an argument for writing ugly code; it is an argument for sending the model the three functions that matter instead of the whole file.
5. Rare and mixed-script text costs a fortune
Scientific nomenclature, chemical formulas, Sanskrit terms, transliterated place names, base64 blobs, UUIDs, and minified JavaScript all tokenize horribly. A single UUID can eat 20+ tokens. If you are pasting logs full of them, you are burning most of your budget on strings the model does not need to read carefully.
Every unusual character you send is a small tax. Every ordinary English word is a discount. That asymmetry is baked into the tokenizer, and no amount of prompt engineering removes it.
Part 4 — The context window: the desk, not the brain
Now the second half. You know what tokens are; the question is how many the model can look at simultaneously.
My favourite analogy comes from a colleague who used to work in an architecture office. Picture a draughtsman at a drawing board. The board is a fixed size. Everything he needs — the client brief, the site survey, last week’s revisions, the sheet he is drawing on right now — has to be laid out on that board at once. Anything that doesn’t fit goes on the floor. And here is the crucial part: he cannot remember what’s on the floor. Not “remembers it vaguely.” Cannot see it at all.
That board is the context window. It is measured in tokens, and it holds four things simultaneously:
Read that diagram twice, because it contains the single most misunderstood fact about chatbots: the conversation history is re-sent, in full, on every turn. The model is not sitting there remembering you between messages. It is stateless. Each time you press enter, the application quietly bundles up the entire transcript so far, appends your new message, and ships the whole parcel off again. That is why turn 40 of a conversation costs far more than turn 2, and why a long chat gradually slows down.
Watch a conversation fall off the edge
The simulator below runs a customer-support chat. Drag the slider to shrink or grow the window and watch which messages survive. The system prompt is pinned — it is always sent — and the newest messages have priority. Everything greyed out is on the floor.
Context window simulator
drag the sliderShrink the window far enough and the model loses the customer’s order number — then confidently asks for it again, or worse, invents one. That “sudden amnesia” moment is not a bug in the model. It is arithmetic.
Part 5 — Who is eating your window?
When a team tells me “we have a 128,000 token window, we’ll never hit it,” I ask them to write down the budget. It is always tighter than they expect. Here’s a real-shaped example — an internal HR assistant:
| Line item | Tokens | Notes |
|---|---|---|
| System prompt (tone, rules, escalation policy) | 1,400 | Sent on every single turn, forever. |
| Tool / function definitions | 2,100 | Six tools with parameter schemas. |
| Few-shot examples | 1,800 | Four demonstration Q&A pairs. |
| Retrieved policy documents (8 chunks) | 6,400 | The RAG payload. |
| Employee’s uploaded payslip PDF | 3,200 | Tables tokenize badly. |
| Conversation history (turn 18) | 9,700 | Grows every turn, never shrinks by itself. |
| Reserved for the reply | 2,000 | If you forget this, generation gets cut off mid-sentence. |
| Total | 26,600 | And this is a simple assistant. |
Notice what dominates: not the user’s question, which is maybe 30 tokens. The scaffolding dominates. That is the normal state of affairs, and it’s why the highest-leverage optimisation is almost never “write a shorter question.”
Input and output share the same window. If you fill 199,000 of a 200,000-token window with a document and then ask for a detailed 5-page report, there is no room left to write it in. The response gets truncated mid-sentence and everyone blames the model. Always leave headroom for the answer — I budget 10–15% by default.
Input tokens and output tokens are not the same product
Every provider charges more per output token than per input token, often 3–5×, and beginners assume this is arbitrary. It isn’t. Reading your input happens in one parallel pass — the whole prompt goes through the model at once. Writing the reply happens one token at a time, sequentially, with a full pass through the network for each token produced. Output is genuinely the expensive half.
The practical takeaway: a request that reads 50,000 tokens and returns a 200-token summary is cheap. A request that reads 500 tokens and generates a 4,000-word essay may cost more. If your bill is climbing, look at what you are asking the model to write, not just what you are feeding it.
What actually fits in a window?
pick a sizePart 6 — Why bigger windows didn’t solve everything
Around the time million-token windows arrived, a lot of people declared retrieval dead. Just dump everything in! It did not play out that way, for four reasons I now explain in every architecture review.
Attention cost grows faster than the input
In a standard transformer, every token compares itself with every other token. Double the input and you roughly quadruple that work. Modern implementations soften the curve considerably, but the shape of the problem remains: long contexts are disproportionately expensive in compute and in memory. That cost lands on you as latency and as money.
Information gets lost in the middle
Researchers have repeatedly measured a U-shaped accuracy curve: models are excellent at recalling material near the beginning of the context and near the end, and noticeably weaker on material buried in the middle. Put the critical clause on page 40 of a 90-page contract and recall genuinely suffers. It is the reading equivalent of remembering the first and last speaker at a conference and losing the eleven in between.
First: put your instructions after the long document, not before it — the tail position is a strong one. Second: for anything critical, state it twice, once at the top and once at the bottom. It feels redundant. It measurably works.
More context means more distraction
Give a model 50 pages when the answer lives in one paragraph, and you have added 49 pages of plausible-looking, semantically similar noise. Precision drops. I have watched a support bot’s accuracy improve by 12 points simply by retrieving four document chunks instead of twenty. Less, but better, beat more.
You pay for every token, every turn
A 300,000-token prompt sent on each of 20 conversational turns is six million input tokens for a single conversation. Multiply by a thousand users. This is the bill that surprises startups in month three.
A large context window is a bigger desk, not a better draughtsman. What you place on the desk still decides the quality of the drawing.
Part 7 — What happens when you overflow
Four different things, and knowing which one your tool does explains a lot of otherwise baffling behaviour.
Hard rejection
The API refuses the request outright with a “maximum context length exceeded” error. Honest and annoying — typical of direct API calls.
Silent truncation
The oldest content is chopped off without telling anyone. The model answers confidently using half the information. This is the dangerous one.
Sliding window
Old turns drop off the back as new ones arrive, like a conveyor belt. Chat apps often do this. It’s why long chats “forget” the beginning.
Rolling summarisation
Older turns get compressed into a paragraph of notes that stays in context. Cheapest in tokens, but detail is permanently lost.
Here’s the failure I see most often in production, told as a small story. A logistics company built an assistant that read a shipment manifest and answered questions about it. It worked beautifully in testing. In production it started confidently reporting wrong container weights. The cause: their largest customers had manifests that pushed past the window, their framework silently truncated the head of the file — including the column headers — and the model, doing its best with headerless numbers, guessed which column was which. No error was ever logged. Nobody had built a token counter into the pipeline.
Count your tokens before you send them. That is the whole lesson. It takes four lines of code and it prevents an entire genus of bug.
Part 8 — The practical playbook
Nine tactics, roughly in the order I reach for them.
| Tactic | What you actually do | Best when |
|---|---|---|
| Chunk and retrieve | Split documents into 300–800 token passages, embed them, and pull only the handful that match the question. | Your corpus is bigger than any window — knowledge bases, manuals, archives. |
| Summarise and carry | Every ~10 turns, compress the conversation into a short state note and drop the raw transcript. | Long-running assistants and agents. |
| Sandwich your instructions | State the task before the document and repeat it after. | Any prompt over ~10,000 tokens. |
| Reserve output space | Cap input at 85% of the window; leave the rest for the reply. | Always. Non-negotiable. |
| Strip the noise | Remove HTML tags, boilerplate footers, base64 blobs, repeated log timestamps, license headers. | Scraped web content and log files — often a 40% saving. |
| Keep the stable parts first | Put the system prompt and fixed examples at the very start, variable content after. | You’re using prompt caching — cache hits need an identical prefix. |
| Ask for structure | Request JSON or a bounded list instead of free prose. | Output tokens are your cost driver. |
| Split the job | Three focused calls beat one giant call that tries to do everything. | Multi-step analysis; also improves accuracy. |
| Right-size the model | Route simple classification to a small model, reserve the big window for the hard step. | Cost is out of control and latency matters. |
A worked example: 200 support tickets
Say you want themes across 200 support tickets averaging 400 words each. Naive approach: paste all of them, about 107,000 tokens, into one prompt and ask for themes. It fits in a large window — and produces a bland, shallow answer, because the middle 150 tickets get skimmed.
What actually works: batch the tickets in groups of 20. For each batch, ask for a compact structured summary — five themes, each with a one-line description and a count. That’s ten calls of ~11,000 input tokens each, returning ~300 tokens apiece. Then a final call takes those ten summaries (3,000 tokens total) and merges them into the master list. Total input is similar, output is small, and every ticket got real attention rather than a glance. This map-then-reduce shape is the workhorse pattern of practical LLM engineering, and it exists entirely because of context limits.
Part 9 — Five myths worth deleting
“The model remembers our previous conversations.”
By default, no. Each request is stateless. If a product appears to remember you across sessions, an application layer is storing notes in a database and quietly pasting the relevant ones into the context window before the model ever sees your message. The memory lives in the product, not in the model.
“A bigger context window means the AI is smarter.”
Window size measures capacity, not capability. A model with a million-token window can still reason worse than a model with 32,000. They’re independent specifications — like confusing the size of a desk with the skill of the person sitting at it.
“One token is one word.”
Only by coincidence, and mostly for short common English words. Average English runs about 1.3 tokens per word; a rare surname might be five tokens; a Devanagari sentence can be three or four times its English equivalent. The splitter above makes this obvious in ten seconds.
“Images and files don’t use tokens.”
They absolutely do. Images are converted into token-equivalents based on their dimensions — a high-resolution screenshot can cost well over a thousand. PDFs are extracted to text and tokenized like anything else, and tables and scanned pages are especially expensive. Audio and video are worse still.
“If it fits in the window, the model reads it all equally.”
Fitting is necessary, not sufficient. Attention is uneven — beginnings and endings dominate. Fitting a document into context guarantees the model can see it, never that it will weigh every paragraph the same.
Quick reference
| Term | In one line |
|---|---|
| Token | The smallest unit of text a model reads; usually a word fragment. |
| Tokenizer | The component that converts text into token IDs and back again. |
| Vocabulary | The fixed list of all tokens a model knows — typically 50K–200K entries. |
| BPE | Byte Pair Encoding — the merge-the-most-frequent-pair algorithm that builds that list. |
| Context window | Maximum tokens the model can hold at once, input and output combined. |
| Input tokens | Everything you send: prompt, history, files, tool definitions. |
| Output tokens | Everything the model writes back. More expensive, generated one at a time. |
| Truncation | Cutting content that doesn’t fit — sometimes silently. |
| RAG | Retrieval-augmented generation: fetch only the relevant passages, then answer. |
| Prompt caching | Reusing the processed form of an unchanged prompt prefix to cut cost and latency. |
| KV cache | Stored intermediate values for tokens already processed; grows with context length. |
| Lost in the middle | The measured tendency to recall the start and end of a long context better than the middle. |
Check yourself
Five questions. No score is recorded anywhere — this is just for you.
Frequently asked questions
How many tokens is 1,000 words?
About 1,300 tokens for ordinary English prose. Technical writing with lots of code, names, or numbers runs higher — budget 1,500. Hindi, Tamil, Arabic or Korean text of the same length can reach 3,000–5,000.
How do I count tokens exactly?
Use the tokenizer library published for your specific model family — the count is model-specific, so a number from one vendor’s tool won’t match another’s precisely. For planning, the four-characters-per-token estimate is close enough; for billing and hard limits, count properly in code before you send.
Does a longer chat cost more even if my messages are short?
Yes, and this surprises almost everyone. The full history is re-sent every turn, so input cost grows roughly with the square of conversation length. Starting a fresh chat for a new topic is not just tidier — it is cheaper and usually produces better answers.
What’s the difference between context window and training data?
Training data is what shaped the model’s weights months ago — permanent, general, and unchangeable at chat time. The context window is working memory for right now — temporary, specific, and gone when the session ends. A model can be trained on the whole internet and still not know what’s in a document you haven’t pasted.
Can I make my text use fewer tokens?
Yes, meaningfully. Strip boilerplate and markup, drop repeated headers and footers, replace long IDs with short labels, summarise older conversation turns, send excerpts instead of whole files, and prefer plain common vocabulary over ornate phrasing. Compressing prompts by 30–50% with no loss of meaning is routine once you look for it.
Why do models struggle with counting letters and long arithmetic?
Because tokenization hides the internal structure. The model sees IDs for word fragments, not individual characters or place-value digits. Spacing the characters out (s-t-r-a-w) or asking it to use a calculator tool both fix it, and both work because they change what the tokenizer produces.
Where this leaves you
Two ideas, and everything downstream follows from them. Text becomes tokens — fragments, not words, priced by how ordinary they are. Tokens live inside a window — a hard-edged desk, not a memory, holding your instructions, your documents, your entire chat history and the answer being written, all at the same time.
Once those two things are solid, the rest of the field stops looking like magic. Retrieval is a technique for choosing what goes on the desk. Prompt caching is a technique for not re-reading the same corner of it. Summarisation buys space. Chunking buys attention. Even the odd failures — the miscounted letters, the sudden amnesia at message 40, the report that stops mid-sentence — become predictable, and therefore preventable.
Try this before you close the tab: take a prompt you use regularly, paste it into the splitter near the top of this page, and look at the number. Most people discover their standard prompt is two or three times more expensive than they assumed, and that a third of it is boilerplate the model never needed. That’s a five-minute experiment that has saved teams I’ve worked with real money — and it starts with just looking at the tokens.
tokenscontext windowtokenizationBPEprompt engineeringLLM basics

