Lesson 05 Context Windows & Long Documents
Theme:
Lesson 05 · Slide 1

Context Windows & Long Documents

Modern models have enormous context windows — but bigger doesn't always mean better. Learn to work with long documents effectively and economically.

Learning Objectives

Lesson 05 · Slide 2

Context Window Sizes

Context windows have grown dramatically since 2022. The constraint is no longer "fits in context?" but cost, latency, and attention quality.

ModelContext windowApprox. pagesNotes
Claude Haiku 3.5200 K tokens~500 pagesLow per-token cost
Claude Sonnet 4200 K tokens~500 pagesMedium per-token cost
GPT-4o128 K tokens~320 pagesMedium per-token cost
Gemini 1.5 Pro1 M tokens~2 500 pagesWatch output costs

Rule of thumb: 1 token ≈ 0.75 English words ≈ 4 characters. A 200-page PDF is roughly 50 K tokens — well within any modern model, but still costs money on every call.

Lesson 05 · Slide 3

Lost in the Middle

Liu et al. (2023) demonstrated that LLM performance degrades for information placed in the middle of long contexts. Models recall the beginning and end much more reliably.

Key finding: on multi-document QA tasks, accuracy was ~20 percentage points lower when the relevant document was placed in the centre of a 20-document context versus at position 1 or position 20.

Visualising the Effect

Recall quality by document position (schematic — start and end are high, middle dips):

← Start of context              End of context →

Mitigations

Lesson 05 · Slide 4

Chunking Strategies

When a document is too long or too expensive to fit in context, split it into chunks and process each independently.

StrategyHow it worksProsCons
Fixed-size with overlap Split every N words; consecutive chunks share K words Simple, predictable cost May cut mid-sentence or mid-idea
Sentence-based Split on sentence boundaries; group sentences until size limit Preserves sentence integrity Chunk sizes vary; needs NLP library
Semantic Embed sentences; split where cosine similarity drops Topically coherent chunks Requires embedding model; slower

Overlap tip: 10–15% word overlap between consecutive chunks prevents losing context at boundaries. For 500-word chunks, use ~50-word overlap.

Lesson 05 · Slide 5

Summarisation Patterns

Two battle-tested architectures for summarising documents that exceed your context window.

Map-Reduce

[chunk 1] → summary 1 ↘
[chunk 2] → summary 2 → COMBINE → final
[chunk 3] → summary 3 ↗

All chunks processed independently (parallelisable). Fast, but may lose cross-chunk relationships.

Refine

[chunk 1] → running summary
[chunk 2] + running → updated
[chunk 3] + updated  → final

Sequential — cannot parallelise. Better narrative coherence but O(n) calls; early errors propagate.

Choosing: use map-reduce when speed matters or chunks are independent. Use refine when narrative coherence is critical (fiction, legal briefs, medical notes).

Lesson 05 · Slide 6

Full Context vs RAG

Not every long-document problem needs chunking. Sometimes stuffing the whole document in is simpler and better; sometimes it's overkill or impossible.

SignalFull contextRAG / chunking
Document size< 100 K tokens, cost acceptableExceeds model limit or too expensive per call
Update frequencyStatic document, queried rarelyFrequently updated corpus
Query typeWhole-document synthesis or comparisonSpecific fact lookup or search
LatencySingle call, predictableCan be faster with small retrieval
CostPays full context on every callOnly pay for retrieved chunks

Decision rule: if the document fits in context and you query it infrequently, go full context. If it's a knowledge base queried hundreds of times a day, build RAG.

Lesson 05 · Slide 7

Demo

Live walkthrough of map-reduce summarisation on demo/sample_document.txt.

Demo Steps

  1. Open demo/sample_document.txt — a ~4 000-word history of AI
  2. Count tokens with tiktoken: note the raw count vs word count
  3. Run chunk_text(text, chunk_size=500, overlap=50) — inspect chunk count and first chunk boundary
  4. Summarise one chunk with Claude to confirm the API call works
  5. Run full map_reduce_summarize(chunks) — watch intermediate summaries appear
  6. Compare cost: single-pass (full text in one call) vs map-reduce (multiple smaller calls)
Notes: Run map-reduce on sample_document.txt, show intermediate summaries printing as they complete. Point out the cost difference between chunked and single-pass approaches.

📥 Demo Files

⬇ sample_document.txt
Lesson 05 · Slide 8

Lab & Homework

Lab Exercises

  1. Chunking — implement chunk_text(text, chunk_size, overlap); verify chunk count, boundary quality, and that overlapping words appear in consecutive chunks
  2. Map-Reduce — implement summarize_chunk() and map_reduce_summarize(); run on the sample document and print intermediate summaries
  3. Cost Comparison — calculate token counts for single-pass vs map-reduce; build a comparison table: approach / input tokens / output tokens / estimated cost

Homework Tasks

  1. Try chunk sizes 256 / 512 / 1024 words — compare summary quality and cost for each. Document which worked best and why.
  2. Implement refine_summarize(chunks) — start with a summary of chunk 0, then for each subsequent chunk ask Claude to refine the running summary. Compare result quality with map-reduce.
  3. Calculate: at what exact document token length does map-reduce become cheaper than single-pass? Show the algebra — write the cost formula for each approach and solve for the crossover point.
1 / ?