RAG Pipeline Architect
Design production-grade RAG pipelines from document ingestion to
retrieval-augmented response generation, with systematic evaluation
and optimization at every stage.
When to Use
- Designing a new RAG system from scratch
- Diagnosing "the LLM doesn't use my documents" problems
- Choosing between chunking strategies, embedding models, or vector databases
- Optimizing retrieval quality (precision, recall, relevance)
- Migrating from naive RAG to advanced RAG patterns
- Building evaluation harnesses for retrieval quality
RAG Architecture Tiers
Tier 1: Naive RAG
The simplest end-to-end pipeline. Good for prototyping.
Documents → Chunk → Embed → Store → Query → Retrieve → Generate
Pros: Fast to build, easy to understand
Cons: Poor handling of complex queries, no re-ranking, chunk boundary issues
Tier 2: Advanced RAG
Adds pre-retrieval and post-retrieval optimization stages.
Documents → Clean → Chunk (smart) → Embed → Store
↓
Query → Rewrite → Embed → Retrieve → Re-rank → Filter → Generate
↑ ↓
└──────────── Self-reflection / Retry ──────────────────┘
Key additions:
- Query rewriting and expansion
- Hybrid search (dense + sparse)
- Re-ranking with cross-encoders
- Self-reflection loop for answer validation
Tier 3: Modular RAG
Fully composable pipeline with pluggable components.
┌─── Ingestion Pipeline ────────────────────────────┐
│ Source Connectors → Parsing → Cleaning → │
│ Chunking → Enrichment → Embedding → Indexing │
└────────────────────────────────────────────────────┘
┌─── Query Pipeline ────────────────────────────────┐
│ Query Analysis → Intent Classification → │
│ Query Routing → Retrieval Strategy Selection → │
│ Multi-source Retrieval → Fusion → Re-ranking → │
│ Context Assembly → Generation → Validation │
└────────────────────────────────────────────────────┘
Workflow
Phase 1: Document Analysis & Ingestion Design
Audit the corpus:
- Document types (PDF, HTML, Markdown, code, tables, images)
- Total size and document count
- Update frequency (static vs. streaming)
- Language distribution
- Structural complexity (headings, tables, nested lists, code blocks)
Choose a parsing strategy:
| Document Type |
Recommended Parser |
Notes |
| PDF (text) |
PyMuPDF / pdfplumber |
Preserves layout and tables |
| PDF (scanned) |
Tesseract + layout detection |
Add OCR preprocessing |
| HTML |
BeautifulSoup + Readability |
Strip boilerplate first |
| Markdown |
Native parsing |
Preserve heading hierarchy |
| Code files |
Tree-sitter |
Parse by function/class boundaries |
| Spreadsheets |
pandas |
Convert to structured text with headers |
| Images/diagrams |
Vision LLM (GPT-4V, Claude) |
Generate text descriptions |
Design the cleaning pipeline:
- Remove boilerplate (headers, footers, navigation)
- Normalize whitespace and encoding
- Extract and preserve metadata (title, author, date, source URL)
- Handle special characters and formatting artifacts
Phase 2: Chunking Strategy
Choose the chunking approach based on document structure:
| Strategy |
Best For |
Chunk Size |
Overlap |
| Fixed-size |
Homogeneous text (articles, books) |
512-1024 tokens |
10-20% |
| Recursive character |
General purpose |
500-1000 tokens |
50-200 tokens |
| Semantic |
Mixed-content documents |
Variable |
Natural boundaries |
| Document-structure |
Technical docs with headings |
Section-based |
Include parent heading |
| Code-aware |
Source code |
Function/class-level |
Include imports/context |
| Sentence-window |
High-precision retrieval |
1-3 sentences |
±2 sentences as context |
| Parent-child |
Hierarchical documents |
Small child, large parent |
Child retrieves, parent provides context |
Chunking decision tree:
Is the document well-structured (headings, sections)?
├── Yes → Document-structure chunking
│ + Parent-child indexing for hierarchy
├── No → Is it source code?
│ ├── Yes → Code-aware chunking (tree-sitter)
│ └── No → Is high precision critical?
│ ├── Yes → Sentence-window chunking
│ └── No → Recursive character chunking
Critical rules:
- Always include metadata in chunks (source, page, section title)
- Never break mid-sentence or mid-code-block
- Test chunk quality by reading 20 random chunks — each should be self-contained and meaningful
Phase 3: Embedding & Indexing
Choose embedding model:
| Model |
Dimensions |
Max Tokens |
Strengths |
| OpenAI text-embedding-3-large |
3072 |
8191 |
Best general quality |
| OpenAI text-embedding-3-small |
1536 |
8191 |
Cost-effective |
| Cohere embed-v4 |
1024 |
512 |
Multilingual excellence |
| Voyage AI voyage-3-large |
1024 |
32000 |
Long-context, code |
| BGE-M3 (open source) |
1024 |
8192 |
Multilingual, free |
| Jina embeddings-v3 |
1024 |
8192 |
Multilingual, open |
| GTE-Qwen2 (open source) |
1024 |
8192 |
Chinese + English, free |
Choose vector database:
| Database |
Type |
Best For |
Scale |
| Pinecone |
Managed |
Production, zero-ops |
Billions |
| Weaviate |
Managed/Self |
Hybrid search, multi-modal |
Millions-Billions |
| Qdrant |
Self-hosted |
Performance, filtering |
Millions |
| ChromaDB |
Embedded |
Prototyping, local dev |
Thousands-Millions |
| pgvector |
Postgres extension |
Existing Postgres stack |
Millions |
| FAISS |
In-memory library |
Research, benchmarking |
Millions |
| Milvus |
Distributed |
Large-scale production |
Billions |
Indexing best practices:
- Store both the embedding vector AND the original text
- Include rich metadata for filtering (source, date, category, language)
- Build separate indexes for different document types if needed
- Implement incremental indexing for updates (don't re-index everything)
Phase 4: Retrieval Strategy
Design the query-time retrieval pipeline:
Query preprocessing:
- Detect query intent (factual, analytical, procedural, conversational)
- Expand query with synonyms or related terms (query expansion)
- Rewrite ambiguous queries using the LLM (HyDE: Hypothetical Document Embeddings)
- Decompose complex queries into sub-queries
Retrieval methods (choose one or combine):
| Method |
How It Works |
When to Use |
| Dense retrieval |
Embedding similarity (cosine/dot product) |
Semantic meaning matches |
| Sparse retrieval |
BM25 / TF-IDF keyword matching |
Exact term matches, names, codes |
| Hybrid |
Dense + Sparse with score fusion |
Best overall quality |
| Multi-query |
Generate N query variants, retrieve for each, merge |
Complex or ambiguous queries |
| Parent-child |
Retrieve small chunks, return parent chunks |
Need both precision and context |
Re-ranking:
- Apply a cross-encoder re-ranker (e.g., Cohere Rerank, BGE-Reranker)
- Re-ranking is the single highest-impact improvement for most RAG systems
- Retrieve more candidates than needed (e.g., top-20), re-rank to top-5
Post-retrieval filtering:
- Remove chunks below a relevance score threshold
- Deduplicate near-identical chunks
- Ensure diversity (don't return 5 chunks from the same page)
- Respect recency requirements (filter by date if needed)
Phase 5: Context Assembly & Generation
Assemble the context:
- Order chunks by relevance (most relevant first AND last — avoid "lost in the middle")
- Include source attribution metadata
- Add a preamble: "Answer based ONLY on the following context. If the context
doesn't contain the answer, say so."
Generation prompt template:
You are a [domain] expert. Answer the user's question based on the
provided context.
## Rules
- Only use information from the provided context
- Cite sources using [Source: document_name, page X]
- If the context is insufficient, explicitly state what's missing
- Never fabricate information
## Context
{retrieved_chunks_with_metadata}
## Question
{user_query}
## Answer
Response validation:
- Check for hallucination: Does every claim have a supporting chunk?
- Check for completeness: Did the response address all parts of the query?
- Check for citation accuracy: Do citations point to the right chunks?
Phase 6: Evaluation
Evaluate the RAG pipeline at two levels:
Retrieval evaluation:
| Metric |
What It Measures |
Target |
| Recall@K |
% of relevant docs in top-K results |
> 0.85 |
| Precision@K |
% of top-K results that are relevant |
> 0.70 |
| MRR (Mean Reciprocal Rank) |
How high the first relevant result ranks |
> 0.80 |
| NDCG |
Quality of the ranking order |
> 0.75 |
End-to-end evaluation:
| Metric |
What It Measures |
Method |
| Faithfulness |
Does the answer stick to the context? |
LLM-as-judge |
| Relevance |
Does the answer address the question? |
LLM-as-judge |
| Completeness |
Are all aspects of the question covered? |
Human eval + LLM |
| Citation accuracy |
Do citations match the claims? |
Automated check |
Build an eval dataset:
- Minimum 50 question-answer pairs with annotated relevant documents
- Include: easy factual, multi-hop reasoning, unanswerable, and adversarial queries
- Version control the eval set and never train/tune on it
Common Failure Modes & Fixes
| Symptom |
Root Cause |
Fix |
| Answers are generic, don't use context |
Weak retrieval, chunks not relevant |
Improve chunking, add re-ranker |
| Answers hallucinate facts |
Context insufficient, no guardrails |
Add "only use context" constraint, validate |
| Answers are correct but miss details |
Chunks too small, key info split |
Increase chunk size or use parent-child |
| Wrong documents retrieved |
Query-document vocabulary mismatch |
Add hybrid search, query expansion |
| Good retrieval but bad answers |
Poor prompt engineering |
Improve generation prompt, add examples |
| Slow response times |
Too many chunks, large context |
Reduce top-K, use faster embedding model |
| Inconsistent quality |
No evaluation framework |
Build eval harness, monitor metrics |
Guidelines
- Start simple, iterate: Begin with Tier 1 (naive RAG), measure, then add
complexity only where metrics show gaps.
- Re-ranking is the best single upgrade: If you do one thing to improve quality,
add a cross-encoder re-ranker.
- Chunk quality > chunk quantity: 5 excellent chunks beat 20 mediocre ones.
- Always evaluate: Without metrics, you're guessing. Build the eval harness
before optimizing.
- Version everything: Embedding models, chunk strategies, and prompts should
all be versioned and traceable.
1---2name: rag-pipeline-architect3description: Design, build, and optimize Retrieval-Augmented Generation (RAG) pipelines from scratch. Use this skill when building a RAG system, diagnosing retrieval quality issues, choosing embedding models, designing chunking strategies, or optimizing the end-to-end pipeline for accuracy and latency. Covers naive RAG, advanced RAG, and modular RAG architectures.4license: MIT5---67# RAG Pipeline Architect89Design production-grade RAG pipelines from document ingestion to10retrieval-augmented response generation, with systematic evaluation11and optimization at every stage.1213## When to Use1415- Designing a new RAG system from scratch16- Diagnosing "the LLM doesn't use my documents" problems17- Choosing between chunking strategies, embedding models, or vector databases18- Optimizing retrieval quality (precision, recall, relevance)19- Migrating from naive RAG to advanced RAG patterns20- Building evaluation harnesses for retrieval quality2122## RAG Architecture Tiers2324### Tier 1: Naive RAG2526The simplest end-to-end pipeline. Good for prototyping.2728```29Documents → Chunk → Embed → Store → Query → Retrieve → Generate30```3132**Pros**: Fast to build, easy to understand33**Cons**: Poor handling of complex queries, no re-ranking, chunk boundary issues3435### Tier 2: Advanced RAG3637Adds pre-retrieval and post-retrieval optimization stages.3839```40Documents → Clean → Chunk (smart) → Embed → Store41 ↓42Query → Rewrite → Embed → Retrieve → Re-rank → Filter → Generate43 ↑ ↓44 └──────────── Self-reflection / Retry ──────────────────┘45```4647**Key additions**:48- Query rewriting and expansion49- Hybrid search (dense + sparse)50- Re-ranking with cross-encoders51- Self-reflection loop for answer validation5253### Tier 3: Modular RAG5455Fully composable pipeline with pluggable components.5657```58┌─── Ingestion Pipeline ────────────────────────────┐59│ Source Connectors → Parsing → Cleaning → │60│ Chunking → Enrichment → Embedding → Indexing │61└────────────────────────────────────────────────────┘6263┌─── Query Pipeline ────────────────────────────────┐64│ Query Analysis → Intent Classification → │65│ Query Routing → Retrieval Strategy Selection → │66│ Multi-source Retrieval → Fusion → Re-ranking → │67│ Context Assembly → Generation → Validation │68└────────────────────────────────────────────────────┘69```7071## Workflow7273### Phase 1: Document Analysis & Ingestion Design74751. **Audit the corpus**:76 - Document types (PDF, HTML, Markdown, code, tables, images)77 - Total size and document count78 - Update frequency (static vs. streaming)79 - Language distribution80 - Structural complexity (headings, tables, nested lists, code blocks)81822. **Choose a parsing strategy**:8384 | Document Type | Recommended Parser | Notes |85 |--------------|-------------------|-------|86 | PDF (text) | PyMuPDF / pdfplumber | Preserves layout and tables |87 | PDF (scanned) | Tesseract + layout detection | Add OCR preprocessing |88 | HTML | BeautifulSoup + Readability | Strip boilerplate first |89 | Markdown | Native parsing | Preserve heading hierarchy |90 | Code files | Tree-sitter | Parse by function/class boundaries |91 | Spreadsheets | pandas | Convert to structured text with headers |92 | Images/diagrams | Vision LLM (GPT-4V, Claude) | Generate text descriptions |93943. **Design the cleaning pipeline**:95 - Remove boilerplate (headers, footers, navigation)96 - Normalize whitespace and encoding97 - Extract and preserve metadata (title, author, date, source URL)98 - Handle special characters and formatting artifacts99100### Phase 2: Chunking Strategy101102Choose the chunking approach based on document structure:103104| Strategy | Best For | Chunk Size | Overlap |105|----------|----------|-----------|---------|106| **Fixed-size** | Homogeneous text (articles, books) | 512-1024 tokens | 10-20% |107| **Recursive character** | General purpose | 500-1000 tokens | 50-200 tokens |108| **Semantic** | Mixed-content documents | Variable | Natural boundaries |109| **Document-structure** | Technical docs with headings | Section-based | Include parent heading |110| **Code-aware** | Source code | Function/class-level | Include imports/context |111| **Sentence-window** | High-precision retrieval | 1-3 sentences | ±2 sentences as context |112| **Parent-child** | Hierarchical documents | Small child, large parent | Child retrieves, parent provides context |113114**Chunking decision tree**:115116```117Is the document well-structured (headings, sections)?118├── Yes → Document-structure chunking119│ + Parent-child indexing for hierarchy120├── No → Is it source code?121│ ├── Yes → Code-aware chunking (tree-sitter)122│ └── No → Is high precision critical?123│ ├── Yes → Sentence-window chunking124│ └── No → Recursive character chunking125```126127**Critical rules**:128- Always include metadata in chunks (source, page, section title)129- Never break mid-sentence or mid-code-block130- Test chunk quality by reading 20 random chunks — each should be self-contained and meaningful131132### Phase 3: Embedding & Indexing1331341. **Choose embedding model**:135136 | Model | Dimensions | Max Tokens | Strengths |137 |-------|-----------|-----------|-----------|138 | OpenAI text-embedding-3-large | 3072 | 8191 | Best general quality |139 | OpenAI text-embedding-3-small | 1536 | 8191 | Cost-effective |140 | Cohere embed-v4 | 1024 | 512 | Multilingual excellence |141 | Voyage AI voyage-3-large | 1024 | 32000 | Long-context, code |142 | BGE-M3 (open source) | 1024 | 8192 | Multilingual, free |143 | Jina embeddings-v3 | 1024 | 8192 | Multilingual, open |144 | GTE-Qwen2 (open source) | 1024 | 8192 | Chinese + English, free |1451462. **Choose vector database**:147148 | Database | Type | Best For | Scale |149 |----------|------|---------|-------|150 | Pinecone | Managed | Production, zero-ops | Billions |151 | Weaviate | Managed/Self | Hybrid search, multi-modal | Millions-Billions |152 | Qdrant | Self-hosted | Performance, filtering | Millions |153 | ChromaDB | Embedded | Prototyping, local dev | Thousands-Millions |154 | pgvector | Postgres extension | Existing Postgres stack | Millions |155 | FAISS | In-memory library | Research, benchmarking | Millions |156 | Milvus | Distributed | Large-scale production | Billions |1571583. **Indexing best practices**:159 - Store both the embedding vector AND the original text160 - Include rich metadata for filtering (source, date, category, language)161 - Build separate indexes for different document types if needed162 - Implement incremental indexing for updates (don't re-index everything)163164### Phase 4: Retrieval Strategy165166Design the query-time retrieval pipeline:1671681. **Query preprocessing**:169 - Detect query intent (factual, analytical, procedural, conversational)170 - Expand query with synonyms or related terms (query expansion)171 - Rewrite ambiguous queries using the LLM (HyDE: Hypothetical Document Embeddings)172 - Decompose complex queries into sub-queries1731742. **Retrieval methods** (choose one or combine):175176 | Method | How It Works | When to Use |177 |--------|-------------|-------------|178 | **Dense retrieval** | Embedding similarity (cosine/dot product) | Semantic meaning matches |179 | **Sparse retrieval** | BM25 / TF-IDF keyword matching | Exact term matches, names, codes |180 | **Hybrid** | Dense + Sparse with score fusion | Best overall quality |181 | **Multi-query** | Generate N query variants, retrieve for each, merge | Complex or ambiguous queries |182 | **Parent-child** | Retrieve small chunks, return parent chunks | Need both precision and context |1831843. **Re-ranking**:185 - Apply a cross-encoder re-ranker (e.g., Cohere Rerank, BGE-Reranker)186 - Re-ranking is the single highest-impact improvement for most RAG systems187 - Retrieve more candidates than needed (e.g., top-20), re-rank to top-51881894. **Post-retrieval filtering**:190 - Remove chunks below a relevance score threshold191 - Deduplicate near-identical chunks192 - Ensure diversity (don't return 5 chunks from the same page)193 - Respect recency requirements (filter by date if needed)194195### Phase 5: Context Assembly & Generation1961971. **Assemble the context**:198 - Order chunks by relevance (most relevant first AND last — avoid "lost in the middle")199 - Include source attribution metadata200 - Add a preamble: "Answer based ONLY on the following context. If the context201 doesn't contain the answer, say so."2022032. **Generation prompt template**:204205 ```206 You are a [domain] expert. Answer the user's question based on the207 provided context.208209 ## Rules210 - Only use information from the provided context211 - Cite sources using [Source: document_name, page X]212 - If the context is insufficient, explicitly state what's missing213 - Never fabricate information214215 ## Context216 {retrieved_chunks_with_metadata}217218 ## Question219 {user_query}220221 ## Answer222 ```2232243. **Response validation**:225 - Check for hallucination: Does every claim have a supporting chunk?226 - Check for completeness: Did the response address all parts of the query?227 - Check for citation accuracy: Do citations point to the right chunks?228229### Phase 6: Evaluation230231Evaluate the RAG pipeline at two levels:232233**Retrieval evaluation**:234235| Metric | What It Measures | Target |236|--------|-----------------|--------|237| **Recall@K** | % of relevant docs in top-K results | > 0.85 |238| **Precision@K** | % of top-K results that are relevant | > 0.70 |239| **MRR** (Mean Reciprocal Rank) | How high the first relevant result ranks | > 0.80 |240| **NDCG** | Quality of the ranking order | > 0.75 |241242**End-to-end evaluation**:243244| Metric | What It Measures | Method |245|--------|-----------------|--------|246| **Faithfulness** | Does the answer stick to the context? | LLM-as-judge |247| **Relevance** | Does the answer address the question? | LLM-as-judge |248| **Completeness** | Are all aspects of the question covered? | Human eval + LLM |249| **Citation accuracy** | Do citations match the claims? | Automated check |250251**Build an eval dataset**:252- Minimum 50 question-answer pairs with annotated relevant documents253- Include: easy factual, multi-hop reasoning, unanswerable, and adversarial queries254- Version control the eval set and never train/tune on it255256## Common Failure Modes & Fixes257258| Symptom | Root Cause | Fix |259|---------|-----------|-----|260| Answers are generic, don't use context | Weak retrieval, chunks not relevant | Improve chunking, add re-ranker |261| Answers hallucinate facts | Context insufficient, no guardrails | Add "only use context" constraint, validate |262| Answers are correct but miss details | Chunks too small, key info split | Increase chunk size or use parent-child |263| Wrong documents retrieved | Query-document vocabulary mismatch | Add hybrid search, query expansion |264| Good retrieval but bad answers | Poor prompt engineering | Improve generation prompt, add examples |265| Slow response times | Too many chunks, large context | Reduce top-K, use faster embedding model |266| Inconsistent quality | No evaluation framework | Build eval harness, monitor metrics |267268## Guidelines269270- **Start simple, iterate**: Begin with Tier 1 (naive RAG), measure, then add271 complexity only where metrics show gaps.272- **Re-ranking is the best single upgrade**: If you do one thing to improve quality,273 add a cross-encoder re-ranker.274- **Chunk quality > chunk quantity**: 5 excellent chunks beat 20 mediocre ones.275- **Always evaluate**: Without metrics, you're guessing. Build the eval harness276 before optimizing.277- **Version everything**: Embedding models, chunk strategies, and prompts should278 all be versioned and traceable.