Context Engineering: Managing What the Model Sees
When systems work in short demos but degrade as conversations lengthen, teams blame 'the model getting dumber'—the true culprit is context window pollution. Layer 2 is the craft of managing what the model sees: token budgeting, just-in-time retrieval, scheduled turn compaction, and working scratchpads.
The “Model Getting Dumber” Fallacy
Every engineering team building multi-turn LLM features encounters the same baffling bug: an assistant answers flawlessly on Turn 1 in a unit test, but by Turn 7 in a live user session, it begins hallucinating facts, repeating itself, or violating strict formatting instructions.
Teams almost universally misdiagnose this failure. They claim “the model got dumber as the chat went on” and attempt to fix it by writing longer system prompts or switching model providers. In reality, language models have no internal fatigue or stateful memory. The degradation is caused 100% by what information was or was not assembled in the context window at the exact moment of inference.
Context Engineering is everything assembled around a single instruction before it is dispatched to the model: system directives, retrieved knowledge chunks, tool calling schemas, pruned conversation turns, and working memory scratchpads. It is an attention-management and curation problem, not a writing problem.
Why Bigger Context Windows Don’t Remove the Need to Curate
With frontier models offering 128k to 2M token context windows, many teams assume context management is obsolete: “Why bother chunking or filtering when we can dump all 300 pages into the prompt?”
This assumption creates severe production failures. Dumping raw material into a context window is never free:
Transformer self-attention distributes finite attention weights across all tokens. Irrelevant noise actively obscures critical facts.
Time-to-first-token (TTFT) scales with prompt token length. Processing 100k unneeded tokens adds seconds of user-facing lag.
Passing 50,000 unneeded tokens across 10 turns bills 500,000 input tokens for a simple $0.001 question.
The 5-Part Context Payload & Deterministic Eviction Hierarchy
The 6-Stage Dynamic RAG Pipeline
Delivering high-precision facts without cluttering the window requires a deterministic 6-stage assembly pipeline:
The 6-Stage Dynamic RAG & Context Pipeline
Context Window Budgeting & Attention Curves
To prevent context starvation, set an explicit token budget partitioned across four distinct reserves:
Context Window Partitioning & The “Lost in the Middle” Curve
Interactive 5-Tier Eviction Priority Inspector
When total tokens exceed your budget ceiling, what gets cut first? Click each tier to inspect the deterministic eviction hierarchy and safety guardrails:
Tier 1: Raw API & Tool Responses
Action: EVICT_FIRSTRaw JSON database dumps, full HTML scraping outputs, and verbose HTTP payloads from previous turns.
The 4 Concrete Context Craft Moves
To build resilient multi-turn applications, master these four foundational context engineering moves:
Just-in-Time Context Assembly
The Rule: Never front-load documents or customer history at session start. Query and assemble context dynamically on each conversational turn based on active user intent.
Explicit Budgeting & Eviction Priority
The Rule: Define an explicit token ceiling for each partition (System, RAG, History, Output). When total tokens exceed budget, execute deterministic eviction in prioritized order.
Scheduled Compaction & Summarization
The Rule: Do not let multi-turn conversation logs grow unbounded. After every 4 turns or when history exceeds 2,000 tokens, trigger background LLM compaction into an immutable summary card.
Working Scratchpad & Ephemeral State
The Rule: Separate intermediate reasoning state from permanent dialogue logs. Use a dedicated structured JSON scratchpad that updates across turns and is cleared upon task resolution.
Interactive Scratchpad State Simulator
See how a structured working scratchpad carries intermediate reasoning across three turns of the Customer Refund Assistant without bloating the permanent conversation log:
{
"orderId": "88412",
"itemSku": "HEADSET-PRO-BT",
"price": 42.50,
"purchaseDaysAgo": 12,
"policy30DaysMet": true,
"conditionVerified": null,
"readyForRefund": false
}Permanent Dialogue Log vs. Ephemeral Working Scratchpad
3 Recognizable Symptoms of Layer 2 Failures
When debugging unexpected model behavior, use this checklist to differentiate context failures from prompt defects:
Symptom 1: Long-Session Quality Collapse
Observable Symptom: The model gives crisp, accurate answers on Turns 1–3, but becomes evasive, repetitive, or contradictory by Turn 7.
Symptom 2: Overlooked Injected Facts
Observable Symptom: The customer order ID or return policy clause was explicitly injected in the prompt, but the model still claims it does not know or hallucinates a generic answer.
Symptom 3: Runaway Token Cost & Latency Inflation
Observable Symptom: API billing and time-to-first-token (TTFT) latency climb exponentially with each conversation turn without any improvement in response quality.
Refund Assistant: Layer 2 in Action
In Topic 01, our prompt-only assistant failed because it hallucinated order details it had never seen. With Layer 2 in place, when Sarah Connor messages: “Can you refund order #88412? I bought it last Tuesday,” the Context Engine executes three parallel lookups:
1. Alphanumeric SQL Query (Order Database)
Executes parameterized lookup for order 88412 linked to authenticated customer cust_9921, pulling item SKU, price ($42.50), purchase date (12 days ago), and return eligibility.
2. Semantic RAG Search (Acme Return Policy Manual)
Searches store policy embeddings for “headphones electronics return window”, retrieving the 30-day undamaged goods clause and $50 automated authorization threshold.
3. Sliding-Window Session Memory
Includes the previous 2 messages where Sarah verified her email and stated that the headset arrived in an unopened box.
Boundary with Trust & Retrieval Engineering
Context Curation vs. Vector Indexing Mechanics
This topic focuses on the runtime discipline of context curation and attention budgeting inside the active window. The deep mathematical mechanics of enterprise document chunking, sparse BM25 inverted indexes, vector embedding benchmarks, and hybrid reranking architectures are comprehensively covered in the Trust & Retrieval Engineering category:
Explore Trust & Retrieval Engineering (RAG Systems Sub-Track)The Next Boundary: Context Ingestion ≠ Execution Authority
When Sarah says “Awesome, please process that refund now,” the model cannot simply generate text saying “I have refunded $42.50.” Language models must not execute banking APIs directly via natural language. To safely intercept tool calls, validate payloads with Zod schemas, and enforce $50 hard authorization limits, we must step into Layer 3: Harness Engineering.
Copy this prompt to architect your production context budgeting, eviction hierarchy, and working scratchpad memory.
Community Discussion & Feedback
Attributed peer feedback and official Netspective architecture notes.