Chapter 3 of 40 · ~20 min read & lab+75 XP
Chapter 3 · Generative AI

LLM Context Windows, Token Inflation & Prompt Budget Packing

How production LLM apps pack system prompts, chat history, RAG chunks, and reserved output tokens inside a strict context window — avoiding Lost-in-the-Middle degradation and runaway decode bills.

What Is It?

A Context Window is the maximum number of input + output tokens an LLM can hold in working memory during a single request, directly governing both latency and dollar cost.

Why Is It Required?

Overflowing the context window crashes API calls or silently truncates instructions, and sloppy prompt packing wastes 50%–80% of your API budget.

Everyday Analogy: A desk with fixed surface area: every page of instructions, retrieved docs, and chat history competes for the same finite space.
Why ML Engineers & Data Scientists Actually Need This

Just because a model advertises a 128K context window doesn't mean stuffing 128K tokens is smart — latency, cost, and 'Lost in the Middle' accuracy all degrade!

ML / AI Engineer

Every production RAG or chat backend needs a deterministic Context Window Packer that guarantees System + User Query + max_output_tokens ALWAYS fit, then greedily packs highest-scoring RAG chunks and recent turns.

Data Scientist

Understanding Prompt Caching (placing static System instructions & documents at the exact prefix of the prompt!) routinely slashes LLM API bills by 50–90% overnight!

Interview & Debug Edge

Frequent AI Engineer system design question: 'Design a context-window budget manager for a multi-turn RAG chatbot — what gets truncated first, where do you place top chunks, and how do you maximize KV Prompt Cache hits?'

Step 0 · Test Your Gut Before Any Math!

To maximize Prompt Caching (90% input cost discount + 2–5× faster Time-To-First-Token) across repeated API calls, where MUST dynamic elements like the current timestamp or user's new question go?

What You Will Master in This Chapter
  • Budget a single LLM context window cleanly across System, Query, RAG Context, History, and Reserved Output tokens
  • Explain the 'Lost in the Middle' U-shaped recall curve and reorder high-priority chunks to the start/end
  • Explain why output tokens cost 3–5× more than input tokens and how Prompt Caching cuts input costs by up to 90%
  • Implement a deterministic priority-ordered Context Window Packer in Python
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
L_maxSay aloud:“max context window”
Plain-English Meaning
Hard upper limit on (input_tokens + output_tokens) accepted by a model
Everyday Example
128,000 tokens
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Think of an LLM's context window like a carry-on suitcase with a strict 20 kg airline limit. First you pack the non-negotiables (passport = System Prompt, boarding pass = User Query, and empty space for souvenirs = Reserved Output). Only THEN do you pack the highest-value clothes (top-ranked RAG chunks & recent chat turns) until the weight limit is reached — and you put the most important items right at the top and bottom where you can grab them instantly!

1. Anatomy of a Context Window & Priority Packing

Everyday Story First (Zero Math Yet!)

Slide the Total Window below to watch our budget packer reserve System + Query + Output first, then greedily pack the highest-scoring RAG chunks that fit!

Anatomy of One Context Window (e.g., 128,000 Tokens Total)System500 tokFew-Shot1.2KRetrieved RAG Chunks8K–64KChat HistorySliding WinReserved Outputmax_tokensBudget Rule: System + Query + Reserved Output are NEVER dropped; History & RAG pack remaining budget!
Every API call shares one finite context window across System Instructions, Few-Shot examples, Retrieved RAG chunks, Chat History, User Query, and reserved Output Max-Tokens.

The Production Context-Packing Equation

Bavailable=Lmax⁡−Tsystem−Tquery−RoutputB_{\text{available}} = L_{\max} - T_{\text{system}} - T_{\text{query}} - R_{\text{output}}

  1. Tier 0 (Never Drop): System prompt, tool schemas, current user query, and reserved output budget RoutputR_{\text{output}}.
  2. Tier 1 (High-Signal Context): Top-ranked RAG chunks packed in descending relevance order while used + chunk_tokens <= B_available.
  3. Tier 2 (Conversational Continuity): Most recent chat turns (sliding window or rolling summary of older turns).
Animated Mini-Lab • 1.2

Context-Window Budget Packer

Available for RAG: 2400 tok
Chunk 1 (score 0.94)
850 tok
PACKED ✓
Chunk 2 (score 0.89)
900 tok
PACKED ✓
Chunk 3 (score 0.82)
750 tok
DROPPED ✕
Chunk 4 (score 0.76)
800 tok
DROPPED ✕

2. Lost in the Middle & Strategic Context Ordering

Everyday Story First (Zero Math Yet!)

Liu et al. (2023) tested LLMs across long multi-document contexts and uncovered a striking U-shaped accuracy curve: models remember the beginning and end far better than the middle!

Lost in the Middle (Liu et al., 2023): Where You Place Facts Matters!Primacy (~92%)Middle Valley (~55% recall!)Recency (~88%)Position of Relevant Fact Inside Prompt (Start → Middle → End)
Empirical 'Lost in the Middle' U-curve: LLMs recall facts placed at the very start (primacy) or very end (recency) far more accurately than facts buried in the middle of long prompts!

Practical Fix: Bookend Ordering

