Rag pipeline design

From FerroxLabs/wayland · View interactive version

Rag pipeline design is an AI agent skill from the GitHub repository FerroxLabs/wayland. Guides expert-level rag pipeline design implementation: ai-ml and database decision frameworks, production-ready patterns, and concrete templates for rag pipeline design workflows. Use when the user asks about rag pipeline design, rag pipeline design configuration, or ai-ml best practices for rag pr

How to use this skill

Skill file

RAG Pipeline Design

When to Use

Use this skill when:

Do NOT use this skill when:


Process

Step 1: Define the RAG Problem Precisely

Before touching any code or infrastructure, establish the precise problem definition. Ambiguity at this stage causes expensive rework.


Step 2: Select the RAG Architecture Pattern

Choose among the three major RAG patterns based on the outputs of Step 1.


Step 3: Design the Ingestion Pipeline

The ingestion pipeline determines the maximum quality ceiling of retrieval. Poor ingestion cannot be compensated by better retrieval or generation.


Step 4: Configure the Vector Store and Indexing

Vector store configuration directly determines retrieval latency and recall at scale.


Step 5: Design the Query Processing Layer

The query processing layer transforms raw user input into retrieval-optimized queries and is the highest-leverage improvement available after the indexing strategy is set.


Step 6: Design the Reranking and Context Assembly Layer

Reranking converts high-recall retrieval results into high-precision context for the generation layer.


Step 7: Design the Generation Layer

The generation layer transforms retrieved context into a final answer with appropriate quality controls.


Step 8: Build the Evaluation and Observability Layer

A RAG pipeline without systematic evaluation is unmaintainable. Build evaluation infrastructure before going to production.


Output Format

Produce the following artifacts when designing a RAG pipeline:

RAG Pipeline Architecture Summary

Pipeline Name:        [Name]
Pattern:              [Naive | Advanced | Modular | Graph]
Corpus Size:          [estimated tokens and document count]
Query Types:          [factual | multi-hop | comparison | procedural -- with % distribution]
Latency SLA:          [p95 end-to-end latency target in seconds]
Quality Targets:      Faithfulness ≥ [X], Answer Relevance ≥ [X],
                      Context Precision ≥ [X], Context Recall ≥ [X]

Component Configuration Table

| Stage | Component | Configuration | Rationale |

|---|---|---|---|

| Parsing | [Parser] | [format-aware settings] | [why this parser for this data] |

| Chunking | [Strategy] | size=[tokens], overlap=[tokens] | [why this strategy] |

| Embedding | [Model] | dim=[N], batch=[N] | [benchmark justification] |

| Vector Store | [Store] | index=[HNSW/IVF], M=[N], ef=[N] | [scale and latency justification] |

| Retrieval | [Dense/Sparse/Hybrid] | top-k=[N], alpha=[N for hybrid] | [query type justification] |

| Query Transform | [HyDE/Decomp/None] | [config] | [query pattern justification] |

| Reranking | [Cross-encoder/LLM/None] | top-n=[N] | [precision requirement] |

| Generation | [LLM] | temp=[N], max_tokens=[N] | [task justification] |

System Architecture Diagram

User Query
    |
    v
[Query Classifier] --(route)--> [Query Transformer]
                                    |
                        +-----------+-----------+
                        |                       |
                [Dense Retriever]       [Sparse Retriever]
                  (vector store)           (BM25 index)
                        |                       |
                        +------[RRF Fusion]-----+
                                    |
                            [Cross-Encoder Reranker]
                                    |
                          [Context Compressor]
                                    |
                         [Context Assembler]
                          (lost-in-middle fix)
                                    |
                         [Generation LLM]
                          + system prompt
                          + grounding instructions
                                    |
                        [Citation Verifier]
                                    |
                            Final Answer
                                    |
                     [Evaluation Logger] --> RAGAS pipeline

Ingestion Pipeline Diagram

Raw Documents (PDF/HTML/DOCX/Code)
    |
[Format-Aware Parser]
    |
[Boilerplate Stripper / Structure Extractor]
    |
[Chunker] --> [Metadata Enricher]
    |                |
    +----------------+
    |
[Content Hash Deduplicator]
    |
[Embedding Model] (batched, async)
    |
[Vector Store Upsert] + [BM25 Index Update]
    |
[Ingestion Audit Log]

Python Component Template

# rag_pipeline.py
# Production RAG Pipeline -- Advanced Pattern

