Reference · Context Engineering

Context engineering — one-page cheat sheet

Context engineeringSemantic searchRetrieval augmented generationContext windowWorking memory

Published

For the principal chair · print me · pairs with Lesson 1 & the glossary
The one sentence: the model is the constant, context is the variable — what you retrieve and assemble into a fixed window decides how smart the system looks, not which LLM you bought.

The spine (mental models)

  1. Context = the new database query — retrieval/assembly plays SQL’s role: it decides what the model ever sees.
  2. The window is RAM — a fixed token budget you allocate, not a pipe to your data. Bigger ≠ solved.
  3. Selection → retrieval → rerank — turn a huge corpus into the curated few that fit.
  4. Recall first, precision second — first stage casts wide (don’t miss it); rerank surfaces the best.
  5. Chunk on meaning + overlap — split on structure; overlap so boundary facts survive.
  6. RAG = retrieval + assembly + LLM — ground the answer in fetched facts, not frozen weights.
  7. Memory vs knowledge base — memory = what I learned from us; KB = what’s true in general.
  8. Compress for long runs — summarize the old, keep the recent & the IDs verbatim.
  9. Match retrieval to the data type — exact→structured, fuzzy→hybrid, volatile→live, long→compress.
  10. Most AI bugs are context bugs — suspect the input before blaming the model.

What competes for the window

System promptInstructions — fixed overhead, paid every call.
Tool defsFunction schemas — grows with #tools.
HistoryConversation — grows every turn (silent eater).
RetrievedDocs/code/facts for THIS turn — the part you engineer.
QuestionThe user’s actual query.
AnswerReserved room the output needs too.

The two diagrams

AI PIPELINE            CLASSIC SOFTWARE
Question               Request
↓        same role     ↓
Retrieval  ◀───────▶   SQL query   (the new query)
↓                      ↓
Assembly (pack window) DB  source of truth
↓                      ↓
LLM   fixed/commodity  Response
↓
Answer
the LLM only ever sees what Retrieval surfaced
TWO-STAGE RETRIEVAL — recall first, precision second
query
│
▼  STAGE 1 · cheap · wide  (optimize RECALL)
┌──────────────┬──────────────┐
│ Lexical/BM25 │ Vector/embed │
│ exact terms  │ meaning      │
└──────┬───────┴──────┬───────┘
└──▶ fuse (RRF) ◀──┘  one candidate list
│
▼  STAGE 2 · expensive · top-N (PRECISION)
cross-encoder rerank
│
▼
top-k → window
stage 2 cannot recover what stage 1 missed

Chunking rules

  1. Split on structure (function/class/heading bounds), not character count.
  2. Add overlap so a fact spanning a boundary survives whole in one chunk.
  3. Beware fragmentation — a split fact lives in neither chunk and is unretrievable.
  4. Contextual chunking — prepend a short doc/section summary so each chunk self-describes.
  5. Each chunk must be complete (answers alone) and retrievable (matches its questions).

Retrieval techniques

TechniqueGood atWeaknessFailure mode
Lexical / BM25Exact terms, identifiers, error codes, IDsNo synonyms / semanticsVocabulary mismatch → total miss
Semantic / embeddingsMeaning, synonyms, paraphraseMisses rare exact tokens (IDs, fn names)Plausible-but-wrong; topically similar
HybridExact and meaning together (fuse via RRF)More infra; fusion weights to tuneBounded by both stages’ recall
Re-rankOrdering the final top-k (cross-encoder)Latency & cost; top-N onlyCan’t recover a missed document

The five failure modes

ModeSymptomRoot causeFix
Missing”I don’t know” / hallucinated fillerRecall gap; not in KB; chunking fragmented itImprove recall (hybrid), better chunking, add source
WrongConfident but off-topic / incorrectEmbedding “similar-but-wrong”; no rerankRerank, metadata filters, hybrid + exact match
OutdatedOld price / old API answerIndex not refreshed; cached docFreshness/invalidation, re-index, live fetch
ConflictingContradictory / arbitrary answerDuplicates/versions; no source-of-truth precedenceDedupe, rank by authority/recency, pass provenance
ExcessiveSlower, costlier; key fact ignoredDump-everything; no selectionSelect less but right; cite position bias (lost in middle)

