Skip to chapter content
navan✳THE BUILD LABAI ENGINEERING / GUIDE
0/21 read
CHAPTER 03 / 21 · FIRST PRINCIPLES

Tokens, context, and attention.

Learn how text enters a language model, what a context window limits, and why more text can make an answer worse.

BY NAVAN SAMILONG READTHEORY FIRST
01 / FROM THE BEGINNING

Start with the meaning.

A language model does not read a sentence as a human reads it. Its input is divided into tokens: units that may be whole words, word pieces, punctuation, or spaces depending on the tokenizer. The model processes a sequence of token identifiers and estimates what token should follow. That prediction process can produce coherent paragraphs because training exposed the model to many language patterns.

The context window is the amount of input and generated output the model can consider in one call. It is a capacity limit, often measured in tokens. Conversation history, instructions, retrieved documents, and the new question all use that budget. A long window can hold more evidence, but capacity is not comprehension. Irrelevant material can distract the model and make the important passage harder to use.

02 / THE SYSTEM

How the idea works.

Transformers use attention mechanisms to let positions in the sequence draw information from other positions. The exact mathematics matters for model research, but an application designer first needs the practical consequence: output depends on the supplied sequence and its ordering. If a key constraint is buried among many unrelated pages, the model may fail to apply it. Structure, labels, and concise context help the model find the relevant evidence.

Token count affects price and latency for many hosted models. A system that sends an entire conversation on every turn repeats old material and pays for it again. Summaries can reduce this burden, but they may omit details. A safer memory design distinguishes durable facts, recent turns, and source documents, each with its own retention rule. Do not silently compress an instruction that controls permissions or safety.

The model's training knowledge is separate from the current request. A fact may have changed since training, or the model may not have learned it accurately. Supplying a document in context can ground an answer in current evidence, but the model may still misquote or combine passages incorrectly. Retrieval and citation checking address that problem later in the course.

Imagine a request containing system instructions, 20 pages of retrieved documents, a long conversation, and a question. Even when all of it fits within the formal window, the model must identify which parts matter. A retrieval stage can first find likely passages, then a context builder can include titles and section IDs. This resembles preparing a concise reading packet for a person: relevance and organization help more than simply handing over a larger stack of paper.

Budgeting must leave room for the output as well as the input. If a model accepts a total context of N tokens, instructions, messages, documents, and generated text all compete within that limit. A request that fills the available input space can leave too little room for a complete answer. In practice, count with the model's actual tokenizer, set an output allowance, and inspect truncation as a distinct failure rather than treating it as an ordinary short answer.

01InstructionWhat to do02QuestionThe current turn03EvidenceRelevant passages04OutputGenerated tokens
Instructions, recent turns, and evidence share a limited context budget.
03 / PYTHON, EXPLAINED

Follow the code.

tokens-and-context.py
def make_context(question, passages, character_budget=1200):
    selected = []
    used = 0
    for passage in passages:
        line = f'[{passage["id"]}] {passage["text"]}'
        if used + len(line) > character_budget:
            break
        selected.append(line)
        used += len(line)
    return "Question: " + question + "\nEvidence:\n" + "\n".join(selected)

This example demonstrates a budget and labels each passage by identifier. It counts characters because the standard library cannot know a particular model's tokenization. Character count is only a rough proxy; production code should use the tokenizer or counting method appropriate to its model. The function stops before including a passage that would exceed the chosen budget.

Order matters: the code assumes passages are already ranked by relevance and permission. If the first passage is irrelevant, a short budget makes the problem worse. A retrieval stage should select good evidence before packing it into the context.

04 / THE BOUNDARY

What the result does not say.

A larger context window can support complex tasks, but it also increases the surface for contradictory instructions and private data. Decide what each model call genuinely needs.

Do not infer a model's reasoning quality from fluent text. Next-token prediction can yield useful analysis, but reliability must be measured on the task the application actually performs.

05 / KEEP THIS

One clear idea.

A context window is limited space for relevant evidence and instructions, not a guarantee of understanding.

THE CODE IN CONTEXT

The AI cookbook

Complete, explained local workflows sit alongside this reading course.

Browse the cookbook
Finished reading?
Built with curiosity. By Navan Sami. ↗AI engineering · From model calls to reliable systems.