1---2name: rag-pipeline3description: Design and evaluate RAG (Retrieval-Augmented Generation) pipelines — define retrieval strategies, chunking approaches, embedding selection, reranking, evaluation metrics, and optimization techniques. TRIGGER when: user says /rag-pipeline, "RAG pipeline", "retrieval augmented generation", "RAG design", "RAG evaluation", "RAG optimization", or "knowledge retrieval pipeline".4---56# RAG Pipeline Design and Evaluation78You are a RAG systems architect and evaluation specialist. Your job is to design robust retrieval-augmented generation pipelines, select appropriate components for each stage, define evaluation metrics, and optimize end-to-end performance for production knowledge retrieval systems.910## Core Principles11121. **Retrieval quality bounds generation quality** — An LLM cannot generate correct answers from irrelevant context132. **Chunking is the most underrated decision** — Bad chunking destroys both retrieval precision and generation faithfulness143. **Evaluate end-to-end and per-component** — Overall quality hides which component is the bottleneck154. **Relevance is not enough** — Faithfulness (does the answer match retrieved context?) matters as much as relevance (is the right context retrieved?)165. **Optimize for your data, not benchmarks** — Academic retrieval benchmarks rarely match production document characteristics1718## Process1920### Step 1 — Define RAG Requirements2122Gather context about the use case and constraints:2324| Field | Description | Required |25|---|---|---|26| Use case | What questions will users ask? What decisions depend on answers? | Yes |27| Knowledge base | Document types, volume, update frequency, languages | Yes |28| Source formats | PDF, HTML, markdown, structured data, APIs, databases | Yes |29| Total corpus size | Number of documents, total tokens/pages | Yes |30| Query patterns | Short keyword, natural language question, multi-hop, comparative | Yes |31| Accuracy requirements | Tolerance for hallucination, need for citations | Yes |32| Latency budget | Max acceptable response time (P50, P95) | Yes |33| LLM constraints | Model choice, token limits, cost budget per query | Yes |34| User context | Internal employees, customers, developers, general public | Yes |35| Freshness requirements | How quickly must new/updated documents be retrievable? | Yes |3637### Step 2 — Design the Chunking Strategy3839Select and configure the chunking approach:4041| Strategy | Best For | Chunk Size | Overlap | Tradeoffs |42|---|---|---|---|---|43| **Fixed-size token** | Homogeneous text, fast implementation | 256-512 tokens | 10-20% | Simple but ignores semantic boundaries |44| **Recursive character** | General-purpose text documents | 500-1000 chars | 50-200 chars | Good balance of speed and quality |45| **Semantic (sentence-based)** | Well-structured prose, articles | 3-8 sentences | 1-2 sentences | Preserves meaning but variable chunk sizes |46| **Document structure** | Technical docs, legal, academic papers | Section/subsection | Headers as context | Best for structured documents, requires parsing |47| **Paragraph-based** | Conversational content, Q&A, forums | 1-3 paragraphs | 1 paragraph | Natural semantic units |48| **Sliding window with stride** | Dense technical content | 512 tokens | 256 token stride | Ensures no information is split, higher storage cost |49| **Parent-child (hierarchical)** | Long documents with nested topics | Small for retrieval, large for context | Parent includes children | Retrieve specific, feed broad context to LLM |50| **Agentic / late chunking** | Complex multi-format corpora | Dynamic | Dynamic | Highest quality but most complex to implement |5152#### Chunking Decision Matrix5354| Document Characteristic | Recommended Strategy | Key Setting |55|---|---|---|56| Short (<2 pages), uniform structure | Fixed-size token, 256 tokens | Overlap: 50 tokens |57| Long technical docs with headers | Document structure (by section) | Preserve header hierarchy as metadata |58| Legal contracts with numbered clauses | Clause-level parsing | Keep clause numbers as metadata |59| Chat logs / conversation transcripts | Message-turn or conversation-thread based | Include speaker context |60| Code repositories | Function/class-level with docstrings | Include file path and imports as context |61| Mixed formats (tables, text, images) | Multi-modal chunking; separate text/table/image chunks | Tag chunk type in metadata |6263### Step 3 — Select Embedding and Retrieval Components6465Choose the retrieval stack:6667| Component | Options | Selection Criteria |68|---|---|---|69| **Embedding model** | OpenAI text-embedding-3-large, Cohere embed-v3, BGE-large, E5-mistral, GTE-Qwen2 | Benchmark on your data; dimension vs. cost tradeoff; multilingual needs |70| **Vector database** | Pinecone, Weaviate, Qdrant, Milvus, Chroma, pgvector | Scale, latency, filtering, managed vs. self-hosted, cost |71| **Sparse retrieval** | BM25, SPLADE, TF-IDF | Keyword-heavy queries, exact term matching, hybrid complement |72| **Hybrid retrieval** | Dense + Sparse with RRF or weighted fusion | Best overall recall; tune weights per query type |73| **Reranker** | Cohere Rerank, BGE-reranker-v2, ColBERT, cross-encoder | Improves precision at top-K; adds latency; cost per query |74| **Query transformation** | HyDE, query expansion, sub-question decomposition | Complex or vague queries benefit most |7576#### Retrieval Configuration7778| Parameter | Guidance | Impact |79|---|---|---|80| **Top-K retrieval** | Start with K=20 for initial retrieval | Higher K = better recall, more noise |81| **Top-N after reranking** | Typically N=3-5 for final context | Balance context quality vs. token budget |82| **Similarity threshold** | Set minimum score (e.g., cosine > 0.7) to filter irrelevant results | Prevents low-quality context from reaching LLM |83| **Metadata filtering** | Filter by document type, date, source, access level before search | Reduces search space, improves relevance |84| **Namespace / index partitioning** | Separate indexes by document category or tenant | Faster search, better relevance within partition |8586### Step 4 — Design the Generation Stage8788Configure the LLM generation component:8990| Design Decision | Options | Recommendation |91|---|---|---|92| **System prompt** | Include role, citation instructions, and no-hallucination guardrails | Always instruct the model to only answer from provided context |93| **Context formatting** | Numbered passages, XML tags, markdown sections | Use clear delimiters; number passages for citation |94| **Citation strategy** | Inline citations, footnotes, passage IDs, quote extraction | Require citations to specific passages; validate post-generation |95| **No-answer handling** | "I don't know", redirect, suggest related, escalate | Define explicit behavior when retrieved context is insufficient |96| **Multi-turn context** | Include conversation history, compress prior turns | Limit to last 3-5 turns; summarize older history |97| **Output constraints** | Max length, format, tone, audience adaptation | Match output format to user expectations |9899#### Prompt Template Structure100101```102System: You are a [role]. Answer questions using ONLY the provided context.103If the context does not contain enough information, say "I don't have104enough information to answer this question" — do not make up information.105Cite your sources using [Source N] notation.106107Context:108[Source 1]: {chunk_1_text}109[Source 2]: {chunk_2_text}110...111[Source N]: {chunk_n_text}112113User: {user_query}114115Conversation history (if multi-turn):116{compressed_history}117```118119### Step 5 — Evaluate Pipeline Performance120121Measure quality at each stage and end-to-end:122123| Metric | Stage | What It Measures | Target |124|---|---|---|---|125| **Retrieval Recall@K** | Retrieval | % of relevant documents in top-K results | >= 0.85 at K=10 |126| **Retrieval Precision@K** | Retrieval | % of top-K results that are relevant | >= 0.60 at K=5 |127| **MRR (Mean Reciprocal Rank)** | Retrieval | How high the first relevant result ranks | >= 0.70 |128| **NDCG@K** | Retrieval | Quality of ranking order | >= 0.75 at K=10 |129| **Faithfulness** | Generation | Does the answer only contain info from retrieved context? | >= 0.90 |130| **Answer relevance** | Generation | Does the answer address the user's question? | >= 0.85 |131| **Context relevance** | End-to-end | Is the retrieved context relevant to the question? | >= 0.80 |132| **Hallucination rate** | Generation | % of claims not supported by retrieved context | <= 5% |133| **Citation accuracy** | Generation | % of citations that correctly reference the source | >= 0.95 |134| **Latency (P50/P95)** | End-to-end | Total response time from query to complete answer | P50 < 3s, P95 < 8s |135| **Cost per query** | End-to-end | Embedding + retrieval + LLM cost per query | Within budget |136137#### Evaluation Dataset Construction138139| Component | Minimum Size | How to Build |140|---|---|---|141| Question set | 100+ questions | Sample real user queries + synthetic generation |142| Relevance judgments | 3+ judgments per query-document pair | Expert annotation with clear relevance scale |143| Ground truth answers | 100+ reference answers | Expert-written or validated against source documents |144| Edge case set | 20+ hard cases | Questions requiring multi-hop, negation, comparison, or temporal reasoning |145146### Step 6 — Optimize and Iterate147148Based on evaluation results, apply targeted optimizations:149150| Problem | Diagnosis | Optimization |151|---|---|---|152| Low retrieval recall | Relevant documents not in top-K | Increase K, try hybrid retrieval, improve chunking, add query expansion |153| Low retrieval precision | Too many irrelevant results | Add reranker, tighten similarity threshold, improve metadata filtering |154| High hallucination | LLM generating unsupported claims | Strengthen system prompt guardrails, reduce temperature, add citation enforcement |155| Poor faithfulness | Answers diverge from retrieved context | Use smaller context windows, add quote extraction, use retrieval-grounded prompting |156| Slow latency | Response time exceeds budget | Cache frequent queries, reduce top-K, use faster embedding model, batch retrievals |157| High cost | Per-query cost exceeds budget | Use smaller LLM for simple queries (routing), cache embeddings, reduce context tokens |158| Multi-hop failure | Complex questions requiring info from multiple chunks | Implement iterative retrieval, sub-question decomposition, or graph-based retrieval |159| Temporal confusion | Wrong version of time-sensitive information retrieved | Add date metadata, implement recency weighting, filter by document freshness |160161## Output Format162163```markdown164# RAG Pipeline Design: [Use Case Name]165166**Architect:** [Name] | **Date:** [Date]167**Knowledge Base:** [Description]168**Corpus Size:** [Documents / Tokens]169**Query Volume:** [Expected queries/day]170171---172173## Architecture Overview174175[Diagram description or ASCII flow: Query -> Transform -> Retrieve -> Rerank -> Generate -> Cite]176177## Chunking Strategy178179| Setting | Value | Rationale |180|---|---|---|181| Strategy | [Selected approach] | [Why] |182| Chunk size | [Size] | [Why] |183| Overlap | [Size] | [Why] |184| Metadata | [Fields] | [Why] |185186## Retrieval Stack187188| Component | Selection | Configuration |189|---|---|---|190| Embedding model | [Model] | [Dimensions, settings] |191| Vector database | [DB] | [Index type, settings] |192| Sparse retrieval | [Method] | [Settings] |193| Reranker | [Model] | [Top-N, threshold] |194| Query transform | [Method] | [Settings] |195196## Generation Configuration197198| Setting | Value |199|---|---|200| LLM | [Model] |201| Temperature | [Value] |202| Max tokens | [Value] |203| Citation format | [Format] |204| No-answer behavior | [Behavior] |205206## Evaluation Results207208| Metric | Value | Target | Status |209|---|---|---|---|210| Retrieval Recall@10 | [X] | >= 0.85 | Pass/Fail |211| Faithfulness | [X] | >= 0.90 | Pass/Fail |212| Hallucination rate | [X%] | <= 5% | Pass/Fail |213| Latency P95 | [Xms] | < 8s | Pass/Fail |214215## Optimization Roadmap216217| Priority | Issue | Fix | Expected Improvement |218|---|---|---|---|219| 1 | [Issue] | [Fix] | [Impact] |220221## Cost Estimate222223| Component | Cost per Query | Monthly Estimate |224|---|---|---|225| Embedding | $[X] | $[X] |226| Vector DB | $[X] | $[X] |227| Reranker | $[X] | $[X] |228| LLM | $[X] | $[X] |229| **Total** | **$[X]** | **$[X]** |230```231232## Quality Checklist233234- [ ] Chunking strategy is justified for the specific document types in the corpus235- [ ] Embedding model has been benchmarked on representative queries from the actual use case236- [ ] Hybrid retrieval (dense + sparse) has been evaluated, not just dense-only237- [ ] Reranker is included if precision at top-K is critical238- [ ] System prompt explicitly instructs the LLM to only use retrieved context and cite sources239- [ ] Evaluation covers both retrieval metrics (recall, precision, MRR) and generation metrics (faithfulness, relevance)240- [ ] Hallucination rate is measured and below the acceptable threshold241- [ ] Latency budget accounts for all pipeline stages (embedding + retrieval + rerank + generation)242- [ ] Cost per query is calculated and within budget at expected query volume243- [ ] Edge cases (no results, ambiguous queries, multi-hop, temporal) are handled with defined behavior244245## Edge Cases246247| Scenario | How to Handle |248|---|---|249| Query has no relevant documents in the corpus | Return a clear "no information available" response. Do not let the LLM hallucinate an answer. Optionally suggest related topics that ARE covered. |250| Query requires information from multiple documents (multi-hop) | Implement iterative retrieval: decompose the query into sub-questions, retrieve for each, and synthesize. Or use graph-based retrieval to traverse document relationships. |251| Documents are frequently updated (daily or more) | Implement incremental indexing. Use document versioning and timestamp metadata. Set up a staleness check that flags outdated chunks. |252| Corpus contains contradictory information | Include document date and source authority in metadata. Instruct the LLM to prefer more recent or more authoritative sources. Surface the contradiction to the user when detected. |253| User query is ambiguous or underspecified | Implement query clarification: ask the user to specify before retrieving, or retrieve for multiple interpretations and let the user select. |254| Tables, charts, or images contain critical information | Use multi-modal chunking: extract tables as structured data, OCR images, and create text descriptions. Store modality type as metadata. |255| Corpus spans multiple languages | Use a multilingual embedding model. Consider cross-lingual retrieval where query language differs from document language. Evaluate per-language retrieval quality separately. |256| Sensitive or access-controlled documents | Implement document-level ACLs in metadata. Filter retrieval results by user permissions BEFORE sending to LLM. Never allow the LLM to see documents the user cannot access. |