Velamuvi AIAcademy

Lesson 6 of 11 · Generation

Context Windows in Practice

Work within an LLM context window: token budgets, chunking, summarising and retrieval for long documents, plus cost, speed, caching and lost-in-the-middle.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • How to budget a context window between its parts
  • What to do when a document does not fit: chunk, summarise or retrieve
  • How long contexts affect quality, speed and cost
  • How prompt caching makes repeated context cheaper

The window is shared

A context window holds everything for one request: the system prompt, the conversation so far, any documents, tool results, and the answer the model is about to write. Building a reliable app means budgeting it.

Type into the box to see how quickly text turns into tokens:

Loading the tokenizer…
0 tokens · 18 words · 107 characters

A token budget

Try it yourselfPython
window = 200_000          # the model's context window, in tokens

budget = {
    "system prompt": 2_000,
    "conversation so far": 12_000,
    "reserved for the answer": 8_000,
}
used = sum(budget.values())
free = window - used

for part in budget:
    print(f"{part:24} {budget[part]:>8,}")
print(f"{'left for documents':24} {free:>8,}")

document_tokens = 450_000   # a long report
if document_tokens <= free:
    print("The whole document fits.")
else:
    print(f"The document is {document_tokens - free:,} tokens too big: "
          "split it, summarise it, or retrieve only the relevant parts.")

Always reserve room for the answer. If the input fills the window, there is no space left for the model to write, and the request fails or the answer is cut short.

When a document does not fit

StrategyHow it worksGood for
TruncateKeep only the start (or end)Rarely a good idea: you lose information silently
Chunk and processSplit into pieces, handle each, combine the resultsSummarising or extracting from the whole document
Summarise firstReplace long material with a summaryLong chat histories, background documents
RetrieveStore chunks, then fetch only the ones relevant to the questionQuestions about large documents or many documents
Try it yourselfPython
def chunk(words, size, overlap):
    chunks = []
    start = 0
    while start < len(words):
        chunks.append(words[start:start + size])
        if start + size >= len(words):
            break
        start += size - overlap      # step forward, keeping some overlap
    return chunks

text = ("The museum opens at nine. Tickets cost twelve euros. Children under five "
        "enter free. The cafe on the top floor closes at four. Guided tours start "
        "every hour from the main hall.")
words = text.split()

for i, piece in enumerate(chunk(words, size=12, overlap=3), start=1):
    print(f"Chunk {i}: {' '.join(piece)}")

Notice the overlap: "Children under five" ends chunk 1 and starts chunk 2, so the fact "Children under five enter free" survives in one piece. Real systems chunk by tokens or by paragraphs and headings, but the idea is the same.

Long contexts: quality, speed and cost

Large windows are useful, but they are not free:

  • Cost: every input token is billed, on every request. A 150,000-token document costs 150,000 tokens each time you ask about it.
  • Speed: the model must process all input before writing; the first word of the answer arrives later.
  • Quality: models are much better than they used to be at using long contexts, but details buried in the middle of a very long input can still be missed or mixed up ("lost in the middle"). Pointing to the relevant part, or putting the question after the material, helps.

Common mistakes

Practice exercise

Work out how many overlapping chunks a long document needs.

Your solutionPython
total_tokens = 10_000   # length of the document
size = 1_000            # tokens per chunk
overlap = 200           # tokens shared with the previous chunk

# Count how many chunks the document is split into, using the same rule
# as the lesson: each new chunk starts (size - overlap) tokens after the last,
# and you stop once a chunk reaches the end. Print it like: 13 chunks
Knowledge check

A 300,000-token document must be questioned with a model whose window is 128,000 tokens. Which approach makes most sense?

Summary

  • A context window is shared by instructions, history, documents, tool results and the answer: budget it and reserve room for the answer.
  • When material does not fit: chunk, summarise or retrieve (RAG); avoid silent truncation.
  • Overlap between chunks keeps sentences at boundaries intact.
  • Long contexts cost more, respond slower and can lose details in the middle.
  • Prompt caching makes a repeated opening block cheaper: stable content first, new question last.

Next: how system, user and assistant messages work in the API.

Finished reading? Tick it off to track your progress.