Context compression (long runs)

MoveWhat + when
SummarizationCondense old history. Lossy. History too long to carry verbatim.
DistillationExtract facts/decisions/state, drop narrative. Lossy. Want conclusions, not chatter.
CompressionDedupe/prune boilerplate. Near-lossless. Content is repetitive.
Sliding windowLast N turns verbatim + rolling summary of older. The default for long agents.

Lossy warning: a dropped ID/constraint can be the one that matters later. Compress the OLD; keep recent + decisions/IDs verbatim; store the full transcript and retrieve on demand. Compress as you approach the budget, not pre-emptively.

Match retrieval to data type

DataRetrieval
Exact / financialDeterministic structured query (SQL keyed by id) — never fuzzy embeddings; never invent amounts.
Fuzzy / textualHybrid + rerank over the KB; cite sources back.
VolatileFetch live — freshness/invalidation; don’t trust a stale index.
Long-runningCompress + remember — summarize old, keep recent verbatim.

Vector search returns the most similar, not the correct. For an invoice total you need a deterministic lookup. Log the assembled context per call — a wrong answer is undebuggable otherwise.

Retrieval evaluation L6

Retrieval metricAsks
recall@kMost important — is ≥1 relevant doc in top-k? Nothing downstream can use what wasn’t retrieved.
precision@kWhat fraction of top-k is actually relevant? Junk crowds the window.
MRRHow high the first relevant hit sits (one good hit is enough).
nDCGGraded, position-discounted — judges the reranker’s ordering.
Answer quality (RAGAS)Asks
FaithfulnessIs every claim grounded in the retrieved context? (catches hallucination)
Answer relevanceDoes it address the question? (catches off-topic)
Context precisionAre retrieved chunks relevant and well-ranked?
Context recallDid retrieval capture all the ideal answer needs? (needs ground truth)
  1. Measure retrieval separately from generation — faithful-but-wrong = retrieval bug; hallucination over good context = generation bug; don’t fix the wrong half.
  2. Golden set + offline regression (CI, gates deploys) + online signals (thumbs · deflection · citation-clicks · rephrase rate); curate new misses back into the golden set.
  3. Trace every call — query · retrieved IDs+scores · packed chunks · answer — turns “the bot was wrong” into “doc X wasn’t retrieved.” LLM-as-judge scales grading but must be calibrated vs human labels.

Pre-retrieval & advanced RAG L7

The raw query is a bad search query — fix it before the index (recall no reranker can recover); flat top-k is a floor, not a ceiling.

Query transformProblem it solves
RewritingVague / pronoun-laden / misspelled input — clean, expand, disambiguate.
Multi-queryOne phrasing misses — N paraphrases, retrieve each, union & dedupe → recall.
HyDEQuestions look unlike answers — embed a drafted hypothetical answer to bridge the vocab gap.
DecompositionMulti-part question no single chunk answers — split into sub-queries, combine.
Step-backToo specific to find grounding — ask a broader question first.
RoutingWrong datasource — classify and send to docs vs code vs SQL.
  1. Parent-doc / small-to-big — match the small precise chunk, return the larger parent for context.
  2. Hierarchical — retrieve over summaries, then drill into details (large docs).
  3. Contextual retrieval — prepend chunk-situating context + add BM25 alongside vectors.
  4. ColBERT / multi-vector — token-level late interaction → higher precision (costly).
  5. GraphRAG — subgraphs + community summaries for global “connect-the-dots across the corpus” themes; overkill for local facts.
  6. Agentic RAG / Self-RAG / CRAG — retrieval becomes an action in a loop: decide-to-retrieve, grade docs, re-retrieve / web-fallback, critique the draft. Buys quality; pays in latency, cost, complexity.

Embeddings, indexing & cost L8

  1. The lens = embedding model + dimensions + similarity metric (cosine = angle, ignores magnitude; normalize first).
  2. Chunk granularity drives embedding quality — a vector is the average of its text; too big → blurry centroid, too small → lost context.
  3. Changing the embedding model = re-index the world — old/new vectors live in different spaces, incomparable; a full migration, not a config flip.