import hashlib
from dataclasses import dataclass
from typing import Optional

@dataclass
class RAGConfig:
    # Chunking
    chunk_size_tokens: int = 512
    chunk_overlap_tokens: int = 64
    chunking_strategy: str = "semantic"  # fixed | semantic | hierarchical | proposition

    # Retrieval
    dense_top_k: int = 20
    sparse_top_k: int = 20
    rerank_top_n: int = 5
    retrieval_mode: str = "hybrid"  # dense | sparse | hybrid
    hybrid_alpha: float = 0.7  # weight for dense vs sparse (0=pure sparse, 1=pure dense)
    min_retrieval_score: float = 0.60  # below this, treat as no relevant results

    # Generation
    llm_temperature: float = 0.1
    max_context_tokens: int = 4096
    max_generation_tokens: int = 1024
    enable_citation_verification: bool = True
    enable_self_consistency: bool = False
    self_consistency_samples: int = 3

    # Evaluation
    enable_ragas_logging: bool = True
    sample_rate_for_human_eval: float = 0.02


@dataclass
class RetrievedChunk:
    chunk_id: str
    content: str
    source_document: str
    section_title: Optional[str]
    page_number: Optional[int]
    dense_score: Optional[float]
    sparse_score: Optional[float]
    rerank_score: Optional[float]
    metadata: dict


@dataclass
class RAGResponse:
    answer: str
    sources: list[RetrievedChunk]
    answer_in_context: bool  # False triggers fallback UX
    citation_verified: bool
    latency_ms: dict  # stage-by-stage breakdown
    token_usage: dict
    ragas_log_id: Optional[str]


class RAGPipeline:
    """
    Advanced RAG pipeline with hybrid retrieval, cross-encoder reranking,
    context compression, and citation verification.

    Configuration is fully injectable for A/B testing and gradual rollout.
    All stages emit structured logs for RAGAS evaluation and cost tracking.
    """

    def __init__(self, config: RAGConfig) -> None:
        self.config = config
        self._init_components()

    def _init_components(self) -> None:
        # Initialize each stage independently for testability
        self.query_classifier = self._build_query_classifier()
        self.query_transformer = self._build_query_transformer()
        self.dense_retriever = self._build_dense_retriever()
        self.sparse_retriever = self._build_sparse_retriever()
        self.reranker = self._build_reranker()
        self.context_compressor = self._build_context_compressor()
        self.generator = self._build_generator()
        self.citation_verifier = self._build_citation_verifier()

    async def query(self, user_query: str, filters: Optional[dict] = None) -> RAGResponse:
        """
        End-to-end RAG query with full stage telemetry.
        filters: optional metadata pre-filter dict, e.g. {"doc_type": "policy", "year": 2023}
        """
        # Stage 1: Query classification and transformation
        query_type = await self.query_classifier.classify(user_query)
        transformed_queries = await self.query_transformer.transform(user_query, query_type)

        # Stage 2: Hybrid retrieval across all transformed queries
        dense_results = await self.dense_retriever.retrieve(
            transformed_queries, top_k=self.config.dense_top_k, filters=filters
        )
        sparse_results = await self.sparse_retriever.retrieve(
            transformed_queries, top_k=self.config.sparse_top_k, filters=filters
        )
        fused_results = self._reciprocal_rank_fusion(
            dense_results, sparse_results, alpha=self.config.hybrid_alpha
        )

        # Stage 3: Reranking and context assembly
        reranked = await self.reranker.rerank(
            user_query, fused_results, top_n=self.config.rerank_top_n
        )
        compressed = await self.context_compressor.compress(user_query, reranked)
        context = self._assemble_context_lost_in_middle(compressed)

        # Stage 4: Generation with grounding
        if not reranked or reranked[0].rerank_score < self.config.min_retrieval_score:
            return self._no_context_fallback(user_query)

        response = await self.generator.generate(user_query, context)

        # Stage 5: Citation verification
        if self.config.enable_citation_verification:
            verified = await self.citation_verifier.verify(response, reranked)
        else:
            verified = True

        return RAGResponse(
            answer=response.text,
            sources=reranked,
            answer_in_context=True,
            citation_verified=verified,
            latency_ms=self._collect_latencies(),
            token_usage=self._collect_token_usage(),
            ragas_log_id=self._emit_ragas_log(user_query, context, response),
        )

    def _reciprocal_rank_fusion(self, dense, sparse, alpha: float, k: int = 60) -> list:
        """
        Combine dense and sparse results using weighted RRF.
        alpha=1.0 is pure dense, alpha=0.0 is pure sparse.
        k=60 is the standard RRF constant that prevents top-rank domination.
        """
        scores = {}
        for rank, chunk in enumerate(dense):
            scores[chunk.chunk_id] = scores.get(chunk.chunk_id, 0) + alpha * (1 / (k + rank + 1))
        for rank, chunk in enumerate(sparse):
            scores[chunk.chunk_id] = scores.get(chunk.chunk_id, 0) + (1 - alpha) * (1 / (k + rank + 1))
        sorted_ids = sorted(scores, key=lambda x: scores[x], reverse=True)
        chunk_map = {c.chunk_id: c for c in dense + sparse}
        return [chunk_map[cid] for cid in sorted_ids if cid in chunk_map]

    def _assemble_context_lost_in_middle(self, chunks: list) -> str:
        """
        Assemble context with lost-in-the-middle mitigation.
        Place highest-relevance chunk first, then lowest-relevance chunks in the middle,
        then second-highest at the end.
        """
        if not chunks:
            return ""
        if len(chunks) == 1:
            return chunks[0].content
        reordered = [chunks[0]] + chunks[2:] + [chunks[1]]
        return "\n\n---\n\n".join(
            f"[Source: {c.source_document}, Section: {c.section_title}]\n{c.content}"
            for c in reordered
        )

