RAG Architecture
Purpose
Design a Retrieval-Augmented Generation pipeline, including document processing, chunking strategy, embedding pipeline, vector database selection, retrieval optimization, and context assembly.
Inputs
- Source documents (type, volume, update frequency)
- Query patterns (user questions, search terms, structured queries)
- Quality requirements (relevance threshold, hallucination tolerance)
- Latency requirements (real-time, near-real-time, batch)
- Cost constraints (embedding costs, storage costs, query costs)
Process
Step 1: Analyze Source Documents
Understand what's being indexed:
- Document types: PDFs, web pages, code, structured data, conversations
- Volume: Number of documents, total size, growth rate
- Update frequency: Static corpus, daily updates, real-time
- Structure: Highly structured (tables, headers) vs unstructured (prose, transcripts)
- Quality: Clean text vs noisy (OCR artifacts, HTML remnants, duplicates)
Step 2: Design Chunking Strategy
Choose how to split documents:
- Fixed-size: 500-1000 tokens with 100-200 token overlap. Simple but may split concepts.
- Semantic: Split on paragraph/section boundaries. Preserves meaning but variable size.
- Hierarchical: Parent-child chunks (section summary + detail chunks). Best for complex docs.
- Recursive: Start large, recursively split until chunks fit size target.
- Metadata enrichment: Attach source, section title, page number to each chunk.
Step 3: Select Embedding Model
Choose the embedding approach:
- OpenAI text-embedding-3-small/large: Best general-purpose, 1536/3072 dimensions
- Cohere embed-v3: Strong multilingual, supports search and classification modes
- Open source (BGE, E5): Self-hosted, lower cost at scale, variable quality
- Considerations: Dimension size (storage), context length, multilingual support, cost per token
Step 4: Select Vector Database
Choose storage and retrieval:
| Database |
Hosted |
Open Source |
Hybrid Search |
Best For |
| Pinecone |
Yes |
No |
Yes (sparse+dense) |
Production, managed |
| Weaviate |
Yes |
Yes |
Yes (BM25+vector) |
Self-hosted, rich filtering |
| ChromaDB |
No |
Yes |
No |
Prototyping, local dev |
| pgvector |
Via Supabase |
Yes |
BM25 separate |
Already using Postgres |
| Qdrant |
Yes |
Yes |
Yes |
High-performance, filtering |
Step 5: Design Retrieval Pipeline
Build the query-time pipeline:
- Query preprocessing: Expand abbreviations, detect intent, generate sub-queries
- Embedding: Encode query with same model used for documents
- Initial retrieval: Top-K vector search (K=20-50)
- Reranking: Cross-encoder reranker to reorder by relevance (return top 5-10)
- Context assembly: Combine retrieved chunks into a prompt, add metadata
- Generation: LLM call with assembled context + user query
Step 6: Design Quality Metrics
Define how to measure RAG quality:
- Retrieval metrics: Recall@K (are relevant docs in top K?), MRR (is the best doc ranked first?)
- Generation metrics: Faithfulness (does the answer stick to context?), relevance (does it answer the question?)
- End-to-end: Answer accuracy on golden dataset, hallucination rate
- Monitoring: Track retrieval scores over time, flag low-confidence answers
Output Format
# RAG Architecture
## Source Analysis
| Attribute | Value |
|-----------|-------|
| Document types | [Types] |
| Corpus size | [Size] |
| Update frequency | [Frequency] |
## Chunking Strategy
**Method:** [Fixed/Semantic/Hierarchical]
**Target chunk size:** [X tokens]
**Overlap:** [X tokens]
**Metadata:** [Fields attached to each chunk]
## Embedding Pipeline
**Model:** [Name]
**Dimensions:** [N]
**Cost:** [$X per 1M tokens]
**Batch processing:** [Strategy for initial load vs incremental updates]
## Vector Database
**Choice:** [Database]
**Rationale:** [Why this DB]
**Index configuration:** [HNSW params, quantization, etc.]
**Hybrid search:** [BM25 + vector approach]
## Retrieval Pipeline
Query → [Preprocess] → [Embed] → [Vector Search (top 20)] → [Rerank (top 5)] → [Assemble Context] → [LLM] → [Validate] → Response
| Stage | Latency | Cost |
|-------|---------|------|
| Embedding | Xms | $X |
| Vector search | Xms | $X |
| Reranking | Xms | $X |
| Generation | Xms | $X |
| **Total** | **Xms** | **$X** |
## Quality Metrics
| Metric | Target | Measurement |
|--------|--------|-------------|
| Recall@10 | >90% | Golden dataset |
| Faithfulness | >95% | Automated scoring |
| Hallucination rate | <5% | Reference checking |
## Cost Model
| Component | Monthly Cost (at X queries/day) |
|-----------|-------------------------------|
| Embeddings | $X |
| Vector DB | $X |
| Reranking | $X |
| Generation | $X |
| **Total** | **$X** |
Quality Checks
Evolution Notes
1---2name: rag-architecture3description: Chunking strategies, embedding pipelines, vector DB selection, and retrieval optimization4---56# RAG Architecture78## Purpose910Design a Retrieval-Augmented Generation pipeline, including document processing, chunking strategy, embedding pipeline, vector database selection, retrieval optimization, and context assembly.1112## Inputs1314- Source documents (type, volume, update frequency)15- Query patterns (user questions, search terms, structured queries)16- Quality requirements (relevance threshold, hallucination tolerance)17- Latency requirements (real-time, near-real-time, batch)18- Cost constraints (embedding costs, storage costs, query costs)1920## Process2122### Step 1: Analyze Source Documents2324Understand what's being indexed:25- **Document types:** PDFs, web pages, code, structured data, conversations26- **Volume:** Number of documents, total size, growth rate27- **Update frequency:** Static corpus, daily updates, real-time28- **Structure:** Highly structured (tables, headers) vs unstructured (prose, transcripts)29- **Quality:** Clean text vs noisy (OCR artifacts, HTML remnants, duplicates)3031### Step 2: Design Chunking Strategy3233Choose how to split documents:34- **Fixed-size:** 500-1000 tokens with 100-200 token overlap. Simple but may split concepts.35- **Semantic:** Split on paragraph/section boundaries. Preserves meaning but variable size.36- **Hierarchical:** Parent-child chunks (section summary + detail chunks). Best for complex docs.37- **Recursive:** Start large, recursively split until chunks fit size target.38- **Metadata enrichment:** Attach source, section title, page number to each chunk.3940### Step 3: Select Embedding Model4142Choose the embedding approach:43- **OpenAI text-embedding-3-small/large:** Best general-purpose, 1536/3072 dimensions44- **Cohere embed-v3:** Strong multilingual, supports search and classification modes45- **Open source (BGE, E5):** Self-hosted, lower cost at scale, variable quality46- **Considerations:** Dimension size (storage), context length, multilingual support, cost per token4748### Step 4: Select Vector Database4950Choose storage and retrieval:5152| Database | Hosted | Open Source | Hybrid Search | Best For |53|----------|--------|------------|---------------|----------|54| Pinecone | Yes | No | Yes (sparse+dense) | Production, managed |55| Weaviate | Yes | Yes | Yes (BM25+vector) | Self-hosted, rich filtering |56| ChromaDB | No | Yes | No | Prototyping, local dev |57| pgvector | Via Supabase | Yes | BM25 separate | Already using Postgres |58| Qdrant | Yes | Yes | Yes | High-performance, filtering |5960### Step 5: Design Retrieval Pipeline6162Build the query-time pipeline:631. **Query preprocessing:** Expand abbreviations, detect intent, generate sub-queries642. **Embedding:** Encode query with same model used for documents653. **Initial retrieval:** Top-K vector search (K=20-50)664. **Reranking:** Cross-encoder reranker to reorder by relevance (return top 5-10)675. **Context assembly:** Combine retrieved chunks into a prompt, add metadata686. **Generation:** LLM call with assembled context + user query6970### Step 6: Design Quality Metrics7172Define how to measure RAG quality:73- **Retrieval metrics:** Recall@K (are relevant docs in top K?), MRR (is the best doc ranked first?)74- **Generation metrics:** Faithfulness (does the answer stick to context?), relevance (does it answer the question?)75- **End-to-end:** Answer accuracy on golden dataset, hallucination rate76- **Monitoring:** Track retrieval scores over time, flag low-confidence answers7778## Output Format7980```markdown81# RAG Architecture8283## Source Analysis84| Attribute | Value |85|-----------|-------|86| Document types | [Types] |87| Corpus size | [Size] |88| Update frequency | [Frequency] |8990## Chunking Strategy91**Method:** [Fixed/Semantic/Hierarchical]92**Target chunk size:** [X tokens]93**Overlap:** [X tokens]94**Metadata:** [Fields attached to each chunk]9596## Embedding Pipeline97**Model:** [Name]98**Dimensions:** [N]99**Cost:** [$X per 1M tokens]100**Batch processing:** [Strategy for initial load vs incremental updates]101102## Vector Database103**Choice:** [Database]104**Rationale:** [Why this DB]105**Index configuration:** [HNSW params, quantization, etc.]106**Hybrid search:** [BM25 + vector approach]107108## Retrieval Pipeline109```110Query → [Preprocess] → [Embed] → [Vector Search (top 20)] → [Rerank (top 5)] → [Assemble Context] → [LLM] → [Validate] → Response111```112113| Stage | Latency | Cost |114|-------|---------|------|115| Embedding | Xms | $X |116| Vector search | Xms | $X |117| Reranking | Xms | $X |118| Generation | Xms | $X |119| **Total** | **Xms** | **$X** |120121## Quality Metrics122| Metric | Target | Measurement |123|--------|--------|-------------|124| Recall@10 | >90% | Golden dataset |125| Faithfulness | >95% | Automated scoring |126| Hallucination rate | <5% | Reference checking |127128## Cost Model129| Component | Monthly Cost (at X queries/day) |130|-----------|-------------------------------|131| Embeddings | $X |132| Vector DB | $X |133| Reranking | $X |134| Generation | $X |135| **Total** | **$X** |136```137138## Quality Checks139140- [ ] Chunking strategy is justified against document structure (not just default 500 tokens)141- [ ] Embedding model matches the query language and domain142- [ ] Retrieval pipeline includes reranking (not just raw vector similarity)143- [ ] Cost model accounts for both indexing and query costs144- [ ] Quality metrics have defined targets and measurement approach145- [ ] Update strategy handles incremental changes (not re-index everything)146- [ ] Latency budget is broken down by pipeline stage147148## Evolution Notes149<!-- Observations appended after each use -->