ANN indexStrengthCost
HNSW (graph)Fast, high recallMemory-heavy; slow build
IVF (cluster)Tunable speed via #probesRecall dips if neighbor in un-probed cell
PQ (compress)Big memory savingsLossy → lower recall (pair as IVF+PQ)
Flat (brute)Perfect recall, zero buildO(n)/query — small corpora only

Pick a corner: recall ↔ latency ↔ memory can’t all max. ANN gives up a few % recall for sub-linear speed; a reranker cleans the top.

Cost leverWhy
Fewer / better chunksTokens are the bill; noise also lowers accuracy.
Rerank only top-nCross-encoder on candidates, not all.
Cheaper embed modelLower query + corpus embed price.
Prompt cachingStop reprocessing the stable prefix (L9).
Batch embeddingCorpus embed offline, avoid needless re-embeds.

Caching, ordering & security L9

Prompt cachePlacement
System promptStable → first — byte-identical every call.
Tool defsStable → in prefix — changes only on deploy.
Few-shotsStable → in prefix — reused across calls.
Retrieved docsVolatile → after prefix — can’t cache.
User queryVolatile → last — new every call.

Cache key = exact identical prefix; one changed token busts it from there down. Lost in the middle: attention is U-shaped — put the query last (recency, also cache-friendly) and the best doc at an edge; never bury key evidence mid-window.

  1. Retrieved content is untrusted data, not instructions — indirect prompt injection rides in through your own KB; delimit it as data, filter outputs, constrain tool egress (OWASP LLM #1).
  2. Multi-tenant access control belongs in the retrieval query — filter by tenant_id/ACL at the index, never in the prompt; the prompt is not a security boundary.
  3. PII / sensitive-info disclosure — redaction, retention/residency limits, least-privilege retrieval.

5-minute revision (the whole spine)

  1. Say the one sentence: model = constant, context = variable; right context + smaller model often beats wrong context + flagship.
  2. Name the window tenants: prompt · tools · history · retrieved · question · answer — all compete for one fixed budget.
  3. Draw the inversion: context retrieval is the new SQL query; the bug is silent — fluent and confidently wrong.
  4. Selection funnel: candidate generation (recall) → ranking → pack to budget; you can’t pack what you never retrieved.
  5. Engines: lexical=exact, semantic=meaning, hybrid=both, rerank=precision at the top.
  6. Chunk on meaning + overlap + contextual summary; chunk grain is the retrieval grain.
  7. RAG = retrieve + assemble + LLM; most “the LLM is dumb” bugs are retrieval bugs — fix recall before model.
  8. Memory (system-written, per-user) ≠ knowledge base (external, read-only); both reach the model only via retrieval.
  9. Long runs: store the transcript, compress the old, keep recent + IDs verbatim.
  10. Classify any bad answer: missing / wrong / outdated / conflicting / excessive — then the fix is obvious.
  11. Production reflex: name the strategy (pre-index · read-on-demand · none) → you’ve named its failure mode → match retrieval to the data type.
  12. Eval (L6): grade retrieval and generation separately — recall@k first, then RAGAS (faithfulness · relevance · context precision/recall); golden set offline + signals online; trace every call.
  13. Pre-retrieval (L7): the query is not the question — rewrite · multi-query · HyDE · decompose · step-back · route; fix the query before the index, recall no reranker can recover.
  14. Advanced RAG (L7): flat top-k is a floor — small-to-big · hierarchical · contextual · ColBERT · GraphRAG (global themes); agentic/Self-RAG/CRAG loop buys quality, pays latency+cost.
  15. Embeddings & cost (L8): model+dims+metric+chunk = the lens; change the model → re-index the world; ANN (HNSW/IVF/PQ/Flat) trades recall↔latency↔memory; tokens are the bill.
  16. Production layer (L9): stable-first/volatile-last for cache; query last + best doc at an edge for “lost in the middle”; retrieved text is data not instructions; ACL in the query, not the prompt.