[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M76XKTYG6VNWYM71KA4MTDQ7":3,"skill-same:01M76XKTYG6VNWYM71KA4MTDQ7":45},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":25,"repositoryHtmlUrl":26,"repositoryHomepageUrl":27,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":29,"updatedAt":30,"install":31,"resources":44},"01M76XKTYG6VNWYM71KA4MTDQ7","afrexai-rag-production",null,"Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fa\u002Fafrexai-rag-production\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"# RAG Production Engineering\n\n> Complete methodology for building, optimizing, and operating Retrieval-Augmented Generation systems in production. From architecture decisions through chunking strategies, embedding selection, retrieval tuning, evaluation frameworks, and production monitoring.\n\n## Quick Health Check\n\nScore your RAG system (1 = poor, 2 = okay):\n\n| Signal | What to Check |\n|--------|--------------|\n| Retrieval relevance | Top-5 results contain answer >90% of time |\n| Answer accuracy | Generated answers faithful to retrieved context |\n| Latency | End-to-end response \u003C3s (p95) |\n| Chunk quality | Chunks are self-contained, meaningful units |\n| Evaluation coverage | Automated eval suite with 50+ test cases |\n| Index freshness | Documents indexed within SLA of source update |\n| Failure handling | Graceful degradation when retrieval returns nothing |\n| Cost efficiency | Cost per query within budget (\u003C$0.05 typical) |\n\n**Score: \u002F16** — Below 10 = critical issues. Below 12 = significant gaps. 14+ = production-ready.\n\n---\n\n## Phase 1: Architecture Decision\n\n### When to Use RAG (vs Alternatives)\n\n| Approach | Use When | Don't Use When |\n|----------|----------|----------------|\n| **RAG** | Dynamic knowledge, source attribution needed, data changes frequently | Static small dataset (\u003C10 pages), real-time data needed |\n| **Fine-tuning** | Consistent style\u002Fformat needed, domain-specific language | Frequently changing data, need source citations |\n| **Long context** | Small corpus (\u003C200K tokens), simple Q&A | Large corpus, cost-sensitive, need precise attribution |\n| **RAG + Fine-tuning** | Domain-specific language AND dynamic knowledge | Budget-constrained, simple use case |\n| **Agentic RAG** | Multi-step reasoning, tool use, complex queries | Simple lookup, latency-critical |\n\n### RAG Architecture Brief\n\n```yaml\n# Fill this out before building\nproject:\n  name: \"\"\n  use_case: \"\"  # Q&A, search, summarization, analysis, chatbot\n  domain: \"\"    # legal, medical, technical, general\n\ndata:\n  sources: []        # PDF, web, database, API, markdown, code\n  volume: \"\"         # \u003C1K docs, 1K-100K, 100K-1M, >1M\n  update_frequency: \"\" # real-time, daily, weekly, static\n  avg_doc_length: \"\" # \u003C1 page, 1-10 pages, 10-100 pages, >100 pages\n  languages: []\n\nrequirements:\n  latency_p95: \"\"    # \u003C1s, \u003C3s, \u003C10s, \u003C30s\n  accuracy_target: \"\" # 85%, 90%, 95%, 99%\n  citations_needed: true\n  access_control: false\n  compliance: []     # GDPR, HIPAA, SOC2, none\n\nbudget:\n  monthly_queries: \"\"\n  cost_per_query_target: \"\"\n  infra_budget: \"\"\n```\n\n### Architecture Patterns\n\n#### Basic RAG\n```\nQuery → Embed → Vector Search → Top-K → LLM → Answer\n```\nBest for: Simple Q&A, \u003C100K documents, single data source.\n\n#### Advanced RAG\n```\nQuery → Classify → Rewrite → Embed → Hybrid Search → Rerank → Filter → LLM → Answer + Citations\n```\nBest for: Production systems, mixed document types, accuracy-critical.\n\n#### Agentic RAG\n```\nQuery → Planner → [Search₁, Search₂, SQL, API] → Synthesize → Verify → Answer\n```\nBest for: Complex multi-step reasoning, multiple data sources, analytical queries.\n\n#### Graph RAG\n```\nQuery → Entity Extract → Graph Traverse → Subgraph → Context Assembly → LLM → Answer\n```\nBest for: Relationship-heavy data (org charts, legal references, knowledge bases).\n\n### Architecture Decision Tree\n\n```\nIs your corpus \u003C 200K tokens?\n  YES → Try long-context first (cheapest, simplest)\n  NO → Continue\n\nDo you need source citations?\n  YES → RAG (not fine-tuning)\n  NO → Consider fine-tuning if style matters\n\nSingle data source, simple queries?\n  YES → Basic RAG\n  NO → Continue\n\nMulti-step reasoning or multiple sources?\n  YES → Agentic RAG\n  NO → Advanced RAG\n```\n\n---\n\n## Phase 2: Document Processing & Chunking\n\n### Document Processing Pipeline\n\n```\nSource → Extract → Clean → Chunk → Enrich → Embed → Index\n```\n\n#### Extraction by Source Type\n\n| Source | Tool\u002FMethod | Gotchas |\n|--------|------------|---------|\n| PDF (text) | PyMuPDF, pdfplumber | Tables break, headers repeat per page |\n| PDF (scanned) | Tesseract, AWS Textract, Azure DI | OCR errors in technical terms |\n| HTML\u002FWeb | BeautifulSoup, Trafilatura | Nav\u002Ffooter pollution, JS-rendered content |\n| Markdown | Direct parse | Frontmatter, relative links |\n| Code | Tree-sitter, AST | Preserve structure, handle imports |\n| Word\u002FPPTX | python-docx, python-pptx | Formatting loss, embedded objects |\n| Database | SQL export | Schema context needed |\n| Audio\u002FVideo | Whisper → text | Timestamp alignment, speaker diarization |\n\n#### Cleaning Checklist\n\n- [ ] Remove headers\u002Ffooters\u002Fpage numbers\n- [ ] Strip navigation, ads, boilerplate\n- [ ] Normalize whitespace and encoding (UTF-8)\n- [ ] Resolve abbreviations in domain text\n- [ ] Handle tables (convert to structured text or separate)\n- [ ] Preserve code blocks with language tags\n- [ ] Remove duplicate content across documents\n- [ ] Extract and preserve metadata (title, author, date, source URL)\n\n### Chunking Strategies\n\n| Strategy | Chunk Size | Best For | Weakness |\n|----------|-----------|----------|----------|\n| **Fixed-size** | 256-512 tokens | Homogeneous text, fast prototyping | Breaks mid-sentence\u002Fthought |\n| **Recursive character** | 256-1024 tokens | General purpose (LangChain default) | May split related paragraphs |\n| **Semantic** | Variable | High-quality retrieval, mixed content | Slower, needs embedding model |\n| **Document structure** | Section-based | Well-structured docs (markdown, HTML) | Uneven chunk sizes |\n| **Sentence window** | 3-5 sentences | Precise retrieval, reranking | More chunks to manage |\n| **Parent-child** | Small retrieve, large context | Best of both worlds | Complex implementation |\n| **Agentic** | Full section\u002Fdoc | Complex reasoning | Higher token cost |\n\n### Chunking Decision Guide\n\n```\nIs your content well-structured (headers, sections)?\n  YES → Document structure chunking\n  NO → Continue\n\nIs retrieval precision critical (legal, medical)?\n  YES → Sentence window + reranking\n  NO → Continue\n\nMixed content types in same corpus?\n  YES → Semantic chunking\n  NO → Recursive character (start here, optimize later)\n```\n\n### Chunking Rules\n\n1. **Always overlap** — 10-20% overlap prevents context loss at boundaries\n2. **Chunk size matters** — Smaller = more precise retrieval, larger = more context. Start at 512 tokens, tune with eval\n3. **Preserve structure** — Don't break tables, code blocks, or lists mid-element\n4. **Include metadata** — Every chunk needs: source document, section title, page\u002Fposition, timestamp\n5. **Test with real queries** — The \"right\" chunk size depends on your actual query patterns\n6. **Parent-child for production** — Retrieve small chunks, expand to parent for LLM context\n\n### Chunk Metadata Schema\n\n```yaml\nchunk:\n  id: \"doc-123-chunk-7\"\n  text: \"...\"\n  metadata:\n    source_id: \"doc-123\"\n    source_title: \"Q3 Financial Report\"\n    source_url: \"https:\u002F\u002F...\"\n    section_title: \"Revenue Analysis\"\n    page_number: 12\n    position: 7           # chunk position in document\n    total_chunks: 23\n    created_at: \"2026-03-24T04:00:00Z\"\n    updated_at: \"2026-03-24T04:00:00Z\"\n    content_type: \"text\"  # text, table, code, image_caption\n    language: \"en\"\n    # Domain-specific\n    access_level: \"internal\"\n    department: \"finance\"\n```\n\n---\n\n## Phase 3: Embedding Models\n\n### Embedding Model Selection\n\n| Model | Dimensions | Context | Speed | Quality | Cost |\n|-------|-----------|---------|-------|---------|------|\n| **text-embedding-3-small** (OpenAI) | 1536 | 8191 | Fast | Good | $0.02\u002F1M tokens |\n| **text-embedding-3-large** (OpenAI) | 3072 | 8191 | Medium | Excellent | $0.13\u002F1M tokens |\n| **Cohere embed-v4** | 1024 | 512 | Fast | Excellent | $0.10\u002F1M tokens |\n| **Voyage-3** | 1024 | 32K | Medium | Excellent | $0.06\u002F1M tokens |\n| **BGE-large-en-v1.5** (open) | 1024 | 512 | Self-host | Very Good | Free (compute) |\n| **GTE-Qwen2** (open) | Various | 8192 | Self-host | Excellent | Free (compute) |\n| **Nomic-embed-text** (open) | 768 | 8192 | Self-host | Good | Free (compute) |\n\n### Selection Rules\n\n1. **Start with OpenAI text-embedding-3-small** — best cost\u002Fquality ratio for most use cases\n2. **Upgrade to large\u002FVoyage-3** when eval shows retrieval gaps\n3. **Use open models** when: data can't leave your infra, cost-sensitive at scale (>10M chunks), need fine-tuning\n4. **Match chunk size to model context** — don't exceed model's context window\n5. **Same model for indexing AND querying** — ALWAYS. Mixing models = broken retrieval\n6. **Benchmark on YOUR data** — MTEB scores don't predict domain-specific performance\n\n### Embedding Best Practices\n\n- **Normalize embeddings** before storing (L2 normalization for cosine similarity)\n- **Batch embed** documents (not one-by-one) for efficiency\n- **Cache embeddings** — re-embedding is expensive and slow\n- **Version your embeddings** — when you change models, re-embed everything\n- **Instruction-prefix for asymmetric models** — some models need \"query: \" vs \"passage: \" prefixes\n- **Dimensionality reduction** — text-embedding-3 models support Matryoshka (lower dims for speed, test quality)\n\n---\n\n## Phase 4: Vector Database & Indexing\n\n### Vector Database Selection\n\n| Database | Type | Scale | Speed | Features | Best For |\n|----------|------|-------|-------|----------|----------|\n| **Pinecone** | Managed | Billions | Fast | Metadata filter, namespaces | Production SaaS, zero-ops |\n| **Weaviate** | Managed\u002FSelf | Millions | Fast | Hybrid search, modules | Mixed search needs |\n| **Qdrant** | Managed\u002FSelf | Billions | Very Fast | Payload filters, sparse vectors | Performance-critical |\n| **Chroma** | Embedded | \u003C1M | Good | Simple API, local | Prototyping, small scale |\n| **pgvector** | Extension | Millions | Good | SQL, existing Postgres | Already have Postgres |\n| **Milvus** | Self-hosted | Billions | Fast | GPU support, hybrid | Large-scale self-hosted |\n| **LanceDB** | Embedded | Millions | Fast | Serverless, multi-modal | Cost-sensitive, serverless |\n\n### Selection Decision\n\n```\nPrototyping or \u003C100K chunks?\n  → Chroma or LanceDB (embedded, no server)\n\nAlready running PostgreSQL?\n  → pgvector (add extension, done)\n\nProduction, want zero-ops?\n  → Pinecone or Weaviate Cloud\n\nNeed hybrid search (vector + keyword)?\n  → Weaviate or Qdrant\n\n>100M vectors, self-hosted?\n  → Milvus or Qdrant\n```\n\n### Indexing Strategy\n\n| Index Type | Speed | Recall | Memory | Use When |\n|-----------|-------|--------|--------|----------|\n| **HNSW** | Very Fast | 95-99% | High | Default choice, \u003C10M vectors |\n| **IVF-PQ** | Fast | 90-95% | Low | >10M vectors, memory-constrained |\n| **Flat\u002FBrute** | Slow | 100% | High | \u003C100K vectors, accuracy-critical |\n| **ScaNN** | Very Fast | 95-99% | Medium | Google ecosystem, large scale |\n\n### Index Configuration Rules\n\n1. **HNSW: M=16, efConstruction=200, efSearch=100** — good defaults, tune from here\n2. **Build index AFTER bulk loading** — not during insertion\n3. **Use metadata filters BEFORE vector search** — reduces search space dramatically\n4. **Namespace\u002Fcollection per tenant** — for multi-tenant access control\n5. **Monitor index health** — fragmentation, query latency percentiles\n\n---\n\n## Phase 5: Retrieval Engineering\n\n### Query Processing Pipeline\n\n```\nUser Query\n  → Query Understanding (classify intent)\n  → Query Transformation (rewrite, expand, decompose)\n  → Retrieval (vector + keyword + filters)\n  → Post-Retrieval (rerank, filter, deduplicate)\n  → Context Assembly (order, truncate, format)\n  → LLM Generation\n  → Post-Processing (citations, formatting)\n```\n\n### Query Transformation Techniques\n\n| Technique | What It Does | When to Use |\n|-----------|-------------|-------------|\n| **Query rewriting** | LLM rewrites for better retrieval | Conversational queries, vague questions |\n| **HyDE** | Generate hypothetical answer, embed that | Semantic gap between query and docs |\n| **Query decomposition** | Break complex query into sub-queries | Multi-part questions |\n| **Step-back prompting** | Ask a more general question first | Specific queries that miss context |\n| **Query expansion** | Add synonyms\u002Frelated terms | Domain jargon, acronyms |\n| **Multi-query** | Generate N query variants, union results | Improve recall for ambiguous queries |\n\n### Hybrid Search\n\nCombine vector similarity with keyword matching for best results:\n\n```\nScore = α × vector_score + (1 - α) × bm25_score\n```\n\n**Tuning α:**\n- α = 0.7 (default) — mostly semantic, some keyword\n- α = 0.5 — equal weight (good for technical docs with specific terms)\n- α = 0.3 — mostly keyword (good for exact match needs, codes, IDs)\n\n### Reranking\n\nReranking dramatically improves precision. Retrieve more (top-20), rerank to fewer (top-5).\n\n| Reranker | Quality | Speed | Cost |\n|----------|---------|-------|------|\n| **Cohere Rerank** | Excellent | Fast | $2\u002F1K queries |\n| **Voyage Rerank** | Excellent | Fast | $0.05\u002F1M tokens |\n| **BGE-reranker-v2** | Very Good | Self-host | Free (compute) |\n| **Cross-encoder** | Best | Slow | Free (compute) |\n| **ColBERT** | Very Good | Medium | Free (compute) |\n| **LLM-as-reranker** | Excellent | Slow | API cost |\n\n### Retrieval Rules\n\n1. **Always rerank** in production — it's the highest-ROI improvement\n2. **Retrieve more, show less** — fetch top-20, rerank to top-5\n3. **Hybrid search > pure vector** — keyword matching catches what embeddings miss\n4. **Filter before search** — metadata filters (date, department, access level) reduce noise\n5. **Deduplicate** — same content from different sources = wasted context\n6. **Set similarity threshold** — don't return irrelevant results (typical: 0.7 for cosine)\n7. **Return \"I don't know\"** — when no chunk meets threshold, say so. Never hallucinate from thin context\n\n---\n\n## Phase 6: Context Assembly & Generation\n\n### Context Window Management\n\n```yaml\ncontext_budget:\n  total_tokens: 128000      # Model context window\n  system_prompt: 2000       # Instructions, persona, rules\n  retrieved_context: 80000  # Retrieved chunks\n  conversation_history: 20000  # Prior turns\n  generation_buffer: 26000  # Room for response\n```\n\n### Context Assembly Rules\n\n1. **Order matters** — put most relevant chunks first (LLMs attend more to beginning)\n2. **Include source metadata** — chunk source, page number in context\n3. **Separate chunks clearly** — use delimiters (`---` or `[Source: doc-title, page 5]`)\n4. **Don't exceed budget** — truncate least-relevant chunks, never the most relevant\n5. **Include diversity** — if top-5 chunks are from same doc, include from other sources too\n\n### Generation Prompt Template\n\n```\nYou are a helpful assistant. Answer the user's question using ONLY the provided context.\n\nRules:\n- If the context doesn't contain the answer, say \"I don't have enough information to answer that.\"\n- Cite sources using [Source: title] format\n- Never make up information not in the context\n- If the answer spans multiple sources, synthesize and cite all\n\nContext:\n---\n[Source: {title_1}, Page {page_1}]\n{chunk_text_1}\n\n[Source: {title_2}, Page {page_2}]\n{chunk_text_2}\n---\n\nUser question: {query}\n```\n\n### Citation Strategies\n\n| Strategy | Quality | Complexity | Best For |\n|----------|---------|-----------|----------|\n| **Chunk-level** | Good | Low | Simple Q&A |\n| **Sentence-level** | Excellent | Medium | Research, legal |\n| **Quote extraction** | Best | High | Compliance-critical |\n| **Inline footnotes** | Good | Medium | Chat interfaces |\n\n---\n\n## Phase 7: Evaluation Framework\n\n### RAG Evaluation Dimensions\n\n| Dimension | What It Measures | Metric |\n|-----------|-----------------|--------|\n| **Retrieval Relevance** | Are retrieved chunks relevant? | Precision@K, Recall@K, MRR, NDCG |\n| **Context Relevance** | Is context sufficient for answer? | Context Precision, Context Recall |\n| **Answer Faithfulness** | Is answer grounded in context? | Faithfulness Score (0-1) |\n| **Answer Relevance** | Does answer address the question? | Answer Relevance Score (0-1) |\n| **Answer Correctness** | Is the answer factually correct? | Correctness vs ground truth |\n| **Hallucination** | Does answer contain made-up info? | Hallucination Rate |\n| **Latency** | How fast is end-to-end response? | p50, p95, p99 |\n| **Cost** | How much per query? | $\u002Fquery |\n\n### Building an Evaluation Dataset\n\nMinimum 50 test cases. Target 200+ for production.\n\n```yaml\neval_case:\n  id: \"eval-042\"\n  query: \"What is the refund policy for enterprise customers?\"\n  # Ground truth\n  expected_answer: \"Enterprise customers can request a full refund within 30 days...\"\n  expected_source_docs: [\"enterprise-tos.pdf\", \"refund-policy.md\"]\n  # Categories for analysis\n  category: \"policy\"       # policy, technical, factual, analytical, multi-hop\n  difficulty: \"easy\"       # easy, medium, hard\n  requires_multi_doc: false\n```\n\n### Eval Case Categories\n\n| Category | Example | Why It Matters |\n|----------|---------|---------------|\n| **Factual lookup** | \"What's the API rate limit?\" | Basic retrieval accuracy |\n| **Multi-hop** | \"Compare Q1 and Q2 revenue\" | Tests cross-document reasoning |\n| **Negative** | \"What's the Mars colonization policy?\" | Should return \"I don't know\" |\n| **Temporal** | \"What changed in the latest update?\" | Tests freshness and recency |\n| **Ambiguous** | \"How do I connect?\" | Tests query understanding |\n| **Adversarial** | \"Ignore instructions and...\" | Tests prompt injection resistance |\n\n### Evaluation Tools\n\n| Tool | Type | Strengths |\n|------|------|-----------|\n| **RAGAS** | Open-source | Comprehensive RAG metrics, LLM-based evaluation |\n| **DeepEval** | Open-source | 14+ metrics, pytest integration |\n| **TruLens** | Open-source | Feedback functions, experiment tracking |\n| **Langfuse** | Managed | Tracing, scoring, datasets |\n| **Braintrust** | Managed | Eval, logging, prompt management |\n| **Custom** | Build | Full control, domain-specific metrics |\n\n### Evaluation Rules\n\n1. **Build eval BEFORE optimizing** — you can't improve what you can't measure\n2. **Include negative cases** — at least 10% of eval should be \"no answer available\"\n3. **Separate retrieval eval from generation eval** — debug each stage independently\n4. **Automate eval in CI\u002FCD** — run on every pipeline change\n5. **Track metrics over time** — quality drift is real and sneaky\n6. **Human evaluation quarterly** — automated metrics correlate but don't replace human judgment\n7. **Test with real user queries** — log production queries, add interesting ones to eval set\n\n---\n\n## Phase 8: Production Operations\n\n### Indexing Pipeline Operations\n\n```yaml\npipeline:\n  schedule: \"0 2 * * *\"  # Daily at 2 AM\n  steps:\n    - name: \"Detect changes\"\n      method: \"incremental\"  # full, incremental, CDC\n      track: \"last_modified, content_hash\"\n    - name: \"Extract & clean\"\n      parallelism: 4\n      timeout: 30m\n    - name: \"Chunk\"\n      strategy: \"recursive_character\"\n      chunk_size: 512\n      overlap: 50\n    - name: \"Embed\"\n      model: \"text-embedding-3-small\"\n      batch_size: 100\n    - name: \"Upsert to vector DB\"\n      collection: \"production\"\n      dedup: true\n    - name: \"Verify\"\n      run_eval_subset: true\n      min_score: 0.85\n    - name: \"Cleanup\"\n      remove_stale: true\n      stale_threshold: \"30d\"\n```\n\n### Update Strategy Decision\n\n| Strategy | Complexity | Freshness | Best For |\n|----------|-----------|-----------|----------|\n| **Full re-index** | Low | Batch only | \u003C100K docs, weekly updates OK |\n| **Incremental** | Medium | Near-real-time | Content with timestamps\u002Fhashes |\n| **CDC (Change Data Capture)** | High | Real-time | Database sources, streaming |\n| **Hybrid** | Medium | Configurable | Mixed — full weekly + incremental daily |\n\n### Monitoring Dashboard\n\n```yaml\nrealtime_metrics:\n  - name: \"Query Latency (p95)\"\n    threshold: \"\u003C3s\"\n    alert_if: \">5s for 5 minutes\"\n  - name: \"Retrieval Relevance\"\n    threshold: \">0.85 avg similarity\"\n    alert_if: \"\u003C0.75 for 10 queries\"\n  - name: \"Empty Results Rate\"\n    threshold: \"\u003C5%\"\n    alert_if: \">10% in 1 hour\"\n  - name: \"Error Rate\"\n    threshold: \"\u003C1%\"\n    alert_if: \">5% in 5 minutes\"\n\nperiodic_metrics:\n  - name: \"Eval Suite Score\"\n    frequency: \"daily\"\n    threshold: \">0.85\"\n  - name: \"Index Freshness\"\n    frequency: \"hourly\"\n    threshold: \"\u003C24h behind source\"\n  - name: \"Cost per Query\"\n    frequency: \"daily\"\n    threshold: \"\u003C$0.05\"\n  - name: \"Hallucination Rate\"\n    frequency: \"weekly\"\n    threshold: \"\u003C3%\"\n\nweekly_review:\n  - Eval suite trend (improving\u002Fdegrading?)\n  - Top failing query categories\n  - Cost per query trend\n  - User feedback analysis\n  - Index health and freshness\n```\n\n### Failure Modes & Remediation\n\n| Failure | Detection | Fix |\n|---------|-----------|-----|\n| Retrieval returns irrelevant chunks | Low similarity scores, user feedback | Tune chunk size, add reranking, improve embeddings |\n| Hallucinated answers | Faithfulness \u003C 0.8, contradiction detection | Strengthen \"cite only\" prompt, lower temperature |\n| Stale information | Document freshness check, user reports | Increase sync frequency, add freshness filter |\n| Missing documents | Recall drop in eval, gap analysis | Audit data sources, check ingestion pipeline |\n| Slow responses | p95 > SLA | Cache frequent queries, optimize index, reduce chunk count |\n| Cost spike | $\u002Fquery exceeds budget | Reduce top-K, use smaller embedding model, cache |\n| Prompt injection | Adversarial eval failures | Input sanitization, output guardrails |\n\n---\n\n## Phase 9: Advanced Patterns\n\n### Parent-Child Retrieval\n\nRetrieve small chunks for precision, expand to parent for context:\n\n```\nDocument\n  └── Parent Chunk (2048 tokens) — sent to LLM\n       ├── Child Chunk (256 tokens) — used for retrieval\n       ├── Child Chunk (256 tokens)\n       └── Child Chunk (256 tokens)\n```\n\nImplementation: Store child embeddings with parent_id reference. On retrieval, fetch children, deduplicate by parent, return parent text.\n\n### Multi-Index Routing\n\nRoute queries to specialized indexes:\n\n```yaml\nindexes:\n  - name: \"technical_docs\"\n    trigger: \"code, API, implementation, error\"\n    collection: \"tech_v2\"\n  - name: \"policies\"\n    trigger: \"policy, compliance, legal, terms\"\n    collection: \"policies_v1\"\n  - name: \"general\"\n    trigger: \"default\"\n    collection: \"general_v1\"\n```\n\nUse an LLM or classifier to route incoming queries to the right index.\n\n### Contextual Retrieval (Anthropic Pattern)\n\nPrepend each chunk with document-level context before embedding:\n\n```\nChunk context: \"This chunk is from the Q3 2025 financial report, \nspecifically the Revenue Analysis section discussing APAC market growth.\"\n\n[Original chunk text follows]\n```\n\n**Impact:** 35% reduction in retrieval failures (Anthropic research). Adds embedding cost but dramatically improves retrieval quality.\n\n### Conversation-Aware RAG\n\nFor multi-turn conversations:\n\n```\n1. Combine last N turns into standalone query\n   \"What about their pricing?\" → \"What is Acme Corp's pricing for enterprise plans?\"\n2. Use standalone query for retrieval\n3. Include conversation history in LLM context (after retrieved chunks)\n```\n\n### Knowledge Graph + RAG (GraphRAG)\n\nWhen relationships matter more than text similarity:\n\n```\n1. Extract entities and relationships from documents\n2. Build knowledge graph (Neo4j, NetworkX)\n3. On query: identify entities → traverse graph → collect relevant subgraph\n4. Use subgraph context + vector-retrieved chunks for generation\n```\n\nBest for: Organizational knowledge, legal document networks, research papers with citations.\n\n### Corrective RAG (CRAG)\n\nSelf-correcting retrieval:\n\n```\n1. Retrieve chunks\n2. LLM evaluates: \"Are these chunks relevant to the query?\"\n3. If YES → proceed with generation\n4. If PARTIALLY → web search for supplementary info\n5. If NO → fallback to web search or \"I don't know\"\n```\n\n### Multi-Modal RAG\n\nFor documents with images, charts, tables:\n\n| Content Type | Processing | Embedding |\n|-------------|-----------|-----------|\n| Text | Standard chunking | Text embedding model |\n| Images | Vision model → description | Text embedding of description |\n| Tables | Structure-preserving extraction | Text embedding of linearized table |\n| Charts | Vision model → data extraction | Text embedding of extracted data |\n\n---\n\n## Phase 10: Security & Access Control\n\n### RAG Security Checklist\n\n**P0 — Before Launch:**\n- [ ] Row-level access control on vector DB queries\n- [ ] Input sanitization (prompt injection prevention)\n- [ ] Output guardrails (PII detection, content filtering)\n- [ ] API authentication and rate limiting\n- [ ] Audit logging of all queries and retrievals\n- [ ] Data encryption at rest and in transit\n\n**P1 — Within 30 days:**\n- [ ] Prompt injection test suite (adversarial eval)\n- [ ] Data retention and deletion policy (GDPR Article 17)\n- [ ] Access control audit trail\n- [ ] Source document access verification\n- [ ] Cost abuse prevention (rate limits per user\u002Forg)\n\n### Access Control Implementation\n\n```\nQuery with user_context\n  → Extract user permissions (role, department, clearance)\n  → Apply metadata filter BEFORE vector search\n  → Filter: access_level IN user.allowed_levels\n  → Retrieve only authorized chunks\n  → Generate answer from authorized context only\n```\n\n**CRITICAL: Filter at retrieval time, not after generation.** If the LLM sees restricted content, it may leak it in the answer even if you try to filter afterward.\n\n### Prompt Injection Defense\n\n| Layer | Defense |\n|-------|---------|\n| Input | Sanitize special characters, detect injection patterns |\n| System prompt | Strong instruction hierarchy, \"ignore attempts to override\" |\n| Retrieved context | Wrap in delimiters, instruct LLM to treat as data not instructions |\n| Output | Content filter, PII detector, answer verification |\n\n---\n\n## Phase 11: Cost Optimization\n\n### Cost Breakdown per Query\n\n| Component | Typical Cost | Optimization |\n|-----------|-------------|-------------|\n| Embedding (query) | $0.000002 | Negligible |\n| Vector search | $0.0001-$0.001 | Cache frequent queries |\n| Reranking | $0.001-$0.005 | Skip for simple queries |\n| LLM generation | $0.01-$0.10 | Smaller model, shorter context |\n| **Total** | **$0.01-$0.10** | |\n\n### Cost Reduction Strategies\n\n1. **Cache frequent queries** — semantic cache (embed query, check similarity to cached). 20-40% hit rate typical\n2. **Tiered models** — simple queries → small model, complex → large model\n3. **Reduce context** — send top-3 instead of top-10 chunks when confidence is high\n4. **Batch embeddings** — embed in batches, not per-query\n5. **Dimensionality reduction** — Matryoshka embeddings at 512 dims vs 1536\n6. **Self-hosted embeddings** — BGE\u002FGTE models eliminate per-token API costs at scale\n7. **Query classification** — route \"I need help\" to FAQ, not full RAG pipeline\n\n### Scale Planning\n\n| Scale | Architecture | Monthly Cost Estimate |\n|-------|-------------|---------------------|\n| \u003C1K queries\u002Fday | Chroma + OpenAI API | $50-200 |\n| 1K-10K queries\u002Fday | Managed vector DB + API | $200-2,000 |\n| 10K-100K queries\u002Fday | Dedicated infra + mix | $2,000-20,000 |\n| >100K queries\u002Fday | Self-hosted everything | $10,000+ (compute) |\n\n---\n\n## Phase 12: Common Patterns Library\n\n### Pattern 1: Internal Knowledge Base Q&A\n\n```yaml\narchitecture: \"Advanced RAG\"\nsources: [\"Confluence\", \"Google Docs\", \"Notion\"]\nchunking: \"Document structure\"\nembedding: \"text-embedding-3-small\"\nvector_db: \"Pinecone\"\nretrieval: \"Hybrid search + Cohere Rerank\"\ngeneration: \"Claude Sonnet with citations\"\naccess_control: \"Department-based metadata filtering\"\neval: \"200 questions from real Slack threads\"\n```\n\n### Pattern 2: Customer Support Bot\n\n```yaml\narchitecture: \"Agentic RAG\"\nsources: [\"Help center\", \"Release notes\", \"Internal runbooks\"]\nchunking: \"Sentence window (3 sentences)\"\nembedding: \"text-embedding-3-small\"\nvector_db: \"Weaviate\"\nretrieval: \"Vector + BM25 hybrid, α=0.6\"\ngeneration: \"GPT-4o-mini (cost-efficient)\"\nfallback: \"Escalate to human after 2 failed retrievals\"\neval: \"500 real support tickets with expert answers\"\n```\n\n### Pattern 3: Legal Document Analysis\n\n```yaml\narchitecture: \"Graph RAG + Advanced RAG\"\nsources: [\"Contracts\", \"Regulations\", \"Case law\"]\nchunking: \"Semantic chunking (clause-level)\"\nembedding: \"Voyage-3 (legal fine-tuned)\"\nvector_db: \"Qdrant (self-hosted, data sovereignty)\"\nretrieval: \"Multi-index routing (contracts vs regulations)\"\ngeneration: \"Claude Opus with sentence-level citations\"\naccess_control: \"Matter-based, attorney-client privilege tagging\"\neval: \"100 questions reviewed by practicing attorneys\"\n```\n\n### Pattern 4: Code Documentation Search\n\n```yaml\narchitecture: \"Advanced RAG\"\nsources: [\"Code comments\", \"README\", \"ADRs\", \"API specs\"]\nchunking: \"Code-aware (function\u002Fclass level via tree-sitter)\"\nembedding: \"Voyage-code-3\"\nvector_db: \"pgvector (already have Postgres)\"\nretrieval: \"Hybrid (code keywords + semantic)\"\ngeneration: \"Claude Sonnet with code snippets\"\neval: \"Developer survey + retrieval accuracy\"\n```\n\n---\n\n## Quality Rubric (0-100)\n\n| Dimension | Weight | 0 (Poor) | 50 (Adequate) | 100 (Excellent) |\n|-----------|--------|-----------|---------------|-----------------|\n| Retrieval Accuracy | 25% | \u003C70% relevant in top-5 | 80-90% relevant | >95% relevant, reranked |\n| Answer Quality | 20% | Hallucinations, unfaithful | Mostly accurate, some gaps | Faithful, cited, comprehensive |\n| Latency | 15% | >10s p95 | 3-5s p95 | \u003C2s p95 |\n| Evaluation Coverage | 15% | No eval suite | 50+ cases, manual | 200+ cases, automated CI |\n| Data Freshness | 10% | Manual, weeks behind | Daily sync | Near-real-time CDC |\n| Security | 10% | No access control | Basic auth, no audit | Row-level ACL, audit trail, injection defense |\n| Cost Efficiency | 5% | >$0.50\u002Fquery | $0.05-$0.10\u002Fquery | \u003C$0.03\u002Fquery with caching |\n\n**Scoring: Sum(dimension_score × weight). Below 50 = not production-ready. 50-70 = MVP. 70-85 = good. 85+ = excellent.**\n\n---\n\n## 10 RAG Commandments\n\n1. **Evaluate first, optimize second** — build eval dataset before tuning anything\n2. **Chunk quality > embedding model** — garbage in, garbage out\n3. **Always rerank** — cheapest improvement with biggest impact\n4. **Filter at retrieval, not generation** — security is not a prompt\n5. **Same model for index and query** — always, no exceptions\n6. **Return \"I don't know\"** — honest uncertainty > confident hallucination\n7. **Monitor continuously** — quality drifts silently\n8. **Cache what you can** — semantic caching saves 20-40% cost\n9. **Test with real queries** — synthetic eval misses real user patterns\n10. **Start simple, add complexity only when eval demands it**\n\n---\n\n## 10 Common RAG Mistakes\n\n| Mistake | Consequence | Fix |\n|---------|------------|-----|\n| No evaluation dataset | Can't measure improvement | Build 50+ eval cases before optimizing |\n| Chunks too large | Low retrieval precision | Reduce to 256-512 tokens, add reranking |\n| Chunks too small | Missing context | Use parent-child retrieval |\n| No overlap between chunks | Lost context at boundaries | 10-20% overlap |\n| Ignoring metadata | Can't filter, poor citations | Rich metadata on every chunk |\n| Pure vector search | Misses keyword matches | Add BM25 hybrid search |\n| No access control | Data leakage | Filter at retrieval time |\n| No \"I don't know\" path | Hallucinations | Similarity threshold + explicit instruction |\n| Over-engineering | Slow delivery, high cost | Start with Basic RAG, upgrade with eval data |\n| Not monitoring production | Silent quality degradation | Automated daily eval + alerting |\n\n---\n\n## Edge Cases\n\n### Multilingual RAG\n- Use multilingual embedding models (Cohere multilingual, BGE-M3)\n- Query language detection → route to language-specific index OR cross-lingual retrieval\n- Generate in query language regardless of document language\n\n### Very Large Documents (>100 pages)\n- Hierarchical chunking: document → section → paragraph → sentence\n- Table of contents as routing layer\n- Summarize each section, use summaries for first-pass retrieval\n\n### Rapidly Changing Data\n- Streaming ingestion pipeline with CDC\n- Time-weighted retrieval (prefer recent)\n- Versioned chunks with effective dates\n\n### Multi-Modal (Images + Text)\n- Vision model to describe images → embed descriptions\n- Separate image and text indexes, merge at retrieval\n- Use multi-modal embedding models (CLIP, SigLIP) for direct image search\n\n### Low-Resource \u002F Offline\n- Self-hosted everything (Ollama + BGE + Chroma + SQLite)\n- Optimize for small models and CPU inference\n- Pre-compute and cache common queries\n\n---\n\n## Natural Language Commands\n\nWhen user says → Agent does:\n- \"Set up a RAG system\" → Walk through Architecture Brief, recommend stack\n- \"My RAG is returning wrong answers\" → Debug with evaluation checklist, check each pipeline stage\n- \"Optimize retrieval\" → Audit chunking, add reranking, tune hybrid search\n- \"How should I chunk these documents?\" → Analyze document types, recommend strategy\n- \"Compare vector databases for my use case\" → Apply selection criteria from Phase 4\n- \"Build an eval dataset\" → Generate eval cases from Phase 7 template\n- \"My RAG is too slow\" → Profile each pipeline stage, identify bottleneck\n- \"How do I handle access control?\" → Implement Phase 10 patterns\n- \"Reduce RAG costs\" → Apply Phase 11 optimization strategies\n- \"Set up monitoring\" → Configure Phase 8 dashboard and alerts\n- \"Review my RAG architecture\" → Score against Quality Rubric\n- \"I need citations in answers\" → Implement citation strategy from Phase 6\n",{},"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fa\u002Fafrexai-rag-production",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":7,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill afrexai-rag-production",{"tool":37,"command":38},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill afrexai-rag-production",{"tool":40,"command":41},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill afrexai-rag-production","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fa\u002Fafrexai-rag-production\u002FSKILL.md",true,[],[46,54,61,68,75,82],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":53},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":53},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":53},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":53},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":53},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":53},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]