← Back to Blog

Section 2: Grounding AI with RAG and Context Engineering

Even the sharpest prompt will fail if the context window is flooded with stale, irrelevant, or contradictory text. Learn how to engineer retrieval pipelines that ground models in verified, up-to-date evidence.

2.1 Context Engineering vs. Prompt Engineering

Prompt engineering focuses on how you phrase instructions. Context engineering is the broader discipline of deliberately selecting, structuring, filtering, and managing every token inside the model's context window—system instructions, few-shot examples, conversation state, tool definitions, and retrieved facts.

2.2 Retrieval-Augmented Generation (RAG) Architecture

RAG grounds an LLM in external, up-to-date knowledge by fetching relevant passages at query time and injecting them into the prompt. A production RAG system splits cleanly into an offline ingestion pipeline and an online query-time pipeline.

Dual-lane RAG pipeline showing offline ingestion and online hybrid retrieval
Figure 2: Dual-lane RAG pipeline illustrating offline document ingestion and online hybrid retrieval with reranking.

2.3 Core Retrieval Design Choices

  • Parsing & Chunking: Cleanly parsing PDFs, HTML, and Markdown while preserving tables and headings is often the highest-leverage step. Small chunks (200–400 tokens) sharpen search precision; larger chunks (800–1,200 tokens) preserve context at higher token cost. Structure-aware chunking (splitting by headings with modest overlap) outperforms naive character splits.
  • Embeddings & Hybrid Retrieval: Dense vector embeddings capture semantic meaning ("reset credentials" matches "rotate API keys"), while lexical/keyword search (BM25) excels at exact identifiers like error codes (ERR_4092) or SKUs. Hybrid retrieval combines both via Reciprocal Rank Fusion (RRF).
  • Metadata Filters & Access Control: Attach metadata (source, timestamp, team, ACL) at ingestion. Always filter by user permissions before retrieval so unauthorized documents never enter the prompt.
  • Reranking, Citations, and Freshness: Retrieve a wider candidate set (top 30), then apply a cross-encoder reranker to keep the top 5–8. Require inline citations referencing chunk IDs, and wire incremental re-indexing webhooks so edits and deletions propagate quickly.

2.4 Advanced RAG Patterns

  • Query Rewriting & Multi-Query Retrieval: Rewrite ambiguous follow-ups ("How do I rotate it?") into standalone queries, or generate 2–3 phrasing variants to broaden recall.
  • Parent-Child Retrieval: Index small child chunks for sharp vector matching, but pass their larger parent section to the LLM for complete context.
  • Contextual Compression & Iterative Retrieval: Extract only query-relevant sentences to save tokens, or allow an agent to issue a second retrieval query if initial evidence is insufficient.
  • Graph-Based Retrieval & Source Routing: Use knowledge graphs for multi-hop relational questions, and use a lightweight router to direct queries to the right corpus (SQL database vs. wiki vs. ticket tracker).

2.5 Common Failure Modes & Separate Evaluation

Rule: Measure Retrieval and Generation Separately

  • Retrieval Failures (Fix Ingestion/Search): Missing or stale sources, broken chunk boundaries, vocabulary mismatch, or irrelevant top-K chunks. Measure with Recall@K, MRR, and NDCG.
  • Generation Failures (Fix Prompt/Model): The right chunk was retrieved, yet the model ignored it, blended conflicting docs without flagging the conflict, or fabricated a citation. Measure with Faithfulness, Citation Precision, and Abstention Accuracy.