Sub topic 2
Tokens and budgeting the window
This chapter assumes you have called a model through a chat or API interface and can read short Python. It covers how tokens measure the context window and how to split that window into a budget.
What a token is
A token is the unit of text a model reads and writes. It is often a word, part of a word, or a punctuation mark. For English prose, one token is roughly four characters, or three quarters of a word. Code, non-English text, and unusual strings usually need more tokens per character.
The context window is the maximum number of tokens the model can handle in one call. Providers count input and output together against this limit. If your input uses the whole window, the model has no room to answer.
Tokens also set cost and speed. Providers bill per token, and longer inputs take longer to process. Every token you include should earn its place.
Dividing the window
Treat the window as a budget with fixed and flexible parts.
- Output reserve: space you set aside for the answer. Set it first, because the model cannot write past the limit.
- Fixed costs: the system prompt and the current question. You must include these.
- Flexible space: what remains. Retrieved documents and conversation history compete for it.
The split between documents and history is a design choice. A question-answering tool may favor documents. A long chat assistant may favor history.
A budget builder
The code below estimates token counts, then fills the flexible space. It ranks documents by relevance score and keeps the most recent history that still fits.
def estimate_tokens(text):
# Rough heuristic: about 4 characters per token for English text.
# Use your model provider's tokenizer for exact counts.
return max(1, len(text) // 4)
def pick_within_budget(items, budget):
chosen, used = [], 0
for item in items:
cost = estimate_tokens(item)
if used + cost > budget:
break
chosen.append(item)
used += cost
return chosen, used
def build_context(system, question, history, docs, window, output_reserve, doc_share=0.5):
# docs is a list of (relevance_score, text) pairs; history is oldest-first.
remaining = window - output_reserve - estimate_tokens(system) - estimate_tokens(question)
if remaining <= 0:
raise ValueError("system prompt and question leave no room")
ranked_docs = [text for _, text in sorted(docs, key=lambda d: d[0], reverse=True)]
picked_docs, used_docs = pick_within_budget(ranked_docs, int(remaining * doc_share))
picked_history, _ = pick_within_budget(list(reversed(history)), remaining - used_docs)
picked_history.reverse()
return {
"system": system,
"documents": picked_docs,
"history": picked_history,
"question": question,
}
system = "S" * 400 # about 100 tokens
question = "Q" * 200 # about 50 tokens
history = ["h" * 200] * 10 # 10 messages, about 50 tokens each
docs = [(0.9, "d" * 800), (0.5, "e" * 800), (0.7, "f" * 800)] # about 200 each
ctx = build_context(system, question, history, docs, window=1000, output_reserve=200)
print(len(ctx["documents"]), len(ctx["history"]))Running it prints 1 9. Here is how the numbers work out:
- Remaining space is 1000 - 200 - 100 - 50 = 650 tokens.
- The document share is half of that, 325 tokens. The 0.9 document fits (200 tokens). The 0.7 document would bring the total to 400, so selection stops.
- History gets everything left over: 650 - 200 = 450 tokens. That holds nine of the ten messages. The oldest message is dropped.
Unused document space flows to history. That is why history is computed from remaining - used_docs rather than from a fixed share.
Common errors
- Forgetting the output reserve. The call fails or the answer is cut off mid-sentence.
- Trusting the 4-characters rule everywhere. It is a rough guess for English. Count with the provider's tokenizer before you run close to the limit.
- Stopping at the first item that does not fit.
pick_within_budgetbreaks at the first overflow to preserve rank order. If you would rather skip a large item and try smaller ones, changebreaktocontinue. That choice can let lower-ranked items in ahead of higher-ranked ones. - Filling the whole window. A full window is not a goal. Extra tokens add cost and latency, and irrelevant text can distract the model. Later chapters cover this.
Exercise
A window is 2,000 tokens. The output reserve is 400, the system prompt is 300, and the question is 100. With doc_share=0.5, how many tokens can documents use at most, and how many are left for history if documents use all of their share?
Show answer
Remaining space is 2000 - 400 - 300 - 100 = 1,200 tokens. Documents can use at most 600 (half). If they use all 600, history gets 1200 - 600 = 600 tokens.