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-architecture3department: "oracle"4description: "Chunking strategies, embedding pipelines, vector DB selection, and retrieval optimization"5version: 16triggers:7 - "RAG"8 - "retrieval"9 - "embedding"10 - "vector"11 - "chunking"12 - "semantic search"13 - "Pinecone"14 - "ChromaDB"15 - "Weaviate"16 - "reranking"17---1819# RAG Architecture2021## Purpose2223Design a Retrieval-Augmented Generation pipeline, including document processing, chunking strategy, embedding pipeline, vector database selection, retrieval optimization, and context assembly.2425## Inputs2627- Source documents (type, volume, update frequency)28- Query patterns (user questions, search terms, structured queries)29- Quality requirements (relevance threshold, hallucination tolerance)30- Latency requirements (real-time, near-real-time, batch)31- Cost constraints (embedding costs, storage costs, query costs)3233## Process3435### Step 1: Analyze Source Documents3637Understand what's being indexed:38- **Document types:** PDFs, web pages, code, structured data, conversations39- **Volume:** Number of documents, total size, growth rate40- **Update frequency:** Static corpus, daily updates, real-time41- **Structure:** Highly structured (tables, headers) vs unstructured (prose, transcripts)42- **Quality:** Clean text vs noisy (OCR artifacts, HTML remnants, duplicates)4344### Step 2: Design Chunking Strategy4546Choose how to split documents:47- **Fixed-size:** 500-1000 tokens with 100-200 token overlap. Simple but may split concepts.48- **Semantic:** Split on paragraph/section boundaries. Preserves meaning but variable size.49- **Hierarchical:** Parent-child chunks (section summary + detail chunks). Best for complex docs.50- **Recursive:** Start large, recursively split until chunks fit size target.51- **Metadata enrichment:** Attach source, section title, page number to each chunk.5253### Step 3: Select Embedding Model5455Choose the embedding approach:56- **OpenAI text-embedding-3-small/large:** Best general-purpose, 1536/3072 dimensions57- **Cohere embed-v3:** Strong multilingual, supports search and classification modes58- **Open source (BGE, E5):** Self-hosted, lower cost at scale, variable quality59- **Considerations:** Dimension size (storage), context length, multilingual support, cost per token6061### Step 4: Select Vector Database6263Choose storage and retrieval:6465| Database | Hosted | Open Source | Hybrid Search | Best For |66|----------|--------|------------|---------------|----------|67| Pinecone | Yes | No | Yes (sparse+dense) | Production, managed |68| Weaviate | Yes | Yes | Yes (BM25+vector) | Self-hosted, rich filtering |69| ChromaDB | No | Yes | No | Prototyping, local dev |70| pgvector | Via Supabase | Yes | BM25 separate | Already using Postgres |71| Qdrant | Yes | Yes | Yes | High-performance, filtering |7273### Step 5: Design Retrieval Pipeline7475Build the query-time pipeline:761. **Query preprocessing:** Expand abbreviations, detect intent, generate sub-queries772. **Embedding:** Encode query with same model used for documents783. **Initial retrieval:** Top-K vector search (K=20-50)794. **Reranking:** Cross-encoder reranker to reorder by relevance (return top 5-10)805. **Context assembly:** Combine retrieved chunks into a prompt, add metadata816. **Generation:** LLM call with assembled context + user query8283### Step 6: Design Quality Metrics8485Define how to measure RAG quality:86- **Retrieval metrics:** Recall@K (are relevant docs in top K?), MRR (is the best doc ranked first?)87- **Generation metrics:** Faithfulness (does the answer stick to context?), relevance (does it answer the question?)88- **End-to-end:** Answer accuracy on golden dataset, hallucination rate89- **Monitoring:** Track retrieval scores over time, flag low-confidence answers9091## Output Format9293```markdown94# RAG Architecture9596## Source Analysis97| Attribute | Value |98|-----------|-------|99| Document types | [Types] |100| Corpus size | [Size] |101| Update frequency | [Frequency] |102103## Chunking Strategy104**Method:** [Fixed/Semantic/Hierarchical]105**Target chunk size:** [X tokens]106**Overlap:** [X tokens]107**Metadata:** [Fields attached to each chunk]108109## Embedding Pipeline110**Model:** [Name]111**Dimensions:** [N]112**Cost:** [$X per 1M tokens]113**Batch processing:** [Strategy for initial load vs incremental updates]114115## Vector Database116**Choice:** [Database]117**Rationale:** [Why this DB]118**Index configuration:** [HNSW params, quantization, etc.]119**Hybrid search:** [BM25 + vector approach]120121## Retrieval Pipeline122```123Query → [Preprocess] → [Embed] → [Vector Search (top 20)] → [Rerank (top 5)] → [Assemble Context] → [LLM] → [Validate] → Response124```125126| Stage | Latency | Cost |127|-------|---------|------|128| Embedding | Xms | $X |129| Vector search | Xms | $X |130| Reranking | Xms | $X |131| Generation | Xms | $X |132| **Total** | **Xms** | **$X** |133134## Quality Metrics135| Metric | Target | Measurement |136|--------|--------|-------------|137| Recall@10 | >90% | Golden dataset |138| Faithfulness | >95% | Automated scoring |139| Hallucination rate | <5% | Reference checking |140141## Cost Model142| Component | Monthly Cost (at X queries/day) |143|-----------|-------------------------------|144| Embeddings | $X |145| Vector DB | $X |146| Reranking | $X |147| Generation | $X |148| **Total** | **$X** |149```150151## Quality Checks152153- [ ] Chunking strategy is justified against document structure (not just default 500 tokens)154- [ ] Embedding model matches the query language and domain155- [ ] Retrieval pipeline includes reranking (not just raw vector similarity)156- [ ] Cost model accounts for both indexing and query costs157- [ ] Quality metrics have defined targets and measurement approach158- [ ] Update strategy handles incremental changes (not re-index everything)159- [ ] Latency budget is broken down by pipeline stage160161## Evolution Notes162<!-- Observations appended after each use -->