Evaluation Dashboard Schema

Weekly RAGAS Report
====================
Date Range:        [YYYY-MM-DD to YYYY-MM-DD]
Total Queries:     [N]
Sampled:           [N] ([X]%)

Core Metrics (automated):
  Faithfulness:         [X.XX]  (target ≥ 0.85)  [PASS/WARN/FAIL]
  Answer Relevance:     [X.XX]  (target ≥ 0.80)  [PASS/WARN/FAIL]
  Context Precision:    [X.XX]  (target ≥ 0.75)  [PASS/WARN/FAIL]
  Context Recall:       [X.XX]  (target ≥ 0.70)  [PASS/WARN/FAIL]

Latency (p50 / p95 / p99):
  Total:                [Xs] / [Xs] / [Xs]
  Retrieval:            [Xs] / [Xs] / [Xs]
  Reranking:            [Xs] / [Xs] / [Xs]
  Generation:           [Xs] / [Xs] / [Xs]

Cost:
  Avg tokens/query:     [N] (prompt: [N], completion: [N])
  Avg cost/query:       $[X.XXXX]
  Projected monthly:    $[X]

Top Failure Modes:
  No-context fallback rate:    [X]%
  Citation verification fail:  [X]%
  Rerank score below threshold: [X]%

Rules

  1. NEVER chunk before cleaning. Boilerplate, headers, footers, navigation elements, and watermarks in document text corrupt chunk quality. Parser output must be cleaned before chunking. A single uncleaned document can produce dozens of low-quality chunks that degrade retrieval precision across all queries.
  1. NEVER choose an embedding model without checking its max sequence length against your chunk size. If chunks exceed the embedding model's max token limit (commonly 512 tokens for older models), content is silently truncated. Use models with max sequence length ≥ 1.5x your target chunk size to provide headroom.
  1. ALWAYS compute retrieval quality metrics separately from generation quality metrics. Debugging a RAG pipeline requires knowing whether failures originate in retrieval or generation. Combine RAGAS Context Precision and Recall for retrieval evaluation and Faithfulness for generation. A Faithfulness failure with high Context Precision indicates a generation problem. A Context Recall failure indicates a retrieval or chunking problem.
  1. NEVER pass more tokens to the generation LLM than the context window allows minus prompt overhead minus expected output tokens. Calculate: usable_context = context_window - system_prompt_tokens - query_tokens - max_output_tokens - safety_buffer(200). Exceeding this silently truncates context or throws errors depending on the API.
  1. ALWAYS store the original document alongside chunks and embeddings. Retrieval pipelines require frequent re-ingestion as chunking strategies, embedding models, or metadata schemas evolve. Without the original documents, re-ingestion requires re-crawling the source system, which is often unavailable or slow. Store raw source documents in object storage (S3-compatible) with the same document ID used in the vector store.
  1. NEVER use the same embedding model for queries and documents without verifying the model was trained for asymmetric retrieval. Some embedding models are trained symmetrically (query and document are the same type). For asymmetric retrieval (short query, long document), use models explicitly trained for that setting or use a query prefix instruction to signal the query role.
  1. ALWAYS set a minimum retrieval score threshold and define explicit behavior when no chunks exceed it. A RAG pipeline without a fallback for zero-recall queries will hallucinate when forced to answer from empty context. Define the fallback: "I don't have relevant information about this topic" with an optional escalation path.
  1. NEVER deploy a RAG pipeline to production without a golden dataset of at least 100 QA pairs for regression testing. Without a golden dataset, pipeline changes (new embedding model, different chunk size, updated prompts) cannot be validated. Every architecture change must be evaluated against the golden dataset before deployment.
  1. NEVER hard-code retrieval top-k without accounting for downstream context window constraints. top_k=10 with 512-token chunks consumes 5,120 tokens of context before the prompt and query. Calculate the maximum feasible top-k for your chunk size and context window, then tune down from there based on quality measurements.
  1. ALWAYS version your embedding model and vector store index together. Embeddings from different model versions are geometrically incompatible -- mixing them in the same index produces silently degraded retrieval. When upgrading the embedding model, create a new index namespace, re-embed all documents, validate quality on the golden dataset, then swap traffic atomically. Never incrementally update a single index with embeddings from two different model versions.

