Language model tokens and context
From text to tokens
A language model processes tokens: units represented by integer IDs in a model-specific vocabulary. A token can correspond to a word, part of a word, punctuation or a byte sequence. For example, an invented vocabulary might split “reusable” into “re” and “usable”; another might keep it whole. This is illustrative, not the output of a real tokenizer. The same sentence can use different numbers of tokens under different tokenizers. Token IDs are categorical identifiers, not measurements of meaning. A language model maps those IDs to learned representations and, in a decoder-only model, repeatedly predicts a distribution over possible next tokens.
The context window is a capacity, not a memory guarantee
The context window bounds the sequence a model can process for a request. In a simple shared-budget decoder model, input tokens plus generated tokens must fit the window. Input can include instructions, previous messages, retrieved documents, formatting and special tokens, not only the latest user text. Some providers impose a separate output cap or account for reasoning tokens differently. Use the exact model and API documentation and count the fully formatted request; a word count or plain-text token estimate is insufficient. A model may overlook a relevant fact even if it fits. A context window does not guarantee durable memory, accurate retrieval or reliable reasoning.
Example: reserve room for output
Suppose an invented model accepts 100 tokens total. An already counted 70-token request and a 20-token output reservation leave 10 unused tokens. A 90-token request with the same reservation overflows by 10. Our pure Python accounting uses nonnegative integers and reports either spare space or overflow. It does not tokenize text or predict actual generated length.
def budget_report(window, input_tokens, reserve): if any(type(n) is not int or n < 0 for n in (window, input_tokens, reserve)): raise ValueError("counts must be nonnegative integers") remaining = window - input_tokens - reserve return {"fits": remaining >= 0, "spare": max(0, remaining), "overflow": max(0, -remaining)}
print(budget_report(100, 70, 20))print(budget_report(100, 90, 20))Expected reports: {'fits': True, 'spare': 10, 'overflow': 0} and {'fits': False, 'spare': 0, 'overflow': 10}. Zero spare still fits exactly. The output reservation is a planning choice, not a promise of generation length.
Example: retain whole recent history segments
If a request does not fit, reject it, retrieve less material, or deliberately shorten optional history. Preserve mandatory instructions and the current task. Summaries can lose exceptions, provenance or exact wording; retain important evidence separately. The following policy preserves the longest contiguous suffix of optional whole history segments that fits after mandatory input and output reserve. It never silently drops required content. Counts are assumed to include any formatting overhead allocated to each segment; a real serializer must recount the resulting request.
def keep_recent(window, required, history, reserve): if any(type(n) is not int or n < 0 for n in [window, required, reserve, *history]): raise ValueError("counts must be nonnegative integers") room = window - required - reserve if room < 0: return None kept = [] for i in range(len(history) - 1, -1, -1): if history[i] > room: break kept.append(i) room -= history[i] return list(reversed(kept))
print(keep_recent(100, 40, [15, 25, 10], 20))print(keep_recent(50, 40, [5], 20))Expected lines: [1, 2] and None. With 40 tokens available for history, the newest two segments consume 35. The older 15 cannot fit. None means the mandatory input and reserve alone exceed the window; an empty list means no history is retained but the mandatory request fits. This is one policy, not a universal truncation strategy.
Inference, stopping and observable behavior
Inference means using the fitted model rather than updating its weights. In a typical autoregressive decoder, the prompt is processed first, then each new token conditions the next prediction. An end-of-sequence token, supported stop sequence, output limit or cancellation can stop generation. A length-limited response may end mid-sentence or mid-JSON; check the reported finish reason where available and validate completeness. A stop marker is not a correctness check. KV caching can avoid repeating some attention computations, but is not durable conversational memory. Actual latency depends on model, input, output, batching and hardware.
Practice and common mistakes
For a 100-token budget with 68 mandatory tokens and a 25-token output reserve, only 7 tokens remain. Explain what you would do if a mandatory source passage requires 12 additional tokens. Never silently remove safety instructions or essential evidence. Recount after any change. Next: sampling and factual limits.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Language model tokens and context quiz
Apply the chapter concepts to synthetic model requests and recorded responses.
A formatted request uses 70 tokens, the window is 100 and 20 are reserved. How much spare capacity remains?
Why can two requests with the same word count have different token counts?
What does keep_recent return when mandatory input and reserve exceed the window?
A generation limit stops a response halfway through a JSON object. What should the application do?
What does a model context window specify?