When packing 6 retrieved RAG chunks ranked [#1, #2, #3, #4, #5, #6], placing #1 first and #2 last (e.g., [#1, #3, #5, #6, #4, #2]) puts your two strongest evidence chunks right in the primacy and recency zones — boosting grounded QA accuracy with zero extra tokens!

3. Input vs. Output Cost Asymmetry & Prompt Caching

Everyday Story First (Zero Math Yet!)

Why do almost all LLM providers charge 3–5× more per output token than per input token? Because input tokens run in one parallel matrix multiply (Prefill), while every output token reloads the entire 70B-parameter model from GPU memory!

Why Output Tokens Cost 3–5× More Than Input TokensInput Tokens (Parallel Prefill)1 Batched Matrix Multiply (GEMM)Saturates GPU Tensor Cores cleanlyCheap + Prompt-Cacheable (90% off!)Output Tokens (Sequential Decode)Reloads ALL Weights Every Single Token!Memory-bandwidth bottlenecked3× to 5× Higher API Price
Output tokens typically cost 3–5× more than input tokens because Prefill runs in parallel while Decode is memory-bandwidth bound one token at a time.

Exact Request Cost Formula

Cost=Tin,uncached⋅Pin+Tin,cached⋅Pcache+Tout⋅Pout106\text{Cost} = \frac{T_{\text{in,uncached}} \cdot P_{\text{in}} + T_{\text{in,cached}} \cdot P_{\text{cache}} + T_{\text{out}} \cdot P_{\text{out}}}{10^6}

  • Prompt Caching Golden Rule: Place static System Instructions, few-shot examples, and long shared documents at the exact start of the prompt. Never inject a live current_time or request_id at line 1!
Formula Anatomy · Click Any Colored Piece to Decode It
Anatomy of Available Context Budget

B_avail = L_max − (T_sys + T_query + R_out)

Model Context Limit

Hard token ceiling (or your stricter latency/cost cap, e.g., 16K).

In our example: 16,384 tok cap
Put it together with real numbers: With L_max = 4,096, T_sys = 400, T_query = 200, R_out = 1,000, your RAG + History budget is exactly 2,496 tokens!
Walk Through With Me · Interactive Worked Example

Worked Example: Packing Priority Chunks Under a Strict Budget

Available budget B = 1,500 tokens. Candidate chunks (sorted by relevance): C1 (600), C2 (700), C3 (500), C4 (200).

11. Pack C1 (600) and C2 (700)Step 1 / 2

Used = 600 + 700 = 1,300 ≤ 1,500 → remaining 200.

Teacher's Note: Both top-2 chunks fit cleanly!
Pause & Check · Quick Intuition Pulse

Why are output (decode) tokens priced 3–5× higher than input (prefill) tokens?

Try It YourselfStandard

Why does placing Current timestamp: 2026-12-03 12:04:19 on Line 1 of a 5,000-token System Prompt destroy Prompt Caching?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Almost never for high-traffic apps! Dumping 200K tokens on every query drives up TTFT latency (5–15 seconds), increases cost, and suffers from distraction/Lost-in-the-Middle. Use RAG to retrieve the sharpest 5–15K tokens, and use long context for deep single-document synthesis!

Interactive Visual Lab
Lab Challenge: Adjust RAG chunk count and output token length in the Context Budget Studio below to see how input vs. output tokens drive cost per 1,000 API calls!
Interactive Animation • 1.2 Deep Lab

Context Window Packing & Input/Output Cost Estimator

Dial retrieved RAG chunks and output length to inspect live context-window utilization and API cost per 1,000 requests.

Input (Prefill)
4,400 tok
Output (Decode)
800 tok
Est. Cost / 1K Calls
$19.00
0%
Total: 5,200 tok
Intuition Takeaway: Reserve System + Query + Output tokens first, pack top-relevance chunks greedily with bookend ordering to beat Lost-in-the-Middle, and keep static prompt prefixes immutable to unlock 90% Prompt Cache savings.
Where This Powers Real ML, Deep Learning & Generative AI

Enterprise RAG Chatbots

Strict token budget packers prevent 400 context_length_exceeded crashes in production.

Agentic Coding Assistants

Prefix Prompt Caching keeps repository maps & system rules cached across 50+ tool-call turns at 90% lower cost.

Multi-Document Legal / Financial QA

Bookend chunk ordering mitigates Lost-in-the-Middle recall drops.

Production NumPy & PyTorch Code Patterns
# Deterministic Priority-Ordered Context Window Packer
def pack_context_window(
    chunks: list[dict],   # [{"id": "c1", "text": "...", "tokens": 450, "score": 0.92}, ...]
    max_tokens: int,
    reserved_tokens: int,
) -> list[dict]:
    budget = max(0, max_tokens - reserved_tokens)
    ordered = sorted(chunks, key=lambda c: (-c["score"], c["id"]))
    selected, used = [], 0
    for ch in ordered:
        if used + ch["tokens"] <= budget:
            selected.append(ch)
            used += ch["tokens"]
    return selected
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting to subtract max_output_tokens before packing input chunks.
Best Practice: Always reserve output headroom first, otherwise the API either errors or truncates the answer mid-JSON!
Trap #2: Breaking Prompt Caching by putting dynamic user IDs or timestamps at the start of the System Prompt.
Best Practice: Keep static instructions/tools/docs byte-identical at the prefix; append dynamic fields at the end.
Chapter Mastery Check (+75 XP)
Score: 0 / 5
1Where should dynamic per-request variables (like timestamps or user queries) be placed to preserve Prompt Caching?
2What does the 'Lost in the Middle' phenomenon describe?
3A model has L_max = 8,000, T_sys = 500, T_query = 300, and max_output_tokens = 1,200. How many tokens remain for RAG + history?
4Why do output tokens typically cost 3–5× more than input tokens?
5Which items should NEVER be truncated by a Context Window Packer?

Apply What You Learned — Solve Matching Coding Problems