RAG Implementer
Build production-ready retrieval-augmented generation systems.
Core Principle
RAG = Retrieval + Context Assembly + Generation
Use RAG when you need LLMs to access fresh, domain-specific, or proprietary knowledge that wasn't in their training data.
⚠️ Prerequisites & Cost Reality Check
STOP: Have You Validated the Need for RAG?
Before implementing RAG, confirm:
Try These FIRST (Before RAG)
RAG is powerful but expensive. Try cheaper alternatives first:
1. FAQ Page / Documentation (1 day, $0)
- Create well-organized FAQ or docs
- Add search with Cmd+F
- Works for: <50 common questions, static content
- Test: Do users find answers? If yes, stop here.
2. Simple Keyword Search (2-3 days, $0-20/month)
- Use Algolia, Typesense, or PostgreSQL full-text search
- Good enough for 80% of use cases
- Works for: <100k documents, keyword matching sufficient
- Test: Do users get relevant results? If yes, stop here.
3. Manual Curation (Concierge MVP) (1 week, $0)
- Manually answer user questions
- Build FAQ from common questions
- Works for: <100 users, validating if users want AI
- Test: Do users value your answers enough to pay? If yes, consider RAG.
4. Simple Semantic Search (1 week, $30-50/month)
- Use OpenAI embeddings + Postgres pgvector
- Skip complex retrieval, re-ranking, etc.
- Works for: <50k documents, basic semantic search
- Test: Are embeddings better than keyword search? If no, stop here.
Cost Reality Check
Naive RAG (Prototype):
- Time: 1-2 weeks
- Cost: $50-150/month (vector DB + embeddings + API calls)
- When: Prototype, <10k documents, proof of concept
Advanced RAG (Production):
- Time: 3-4 weeks
- Cost: $200-500/month (hybrid search, re-ranking, monitoring)
- When: Production, 10k-1M documents, validated demand
Modular RAG (Enterprise):
- Time: 6-8 weeks
- Cost: $500-2000+/month (multiple KBs, specialized modules)
- When: Enterprise, 1M+ documents, mission-critical
Decision Tree: Do You Really Need RAG?
Do users need to search your content?
│
├─ No → Don't build RAG ❌
│
└─ Yes
├─ <50 items? → FAQ page ✅ ($0)
│
└─ >50 items?
├─ Keyword search enough? → Use Algolia ✅ ($0-20/mo)
│
└─ Need semantic understanding?
├─ <50k docs? → Simple semantic (pgvector) ✅ ($30/mo)
│
└─ >50k docs?
├─ Validated with users? → Build RAG ✅
└─ Not validated? → Test with Concierge MVP first ⚠️
Validation Checklist
Only proceed with RAG implementation if:
If any checkbox is unchecked: Go back to product-strategist or mvp-builder skills to validate first.
See also: PLAYBOOKS/validation-first-development.md for step-by-step validation process.
8-Phase RAG Implementation
Phase 1: Knowledge Base Design
Goal: Create well-structured knowledge foundation
Actions:
- Map data sources (internal: docs, databases, APIs / external: web, feeds)
- Filter noise, select authoritative content (prevent "data dump fallacy")
- Define chunking strategy: semantic chunking based on structure
- Add metadata: tags, timestamps, source identifiers, categories
Validation:
Common Chunking Strategies:
- Fixed-size: 500-1000 tokens, 50-100 token overlap
- Semantic: By paragraph, section headers, or topic boundaries
- Recursive: Split by structure (markdown headers, code blocks)
Phase 2: Embedding Strategy
Goal: Choose optimal embedding approach for semantic understanding
Actions:
- Select embedding model:
text-embedding-3-large (1536 dim) for general, domain-specific for specialized
- Plan multi-modal needs (text, code, images, tables)
- Decide on fine-tuning: use domain data if general embeddings underperform
- Establish similarity benchmarks
Validation:
Model Selection:
- General: OpenAI
text-embedding-3-large, text-embedding-3-small
- Code:
code-search-babbage-code-001 or StarEncoder
- Multilingual:
multilingual-e5-large
Phase 3: Vector Store Architecture
Goal: Implement scalable vector database
Actions:
- Choose vector DB (Pinecone, Weaviate, Qdrant, Chroma, pgvector)
- Configure index: HNSW for speed, IVF for scale
- Plan scalability: data growth and query volume
- Implement backup, recovery, security
Validation:
Vector DB Decision:
- Managed cloud → Pinecone
- Self-hosted, feature-rich → Weaviate
- Lightweight, local → Chroma
- Cost-conscious → pgvector (Postgres extension)
- High-performance → Qdrant
Phase 4: Retrieval Pipeline
Goal: Build sophisticated retrieval beyond simple similarity search
Actions:
- Implement hybrid retrieval: semantic search + keyword (BM25)
- Add query enhancement: expansion, reformulation, multi-query
- Apply contextual filtering: metadata, temporal constraints, relevance ranking
- Design for query types: factual (precision), analytical (breadth), creative (diversity)
- Handle edge cases: no relevant results found
Advanced Techniques:
- Re-ranking: Use cross-encoder after initial retrieval (e.g.,
cross-encoder/ms-marco-MiniLM-L-12-v2)
- Query routing: Route different query types to specialized strategies
- Ensemble methods: Combine multiple retrieval approaches
- Adaptive retrieval: Adjust top-k based on query complexity
Validation:
Phase 5: Context Assembly
Goal: Transform retrieved chunks into optimal LLM context
Actions:
- Rank and select: prioritize by relevance score, recency, source authority
- Synthesize: merge related chunks, avoid redundancy
- Compress: use LLMLingua or similar for token optimization
- Mitigate "lost in the middle": place critical info at start/end
- Adapt dynamically: adjust context based on conversation history
Context Engineering Integration:
- Blend RAG results with system instructions and user prompts
- Maintain conversation coherence across multi-turn interactions
- Implement context persistence for follow-up queries
- Balance context size vs. information density
Validation:
Phase 6: Evaluation & Metrics
Goal: Measure RAG system performance comprehensively
Retrieval Quality:
- Precision@K: Fraction of top-K results that are relevant
- Recall@K: Fraction of relevant docs in top-K
- MRR (Mean Reciprocal Rank): Average rank of first relevant result
- NDCG: Ranking quality with graded relevance
Generation Quality:
- Faithfulness: Generated content accuracy vs. sources
- Answer Relevance: Response relevance to query
- Context Utilization: How effectively LLM uses retrieved info
- Hallucination Rate: Frequency of unsupported claims
System Performance:
- End-to-End Latency: Query to answer (<3 seconds target)
- Retrieval Latency: Time to retrieve and rank (<500ms)
- Token Efficiency: Information density per token
- Cost Per Query: Combined retrieval + generation costs
Validation:
Phase 7: Production Deployment
Goal: Deploy with enterprise-grade reliability and security
Deployment:
- Containerize with Docker/Kubernetes
- Implement load balancing across RAG instances
- Add caching for frequent queries
- Graceful degradation: fallback to base model on component failure
Security:
- Role-based access controls for knowledge base
- Data masking and PII protection
- Audit logging for compliance
- Prompt injection defense
Monitoring:
- Real-time metrics dashboard (latency, cost, accuracy)
- Query analysis for patterns and failure modes
- Cost tracking and optimization alerts
- Performance profiling for bottlenecks
Validation:
Phase 8: Continuous Improvement
Goal: Establish processes for ongoing enhancement
Data Pipeline:
- Automated knowledge base updates (real-time or scheduled)
- Quality monitoring: detect data drift and degradation
- Source diversification: add new data sources
- Feedback integration: user corrections and preferences
Model Evolution:
- Evaluate and migrate to improved embeddings
- Fine-tune on domain data regularly
- Upgrade architecture: Naive → Advanced → Modular RAG
- Expand multi-modal support (images, audio, video)
Optimization:
- Analyze query patterns, optimize for common needs
- Improve cache hit rates
- Tune vector indices regularly
- Balance performance vs. costs
Validation:
Key RAG Principles
1. Relevance Over Volume
- Quality curation > massive datasets
- Remove outdated/low-quality content continuously
- Prioritize most relevant info to prevent "lost in the middle"
2. Semantic Understanding
- Use embeddings for true semantic matching, not just keywords
- Recognize query intent (factual, analytical, creative)
- Adapt retrieval strategy based on context
3. Multi-Modal Intelligence
- Handle text, images, code, tables, structured data
- Enable cross-modal retrieval (text query → image results)
- Preserve document structure and formatting
4. Temporal Awareness
- Prioritize recent info for time-sensitive topics
- Maintain historical access when relevant
- Integrate real-time data feeds for dynamic domains
5. Transparency & Trust
- Always provide source citations
- Indicate confidence levels
- Explain why specific information was selected
Standard RAG Response Format
{
"answer": "Generated response incorporating retrieved information",
"sources": [
{
"content": "Retrieved text chunk",
"source": "Document/URL identifier",
"relevance_score": 0.95,
"chunk_id": "unique_identifier"
}
],
"confidence": 0.87,
"retrieval_metadata": {
"chunks_retrieved": 5,
"retrieval_time_ms": 150,
"generation_time_ms": 800
}
}
Critical Success Rules
Non-Negotiable:
- ✅ Source attribution for every response
- ✅ Validate generated content against sources (prevent hallucination)
- ✅ Filter sensitive data before retrieval
- ✅ Respond within latency thresholds (<3 seconds)
- ✅ Monitor and optimize costs continuously
- ✅ Comply with security policies
- ✅ Graceful degradation on failures
- ✅ Comprehensive testing before production
Quality Gates:
- Before Production: >85% accuracy on evaluation dataset
- Ongoing: User satisfaction >4.0/5.0
- Performance: 95th percentile <5 seconds
- Reliability: 99.5% uptime
- Cost: Within 10% of budget
Advanced Patterns
Modular RAG Architecture
- Search Module: Query understanding and reformulation
- Memory Module: Long-term conversation persistence
- Routing Module: Query routing to specialized knowledge bases
- Predict Module: Anticipatory pre-loading based on context
Hybrid RAG + Fine-tuning
- RAG for dynamic, frequently changing knowledge
- Fine-tuning for domain-specific reasoning patterns
- Combine strengths for maximum effectiveness
Related Resources
Related Skills:
multi-agent-architect - For complex RAG orchestration
knowledge-graph-builder - For structured knowledge integration
performance-optimizer - For RAG system optimization
Related Patterns:
META/DECISION-FRAMEWORK.md - Vector DB and embedding selection
STANDARDS/architecture-patterns/rag-pattern.md - RAG architecture details (when created)
Related Playbooks:
PLAYBOOKS/deploy-rag-system.md - RAG deployment procedure (when created)
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: rag-implementer3description: Implement retrieval-augmented generation systems. Use when building knowledge-intensive applications, document search, Q&A systems, or need to ground LLM responses in external data. Covers embedding strategy, vector stores, retrieval pipelines, and evaluation. Use when this capability is needed.4---56# RAG Implementer78Build production-ready retrieval-augmented generation systems.910## Core Principle1112**RAG = Retrieval + Context Assembly + Generation**1314Use RAG when you need LLMs to access fresh, domain-specific, or proprietary knowledge that wasn't in their training data.1516---1718## ⚠️ Prerequisites & Cost Reality Check1920### STOP: Have You Validated the Need for RAG?2122**Before implementing RAG, confirm:**2324- [ ] **Problem validated** - Completed `product-strategist` Phase 1 (problem discovery)25- [ ] **Users need AI search** - Tested with simpler alternatives (see below)26- [ ] **ROI justified** - Calculated cost vs benefit of RAG vs alternatives2728### Try These FIRST (Before RAG)2930RAG is powerful but expensive. Try cheaper alternatives first:3132**1. FAQ Page / Documentation (1 day, $0)**3334- Create well-organized FAQ or docs35- Add search with Cmd+F36- **Works for:** <50 common questions, static content37- **Test:** Do users find answers? If yes, stop here.3839**2. Simple Keyword Search (2-3 days, $0-20/month)**4041- Use Algolia, Typesense, or PostgreSQL full-text search42- Good enough for 80% of use cases43- **Works for:** <100k documents, keyword matching sufficient44- **Test:** Do users get relevant results? If yes, stop here.4546**3. Manual Curation (Concierge MVP) (1 week, $0)**4748- Manually answer user questions49- Build FAQ from common questions50- **Works for:** <100 users, validating if users want AI51- **Test:** Do users value your answers enough to pay? If yes, consider RAG.5253**4. Simple Semantic Search (1 week, $30-50/month)**5455- Use OpenAI embeddings + Postgres pgvector56- Skip complex retrieval, re-ranking, etc.57- **Works for:** <50k documents, basic semantic search58- **Test:** Are embeddings better than keyword search? If no, stop here.5960### Cost Reality Check6162**Naive RAG (Prototype):**6364- **Time:** 1-2 weeks65- **Cost:** $50-150/month (vector DB + embeddings + API calls)66- **When:** Prototype, <10k documents, proof of concept6768**Advanced RAG (Production):**6970- **Time:** 3-4 weeks71- **Cost:** $200-500/month (hybrid search, re-ranking, monitoring)72- **When:** Production, 10k-1M documents, validated demand7374**Modular RAG (Enterprise):**7576- **Time:** 6-8 weeks77- **Cost:** $500-2000+/month (multiple KBs, specialized modules)78- **When:** Enterprise, 1M+ documents, mission-critical7980### Decision Tree: Do You Really Need RAG?8182```83Do users need to search your content?84│85├─ No → Don't build RAG ❌86│87└─ Yes88 ├─ <50 items? → FAQ page ✅ ($0)89 │90 └─ >50 items?91 ├─ Keyword search enough? → Use Algolia ✅ ($0-20/mo)92 │93 └─ Need semantic understanding?94 ├─ <50k docs? → Simple semantic (pgvector) ✅ ($30/mo)95 │96 └─ >50k docs?97 ├─ Validated with users? → Build RAG ✅98 └─ Not validated? → Test with Concierge MVP first ⚠️99```100101### Validation Checklist102103Only proceed with RAG implementation if:104105- [ ] Tested simpler alternatives (FAQ, keyword search, manual curation)106- [ ] Users confirmed they need AI-powered search (not just you think they do)107- [ ] Calculated ROI: cost of RAG < value users get108- [ ] Have >50k documents OR complex semantic search requirements109- [ ] Budget: $200-500/month for infrastructure110- [ ] Time: 3-4 weeks for production implementation111112**If any checkbox is unchecked:** Go back to `product-strategist` or `mvp-builder` skills to validate first.113114**See also:** `PLAYBOOKS/validation-first-development.md` for step-by-step validation process.115116---117118## 8-Phase RAG Implementation119120### Phase 1: Knowledge Base Design121122**Goal**: Create well-structured knowledge foundation123124**Actions**:125126- Map data sources (internal: docs, databases, APIs / external: web, feeds)127- Filter noise, select authoritative content (prevent "data dump fallacy")128- Define chunking strategy: semantic chunking based on structure129- Add metadata: tags, timestamps, source identifiers, categories130131**Validation**:132133- [ ] All data sources catalogued and prioritized134- [ ] Data quality assessed (accuracy, completeness, freshness)135- [ ] Chunking strategy tested with sample documents136- [ ] Metadata schema validated for search effectiveness137138**Common Chunking Strategies**:139140- Fixed-size: 500-1000 tokens, 50-100 token overlap141- Semantic: By paragraph, section headers, or topic boundaries142- Recursive: Split by structure (markdown headers, code blocks)143144---145146### Phase 2: Embedding Strategy147148**Goal**: Choose optimal embedding approach for semantic understanding149150**Actions**:151152- Select embedding model: `text-embedding-3-large` (1536 dim) for general, domain-specific for specialized153- Plan multi-modal needs (text, code, images, tables)154- Decide on fine-tuning: use domain data if general embeddings underperform155- Establish similarity benchmarks156157**Validation**:158159- [ ] Embedding model benchmarked on domain data160- [ ] Retrieval accuracy tested with known query-document pairs161- [ ] Storage and compute costs validated162163**Model Selection**:164165- General: OpenAI `text-embedding-3-large`, `text-embedding-3-small`166- Code: `code-search-babbage-code-001` or StarEncoder167- Multilingual: `multilingual-e5-large`168169---170171### Phase 3: Vector Store Architecture172173**Goal**: Implement scalable vector database174175**Actions**:176177- Choose vector DB (Pinecone, Weaviate, Qdrant, Chroma, pgvector)178- Configure index: HNSW for speed, IVF for scale179- Plan scalability: data growth and query volume180- Implement backup, recovery, security181182**Validation**:183184- [ ] Vector store benchmarked under expected load185- [ ] Index optimized for retrieval speed and accuracy186- [ ] Backup and recovery tested187- [ ] Security controls implemented188189**Vector DB Decision**:190191- Managed cloud → Pinecone192- Self-hosted, feature-rich → Weaviate193- Lightweight, local → Chroma194- Cost-conscious → pgvector (Postgres extension)195- High-performance → Qdrant196197---198199### Phase 4: Retrieval Pipeline200201**Goal**: Build sophisticated retrieval beyond simple similarity search202203**Actions**:204205- Implement hybrid retrieval: semantic search + keyword (BM25)206- Add query enhancement: expansion, reformulation, multi-query207- Apply contextual filtering: metadata, temporal constraints, relevance ranking208- Design for query types: factual (precision), analytical (breadth), creative (diversity)209- Handle edge cases: no relevant results found210211**Advanced Techniques**:212213- **Re-ranking**: Use cross-encoder after initial retrieval (e.g., `cross-encoder/ms-marco-MiniLM-L-12-v2`)214- **Query routing**: Route different query types to specialized strategies215- **Ensemble methods**: Combine multiple retrieval approaches216- **Adaptive retrieval**: Adjust top-k based on query complexity217218**Validation**:219220- [ ] Retrieval accuracy tested across diverse query types221- [ ] Hybrid retrieval outperforms single-method baselines222- [ ] Query latency meets requirements (<500ms ideal)223- [ ] Edge cases and fallbacks tested224225---226227### Phase 5: Context Assembly228229**Goal**: Transform retrieved chunks into optimal LLM context230231**Actions**:232233- Rank and select: prioritize by relevance score, recency, source authority234- Synthesize: merge related chunks, avoid redundancy235- Compress: use LLMLingua or similar for token optimization236- Mitigate "lost in the middle": place critical info at start/end237- Adapt dynamically: adjust context based on conversation history238239**Context Engineering Integration**:240241- Blend RAG results with system instructions and user prompts242- Maintain conversation coherence across multi-turn interactions243- Implement context persistence for follow-up queries244- Balance context size vs. information density245246**Validation**:247248- [ ] Context relevance validated against human judgments249- [ ] Token optimization maintains accuracy250- [ ] Multi-turn conversations maintain coherence251- [ ] Assembly latency <200ms252253---254255### Phase 6: Evaluation & Metrics256257**Goal**: Measure RAG system performance comprehensively258259**Retrieval Quality**:260261- **Precision@K**: Fraction of top-K results that are relevant262- **Recall@K**: Fraction of relevant docs in top-K263- **MRR (Mean Reciprocal Rank)**: Average rank of first relevant result264- **NDCG**: Ranking quality with graded relevance265266**Generation Quality**:267268- **Faithfulness**: Generated content accuracy vs. sources269- **Answer Relevance**: Response relevance to query270- **Context Utilization**: How effectively LLM uses retrieved info271- **Hallucination Rate**: Frequency of unsupported claims272273**System Performance**:274275- **End-to-End Latency**: Query to answer (<3 seconds target)276- **Retrieval Latency**: Time to retrieve and rank (<500ms)277- **Token Efficiency**: Information density per token278- **Cost Per Query**: Combined retrieval + generation costs279280**Validation**:281282- [ ] Baseline metrics established283- [ ] A/B testing framework for config comparisons284- [ ] Automated evaluation pipeline deployed285- [ ] Human evaluation protocols for ground truth286287---288289### Phase 7: Production Deployment290291**Goal**: Deploy with enterprise-grade reliability and security292293**Deployment**:294295- Containerize with Docker/Kubernetes296- Implement load balancing across RAG instances297- Add caching for frequent queries298- Graceful degradation: fallback to base model on component failure299300**Security**:301302- Role-based access controls for knowledge base303- Data masking and PII protection304- Audit logging for compliance305- Prompt injection defense306307**Monitoring**:308309- Real-time metrics dashboard (latency, cost, accuracy)310- Query analysis for patterns and failure modes311- Cost tracking and optimization alerts312- Performance profiling for bottlenecks313314**Validation**:315316- [ ] Production handles expected traffic317- [ ] Security prevents unauthorized access318- [ ] Monitoring provides actionable insights319- [ ] Incident response procedures tested320321---322323### Phase 8: Continuous Improvement324325**Goal**: Establish processes for ongoing enhancement326327**Data Pipeline**:328329- Automated knowledge base updates (real-time or scheduled)330- Quality monitoring: detect data drift and degradation331- Source diversification: add new data sources332- Feedback integration: user corrections and preferences333334**Model Evolution**:335336- Evaluate and migrate to improved embeddings337- Fine-tune on domain data regularly338- Upgrade architecture: Naive → Advanced → Modular RAG339- Expand multi-modal support (images, audio, video)340341**Optimization**:342343- Analyze query patterns, optimize for common needs344- Improve cache hit rates345- Tune vector indices regularly346- Balance performance vs. costs347348**Validation**:349350- [ ] Automated improvement pipelines functioning351- [ ] Performance trends show improvement352- [ ] User satisfaction increasing353- [ ] System adapts to changing needs354355## Key RAG Principles356357### 1. Relevance Over Volume358359- Quality curation > massive datasets360- Remove outdated/low-quality content continuously361- Prioritize most relevant info to prevent "lost in the middle"362363### 2. Semantic Understanding364365- Use embeddings for true semantic matching, not just keywords366- Recognize query intent (factual, analytical, creative)367- Adapt retrieval strategy based on context368369### 3. Multi-Modal Intelligence370371- Handle text, images, code, tables, structured data372- Enable cross-modal retrieval (text query → image results)373- Preserve document structure and formatting374375### 4. Temporal Awareness376377- Prioritize recent info for time-sensitive topics378- Maintain historical access when relevant379- Integrate real-time data feeds for dynamic domains380381### 5. Transparency & Trust382383- Always provide source citations384- Indicate confidence levels385- Explain why specific information was selected386387## Standard RAG Response Format388389```json390{391 "answer": "Generated response incorporating retrieved information",392 "sources": [393 {394 "content": "Retrieved text chunk",395 "source": "Document/URL identifier",396 "relevance_score": 0.95,397 "chunk_id": "unique_identifier"398 }399 ],400 "confidence": 0.87,401 "retrieval_metadata": {402 "chunks_retrieved": 5,403 "retrieval_time_ms": 150,404 "generation_time_ms": 800405 }406}407```408409## Critical Success Rules410411**Non-Negotiable**:4124131. ✅ Source attribution for every response4142. ✅ Validate generated content against sources (prevent hallucination)4153. ✅ Filter sensitive data before retrieval4164. ✅ Respond within latency thresholds (<3 seconds)4175. ✅ Monitor and optimize costs continuously4186. ✅ Comply with security policies4197. ✅ Graceful degradation on failures4208. ✅ Comprehensive testing before production421422**Quality Gates**:423424- Before Production: >85% accuracy on evaluation dataset425- Ongoing: User satisfaction >4.0/5.0426- Performance: 95th percentile <5 seconds427- Reliability: 99.5% uptime428- Cost: Within 10% of budget429430## Advanced Patterns431432### Modular RAG Architecture433434- **Search Module**: Query understanding and reformulation435- **Memory Module**: Long-term conversation persistence436- **Routing Module**: Query routing to specialized knowledge bases437- **Predict Module**: Anticipatory pre-loading based on context438439### Hybrid RAG + Fine-tuning440441- RAG for dynamic, frequently changing knowledge442- Fine-tuning for domain-specific reasoning patterns443- Combine strengths for maximum effectiveness444445## Related Resources446447**Related Skills**:448449- `multi-agent-architect` - For complex RAG orchestration450- `knowledge-graph-builder` - For structured knowledge integration451- `performance-optimizer` - For RAG system optimization452453**Related Patterns**:454455- `META/DECISION-FRAMEWORK.md` - Vector DB and embedding selection456- `STANDARDS/architecture-patterns/rag-pattern.md` - RAG architecture details (when created)457458**Related Playbooks**:459460- `PLAYBOOKS/deploy-rag-system.md` - RAG deployment procedure (when created)461462---463> Converted and distributed by [TomeVault](https://tomevault.io/claim/daffy0208) — claim your Tome and manage your conversions.464<!-- tomevault:4.0:skill_md:2026-04-11 -->