Edge Cases

Legacy Document Corpus with Mixed Quality

Enterprise corpora frequently contain scanned PDFs (requiring OCR), HTML with heavy boilerplate, Word documents with revision history, and PowerPoint slides with minimal text. Each format requires a different parsing strategy.

Corpus Updates and Stale Retrieval

When the source corpus is updated frequently (e.g., a knowledge base with daily edits, a documentation site with frequent releases), stale chunks produce confidently wrong answers that are worse than no-answer fallbacks.

Multi-Language Corpus

RAG pipelines built with English-only embedding models fail silently on non-English queries and documents -- they produce embeddings in the same space but with dramatically reduced semantic accuracy.

Very Long Documents (Books, Legal Agreements, Research Reports)

Documents exceeding 100 pages produce hundreds of chunks that may all have moderate similarity to a given query, exhausting the context window and diluting the truly relevant content.

Adversarial and Off-Topic Queries

Production RAG systems receive queries that are unrelated to the corpus, attempts to extract sensitive information from source documents, or prompt injection attempts embedded in user input.

Context Window Exhaustion at High top-k

When retrieval returns many large chunks and the context window is limited (e.g., using a 4K-context model for cost reasons), context assembly must be precise.

Evaluation Metric Paradoxes

RAGAS metrics can produce misleading signals if interpreted without domain context.


Example

Input: "We're building a RAG pipeline for a legal tech startup. Our corpus is 50,000 legal contracts (PDFs, average 30 pages each), primarily US commercial contracts in English. Users are lawyers asking detailed contract review questions like 'Does this agreement contain a limitation of liability clause? What are the caps?' We need sub-3-second p95 latency, high faithfulness, and the pipeline must go to production in 8 weeks. What architecture should we use?"


Output:

Problem Analysis

This is a well-defined Advanced RAG use case with several domain-specific requirements that drive concrete decisions:


Recommended Architecture: Advanced RAG with Clause-Aware Chunking

Pattern: Advanced RAG

Query Type Distribution: ~70% clause lookup, ~20% clause interpretation, ~10% comparison

Latency Budget: 3000ms p95 end-to-end

Quality Targets: Faithfulness ≥ 0.88, Answer Relevance ≥ 0.82, Context Precision ≥ 0.80, Context Recall ≥ 0.75


Component Configuration

| Stage | Component | Configuration | Rationale |

|---|---|---|---|

| Parsing | Layout-aware PDF parser | Structure extraction enabled, TOC extraction, clause boundary detection | Legal PDFs have dense two-column layouts and section hierarchies that naive parsers flatten, destroying clause structure |

| Chunking | Hierarchical clause-aware | Parent: contract section (1024 tokens), Child: individual clause (256--512 tokens), overlap: 0 (clause boundaries are hard) | Legal meaning is clause-scoped. Overlapping clause text creates ambiguous attributions. Parent-child allows precise retrieval with full-context generation |

| Embedding | Legal-domain embedding model | 768-dimension, max 512 tokens, asymmetric retrieval trained | Legal language has a distinct vocabulary distribution. A general-purpose embedding model underperforms on legal terminology and clause-type classification |

