TExcelTAD
Home › Generative AI & LLMs › Context Windows

Context Windows

An LLM has no memory between requests. Everything it can "see" when it generates a reply — the system prompt, the conversation so far, pasted documents, tool results, and the reply it is writing — must fit inside its context window, a fixed maximum number of tokens. Current models offer windows from tens of thousands to a million tokens or more, depending on the model.

What fills the window

text
┌──────────────────────── context window (N tokens) ────────────────────────┐
│ system prompt │ earlier turns │ documents / tool results │ user │ reply … │
└───────────────────────────────────────────────────────────────────────────┘

The reply counts too: if the input already uses almost the whole window, there is little room left for output. APIs let you cap the output with a parameter such as max_tokens.

Estimating token counts

Exact counts need the model's own tokenizer (providers offer token-counting endpoints). For planning, a rough rule for English is about 4 characters per token:

python · try it yourself
def estimate_tokens(text):
    return max(1, round(len(text) / 4))

messages = [
    ("system", "You are a concise assistant for a bicycle shop."),
    ("user", "What size frame do I need? I am 178 cm tall."),
    ("assistant", "For 178 cm, most road bikes in size M (54-56 cm) fit well. A test ride is best."),
    ("user", "And for a mountain bike?"),
]
total = 0
for role, text in messages:
    n = estimate_tokens(text)
    total += n
    print(f"{role:<9} ~{n:>3} tokens")
print(f"total     ~{total:>3} tokens")
system    ~ 12 tokens
user      ~ 11 tokens
assistant ~ 20 tokens
user      ~  6 tokens
total     ~ 49 tokens

Staying inside the budget

Long chats and big documents eventually overflow. Common strategies:

Strategy Idea Trade-off
Sliding window keep the system prompt and the newest turns, drop the oldest forgets early details
Summarise replace old turns with a short summary summary can lose facts
Retrieve (RAG) store everything outside; insert only relevant pieces needs a search step
Truncate documents send only the relevant sections must know what is relevant

Here is a sliding window that always keeps the system prompt and as many recent messages as fit, leaving room for the reply:

python · try it yourself
def estimate_tokens(text):
    return max(1, round(len(text) / 4))

def fit_to_window(system, history, window, reserve_for_reply):
    budget = window - reserve_for_reply - estimate_tokens(system)
    kept = []
    for msg in reversed(history):              # newest first
        cost = estimate_tokens(msg["content"])
        if cost > budget:
            break
        kept.insert(0, msg)
        budget -= cost
    return kept

system = "You are a helpful travel assistant."
history = [
    {"role": "user", "content": "I'm planning a week in Portugal in May."},
    {"role": "assistant", "content": "Lovely! Lisbon, Porto and the Algarve are popular. What do you enjoy?"},
    {"role": "user", "content": "Food, old towns and some hiking."},
    {"role": "assistant", "content": "Try Porto for food, Sintra for palaces, and the Rota Vicentina trail."},
    {"role": "user", "content": "How many days in Porto?"},
]
kept = fit_to_window(system, history, window=60, reserve_for_reply=20)
print(f"kept {len(kept)} of {len(history)} messages:")
for m in kept:
    print(f"  {m['role']}: {m['content']}")
kept 3 of 5 messages:
  user: Food, old towns and some hiking.
  assistant: Try Porto for food, Sintra for palaces, and the Rota Vicentina trail.
  user: How many days in Porto?

The model still knows the user likes hiking, but no longer that the trip is one week in May — so it cannot sensibly answer "how many days in Porto?". That is the classic symptom of a too-small window. A short summary of the dropped turns ("User: one week in Portugal in May") would preserve the key facts for a few tokens.

Bigger is not free

Self-attention compares every token with every other one, so its work grows roughly with the square of the context length (real systems use many optimisations, but long inputs still cost more time and money):

python · try it yourself
for n in [1_000, 10_000, 100_000]:
    pairs = n * n
    print(f"{n:>7,} tokens -> {pairs:>15,} token pairs ({pairs // 1_000_000:,}M)")
  1,000 tokens ->       1,000,000 token pairs (1M)
 10,000 tokens ->     100,000,000 token pairs (100M)
100,000 tokens ->  10,000,000,000 token pairs (10,000M)

There are also quality effects. Models are generally best at using information near the start and end of a long prompt; facts buried in the middle of a huge context can be overlooked (often called lost in the middle). Newer models handle long contexts much better, but it is still good practice to:

  • put the most important instructions at the start (system prompt) and repeat the key question at the end,
  • send only the relevant parts of long documents,
  • clearly label documents, e.g. with <document> tags.

Tip: "The model forgot what I said" in a chat app is usually not a model defect — the app dropped or summarised old messages to stay inside the window.

Test yourself

What must fit inside the context window?

  1. Only the user's latest message
  2. The whole input (system prompt, history, documents) plus the generated reply
  3. The model's training data
  4. Only the reply

A chat app keeps only the newest messages that fit. What is the main downside?

  1. The reply gets longer
  2. Facts from early in the conversation are forgotten
  3. The model becomes slower
  4. The system prompt is deleted

Roughly how does self-attention work grow when the context length doubles?

  1. It stays the same
  2. It doubles
  3. It roughly quadruples
  4. It halves