Sub topic 3
Tokens and context windows: will it fit?
This chapter assumes you can write basic Python, have sent prompts to an LLM through an API or chat interface, and know that models read text as tokens. By the end you should be able to estimate whether a document fits in a model's context window before you send it, and know what to do when it does not.
Tokens are the unit that matters
A token is a piece of text that the model's tokenizer treats as one unit. A token can be a whole common word, part of a rare word, a punctuation mark, or a run of whitespace. The model never sees characters or words. It sees a sequence of token IDs.
Token counts matter for three reasons:
- Limits are set in tokens. A model accepts only a fixed number of tokens per request.
- Price is set in tokens. Providers charge per input token and per output token.
- Speed depends on tokens. More input takes longer to process, and more output takes longer to generate.
Different model families use different tokenizers. The same paragraph can be 900 tokens for one model and 1,000 for another. Never assume a count from one tokenizer holds for a different model.
Rules of thumb
For ordinary English prose, these approximations are common:
- One token is about 4 characters.
- One token is about three quarters of a word. So 1,000 tokens is roughly 750 words.
- A page of single-spaced text is roughly 500 to 700 tokens.
These ratios break down for other content:
| Content | Typical effect on token count |
|---|---|
| Plain English prose | Close to the rule of thumb |
| Other languages, especially non-Latin scripts | Often 1.5 to 3 times more tokens for the same meaning |
| Source code | More tokens per line because of symbols and indentation |
| Numbers, IDs, hashes, URLs | Many tokens, because they split into short pieces |
| Tables and JSON | Extra tokens for punctuation and repeated keys |
Use the rule of thumb for a quick check. Use the real tokenizer for any decision that has a cost or a failure attached to it.
Counting tokens properly
Many providers publish a tokenizer library or a token-counting endpoint. Use the one that matches your model. The example below uses the tiktoken library, which implements tokenizers for OpenAI models. If you use a different provider, replace the counting function with that provider's tool. The rest of the code in this tutorial only needs a function that takes a string and returns an integer.
import tiktoken
def make_counter(encoding_name="cl100k_base"):
enc = tiktoken.get_encoding(encoding_name)
def count_tokens(text):
return len(enc.encode(text))
return count_tokens
count_tokens = make_counter()
sample = "Summarisation turns a long document into a short one."
print(count_tokens(sample))The function count_tokens returned here has the same shape as the count_tokens argument in the chunking and summarising code later in this tutorial. You write it once and pass it around.
A cheap fallback when no tokenizer is available is to estimate from characters:
def estimate_tokens(text):
return len(text) // 4This is fine for rough planning. Add a safety margin of 20 to 30 percent when you rely on it, and more for code or non-English text.
What a context window is
The context window is the maximum number of tokens a model can handle in one request. It covers everything the model sees and produces in that request, not only your document. The window is shared between:
- The system prompt and your instructions.
- Any examples you include in the prompt.
- The document you want summarised.
- Earlier turns of the conversation, if you are in a chat.
- The output the model generates, including any hidden reasoning tokens some models produce.
Some providers state separate limits for input and for output. A model might accept 200,000 input tokens but cap the output at 8,000. Check the documentation for your exact model, because both numbers change between versions.
The budget formula
Treat the window as a budget you divide up before you send anything:
available_for_document = context_window
- instruction_tokens
- example_tokens
- history_tokens
- output_reserveThe output reserve is the part people forget. If the input fills the window, the model has no room left to write. Depending on the provider, you get an error or a summary that stops mid-sentence.
A fit check in code
The function below turns the formula into a reusable check. It returns whether the document fits and how many tokens remain.
def fits_in_window(document, instructions, count_tokens,
context_window, output_reserve,
examples="", history=""):
overhead = (
count_tokens(instructions)
+ count_tokens(examples)
+ count_tokens(history)
)
doc_tokens = count_tokens(document)
available = context_window - overhead - output_reserve
return {
"document_tokens": doc_tokens,
"available_tokens": available,
"fits": doc_tokens <= available,
"margin": available - doc_tokens,
}
instructions = "Summarise the following text in a short paragraph."
document = "word " * 5000
result = fits_in_window(
document,
instructions,
count_tokens,
context_window=8000,
output_reserve=500,
)
print(result)With an 8,000-token window and a 500-token output reserve, a 5,000-word document of repeated short words fits, because each word is about one token. A real 5,000-word article is closer to 6,700 tokens and would still fit, but only just. Always look at margin, not only fits. A margin near zero means a slightly longer instruction or document will break the request.
Choosing the output reserve
Size the reserve from the summary you want, not from a default:
- A one-paragraph summary needs roughly 150 to 300 tokens.
- A page-long summary needs roughly 600 to 800 tokens.
- A structured summary with headings and bullet points can need 1,000 or more.
- Add headroom if the model produces reasoning tokens before its answer, since those usually count against the output limit.
Window size is not the same as usable size
A document that technically fits may still be a poor candidate for one request. Three things push you to split early:
- Quality. Models tend to use information near the start and end of a long input more reliably than information in the middle. The chapter on long-context pitfalls covers this in detail. For now, treat the stated window as an upper bound, not a recommendation.
- Cost. A single request that fills a large window costs the same as the sum of its tokens. If you resend the full document for several different summaries, you pay for it each time.
- Latency. Long inputs take longer before the first output token appears.
A practical rule is to use single-pass summarisation only when the document uses a comfortable fraction of the window, for example under half, and to move to chunking when it gets close to the limit.
Common errors
- Counting words instead of tokens. A 100,000-word report is about 130,000 tokens in English, and more in other languages or with heavy formatting.
- Using the wrong tokenizer. A count from one model family can be off by 10 percent or more for another. The error grows for code and non-English text.
- Forgetting the output reserve. The request either fails or the summary is cut off.
- Ignoring the instructions and history. A long system prompt, pasted examples or an extended chat can consume thousands of tokens before the document arrives.
- Trusting the marketing number. Check the limit for the specific model version and endpoint you call. Input limit, output limit and total window can all differ.
- Counting once and editing later. If you add text to the prompt after the check, such as a retrieved note or a formatting rule, run the check again.
Deciding what to do next
Once you know the numbers, the decision is mechanical:
| Situation | Action |
|---|---|
| Document uses well under the available budget | Summarise in a single pass |
| Document fits but uses most of the window | Consider chunking anyway for quality and cost |
| Document is larger than the available budget | Split into chunks and use map-reduce or refine |
| Document is far larger than the budget | Add levels of summarising, as in hierarchical summarisation |
The next chapters build each of these strategies. The chunking code later in the tutorial uses the same count_tokens function you defined here to keep each chunk under a token budget.
Exercise
A model has a 16,000-token context window. Your instructions use 300 tokens, you include one example of 700 tokens, there is no chat history, and you want to reserve 1,000 tokens for the summary. A document is 14,500 tokens long. Does it fit in a single request? What is the margin, and what would you do?
Show answer
Available for the document = 16,000 - 300 - 700 - 0 - 1,000 = 14,000 tokens. The document is 14,500 tokens, so it does not fit. The margin is 14,000 - 14,500 = -500 tokens. Options: drop the example (freeing 700 tokens, which gives 14,700 available and a margin of +200, though that is thin), shorten the output reserve if a shorter summary is acceptable, or split the document into chunks and use map-reduce or refine. Because the margin would be so small even after dropping the example, chunking is the safer choice.
Exercise
You count tokens with a tokenizer for one model family, then send the text to a different model family and the request is rejected as too long, even though your check passed with a small margin. Give two likely causes and one fix.
Show answer
Likely causes: the second model's tokenizer produces more tokens for the same text (common for code, numbers and non-English text), and the check ignored some prompt content such as the output reserve, a system prompt or chat history. Fix: count tokens with the tokenizer or counting endpoint for the exact model you call, include every part of the request in the count, and keep a safety margin of 10 to 20 percent.