| Vector Store | HNSW index | M=32, ef_construction=400, ef_query=150 | 1.5M vectors requires ANN. M=32 provides higher recall than default M=16. At 1.5M vectors, HNSW retrieval latency is ~15--40ms, within latency budget |

| Retrieval | Hybrid (dense + BM25) | dense top-k=20, sparse top-k=20, hybrid_alpha=0.6 (slightly dense-weighted), RRF k=60 | Contract queries frequently contain specific legal phrases ("limitation of liability," "indemnification," "force majeure") that are high-precision BM25 targets. Hybrid captures both semantic and keyword signals |

| Query Transform | None for clause lookup; HyDE for interpretation queries | Query classifier routes interpretation queries through HyDE | Clause lookup queries are precise -- transformation degrades them. Interpretation queries are abstract -- HyDE improves recall significantly |

| Reranking | Cross-encoder | top-n=5, legal domain cross-encoder preferred | Cross-encoder reranking is the highest single-stage quality improvement available. Latency budget: 400ms for reranking 40 candidate chunks. Use a distilled model for speed |

| Context Assembly | Lost-in-middle mitigation + deduplication | Assemble up to 3500 context tokens using greedy packer | Clause answers are typically short. 3500 context tokens accommodates 5--7 full clauses with attribution headers |

| Generation | LLM with legal grounding prompt | temperature=0.0, max_tokens=800, structured JSON output | Legal answers require high determinism. JSON output with clause_found boolean, clause_text extraction, interpretation, and source_section fields enables downstream citation display |

| Citation Verification | NLI-based verifier | Verify each claim in the answer against retrieved chunks | Legal accuracy is non-negotiable. NLI verification catches generation-level hallucination. Flag unverified answers for human review |


Ingestion Pipeline -- Legal Contract Specific

Clause boundary detection strategy:

Legal contracts have a consistent heading pattern: numbered clauses (1., 2., 1.1, 1.2) and titled clauses (WHEREAS, NOW, THEREFORE, Section 1. Definitions). Extract these boundaries using regex and layout cues from the PDF parser's heading detection.

Metadata schema per chunk:

{
  "chunk_id": "sha256(contract_id + clause_number)",
  "contract_id": "contract_20240115_acme_vendor",
  "clause_number": "12.3",
  "clause_title": "Limitation of Liability",
  "clause_type": "limitation_of_liability",
  "governing_law": "Delaware",
  "contract_type": "Master Service Agreement",
  "effective_date": "2024-01-15",
  "party_a": "ACME Corp",
  "party_b": "Vendor Inc",
  "page_range": [28, 29],
  "parent_chunk_id": "sha256(contract_id + section_12)"
}

Clause type taxonomy: Pre-tag each chunk with its clause type using a clause classifier (a fine-tuned classifier or few-shot LLM call at ingestion). The taxonomy should cover the 30--40 most common clause types in commercial contracts: limitation of liability, indemnification, governing law, dispute resolution, termination, confidentiality, IP assignment, warranty disclaimer, force majeure, payment terms, etc. This metadata enables highly precise filtered retrieval.

Estimated ingestion time: 50,000 contracts × 30 pages = 1.5M pages. At 10 pages/second parsing and 200 chunks/second embedding (batched), total ingestion time ≈ 55 hours. Plan for a 72-hour initial ingestion window with incremental updates thereafter.


Query Processing -- Clause Lookup Example

User query: "Does this agreement contain a limitation of liability clause? What are the caps?"

Query classification: Clause lookup (single-hop, high precision required)

Metadata filter applied: {"contract_id": "contract_20240115_acme_vendor"} -- single-contract query, pre-filter eliminates 99.998% of the corpus immediately

Dense query: "limitation of liability clause caps maximum liability" -- no HyDE needed for this precise query type

BM25 query: "limitation of liability" AND "cap" AND ("shall not exceed" OR "maximum" OR "aggregate")

After hybrid retrieval and reranking (top 5 chunks):

  1. Clause 12.3 "Limitation of Liability" (rerank score: 0.94) -- primary clause text
  2. Clause 12.4 "Exceptions to Limitation" (rerank score: 0.89) -- carve-outs from the cap
  3. Clause 1.1 Definition of "Liability" (rerank score: 0.71) -- definitional scope
  4. Clause 14.2 "Indemnification Cap" (rerank score: 0.67) -- related financial cap
  5. Clause 12.1 "Mutual Indemnification" (rerank score: 0.61) -- adjacent clause for context

Generation prompt structure:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.