Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 4/ 160
01. LLM Fundamentals

Context Windows

Maximum input length, long-context techniques, and practical limits when stuffing prompts with docs.

BeginnerMax Tokens · Long Context3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

The window is how much the model can read and write in one go. Anything that doesn't fit gets cut off or forgotten.

Think of it like…

A desk of fixed size: instructions, the notes you're working from and the page you're writing all need space on it at once. A bigger desk helps, but piling it with every paper you own makes it harder to find the one sheet you need.

Where you’ve seen it

A contract-review tool sends the full 180-page agreement (about 120K tokens) plus a question. It works on a 200K-window model but costs about 30 times a retrieval-based answer and misses clauses buried in the middle. Switching to chunk-and-retrieve (6 relevant sections, about 4K tokens) cuts cost sharply and raises accuracy on a labelled test set, so they keep full-document mode only for whole-contract summaries.

Words you’ll hear

Context window
Total tokens (input + output) a model handles in one request.
Max output tokens
A separate cap on how many tokens the model may generate.
Lost in the middle
Models often use information at the start and end of a long prompt better than the middle.
Context budget
Your plan for how many tokens each prompt component may use.

Visual diagram

Loading interactive diagram

Theory & deep dive

Budgeting and managing the window

Treat the window as a budget. Reserve the output tokens you need first, then allocate the rest: a stable system prompt, a bounded slice of conversation history, retrieved context, and tool results. Count tokens with the model's tokenizer before each request and trim the lowest-value material first. Chat history is commonly managed by keeping the last N turns verbatim and replacing older turns with a running summary.

Because each call re-sends the entire prompt, long contexts increase cost and time-to-first-token on every turn, not just once. Prompt caching helps when a long prefix is stable, but history that changes each turn is still billed as fresh input.

A simple budget for a 32K model

Reserve 2K for the answer, 1K system prompt, 6K recent history (the rest summarised into 500 tokens), and up to 12K of retrieved chunks. That totals about 21.5K, leaving a safety margin for tool output and tokenizer variance.

Key takeaway: Count tokens, reserve output first, and trim by value, not just by age.

Long context is not perfect memory

Research and practice show recall is uneven across long prompts: facts at the beginning and end are used more reliably than facts in the middle ("lost in the middle"), and accuracy on multi-fact questions tends to fall as irrelevant text is added. Models differ, and recent long-context models are much better, but you should test on your own data with the needle placed at different depths rather than trust the headline window size.

Alternatives to stuffing include retrieval (send only relevant chunks), hierarchical summarisation (map-reduce over sections), and structured memory (store facts outside the prompt and fetch them on demand). Use the full window when the task genuinely needs global context, such as summarising an entire document or reasoning across a whole codebase, and otherwise send less.

A quick needle test

Insert a known fact at 10%, 50% and 90% depth of a 100K-token filler document, ask for it, and record accuracy at each depth. If the 50% position drops, put critical instructions and key evidence at the start or end of your prompts.

Key takeaway: Test recall by position; prefer retrieval over stuffing unless the task needs the whole text.

How it works, step by step

Step 1 of 4
Design

1. Set the budget

Decide token allowances for system prompt, history, retrieval, tool output and the reply.

window − output reserve − safety margin
Key numbers at this step
Margin
5 – 10%

When to use it & trade-offs

What it is

A context window is the maximum number of tokens a model can consider in one request, and it has to hold everything: the system prompt, conversation history, retrieved documents, tool results and the model's own output. Windows now range from about 8,000 tokens to over a million, but a bigger window is not the same as using it well: accuracy, cost and latency all change as you fill it.

Why it matters: Most production failures with long inputs are budget and placement problems rather than model problems: a chat history that silently overflows, 20 retrieved chunks that bury the one that matters, or a 500-page contract stuffed into a prompt that costs dollars per call. Understanding limits, the lost-in-the-middle effect and alternatives to stuffing (retrieval, summarisation, caching) is core AI engineering.

When to reach for it

  • Budgeting tokens across prompt components
  • Deciding between long context and retrieval
  • Managing multi-turn chat history

When to avoid or be careful

  • Assuming the advertised window is the effective window for accuracy
  • Forgetting that output tokens count toward the same window
  • Sending entire histories every turn without trimming

Ways to give a model large amounts of information

Stuff everything into the window
Best for: Whole-document tasks such as summarising one file

Strengths: Simplest; model sees all the context.

Watch out: Costly and slow; middle-of-prompt recall can drop.

Retrieve relevant chunks (RAG)
Best for: Question answering over large corpora

Strengths: Small prompts, lower cost, easier citations.

Watch out: Depends on retrieval quality; can miss cross-document reasoning.

Summarise hierarchically (map-reduce)
Best for: Documents bigger than any window

Strengths: Handles unlimited length.

Watch out: Loses detail; multiple calls and compounding errors.

Interview signals & numbers to know

When this topic comes up

  • “The model ignores part of my long prompt”
  • “Should we just use the 1M window?”
  • “Requests fail with a context length error”
  • Lost in the middle
  • Chat history management

Benchmarks & rules of thumb

8K – 1M+ -
range of context windows today
5 – 10% -
safety margin to keep free
start and end -
where recall is typically strongest

Common mistakes & follow-ups

Common interview mistakes

  • Filling the window with input and leaving too few tokens for the answer, so replies cut off mid-sentence.
  • Trusting needle-in-a-haystack headline results for multi-fact reasoning over long inputs.
  • Appending every retrieved chunk to history, so each later turn re-sends and re-pays for them.

Likely interviewer follow-ups

  • How would you manage conversation history for a long chat?
  • When would you choose retrieval over a long context window?
  • What is the lost-in-the-middle problem and how do you mitigate it?
Interview tip: Say "window, minus output, minus margin" and then explain how you'd test recall by position. A budget plus a test is a complete production answer.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Context Windows with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Self-Attention
Next topic
KV Cache