ai-rag
RAG and search engineering — chunking, hybrid retrieval, reranking, and nDCG evaluation. Use when building retrieval-augmented generation pipelines.
What this skill does
# RAG & Search Engineering — Complete Reference
Build production-grade retrieval systems with **hybrid search**, **grounded generation**, and **measurable quality**.
This skill covers:
- **RAG**: Chunking, contextual retrieval, grounding, adaptive/self-correcting systems
- **Search**: BM25, vector search, hybrid fusion, ranking pipelines
- **Evaluation**: recall@k, nDCG, MRR, groundedness metrics
**Modern Best Practices (Jan 2026)**:
- Separate **retrieval quality** from **answer quality**; evaluate both (RAG: https://arxiv.org/abs/2005.11401).
- Default to **hybrid retrieval** (sparse + dense) with **reranking** when precision matters (DPR: https://arxiv.org/abs/2004.04906).
- Use a failure taxonomy to debug systematically (Seven Failure Points in RAG: https://arxiv.org/abs/2401.05856).
- Treat **freshness/invalidation** as first-class; staleness is a correctness bug, not a UX issue.
- Add **grounding gates**: answerability checks, citation coverage checks, and refusal-on-missing-context defaults.
- Threat-model RAG: retrieved text is untrusted input (OWASP LLM Top 10: https://owasp.org/www-project-top-10-for-large-language-model-applications/).
**Default posture**: deterministic pipeline, bounded context, explicit failure handling, and telemetry for every stage.
**Scope note**: For prompt structure and output contracts used in the generation phase, see [ai-prompt-engineering](../ai-prompt-engineering/SKILL.md).
## Quick Reference
| Task | Tool/Framework | Command/Pattern | When to Use |
|------|----------------|-----------------|-------------|
| Decide RAG vs alternatives | Decision framework | RAG if: freshness + citations + corpus size; else: fine-tune/caching | Avoid unnecessary retrieval latency/complexity |
| Chunking & parsing | Chunker + parser | Start simple; add structure-aware chunking per doc type | Ingestion for docs, code, tables, PDFs |
| Retrieval | Sparse + dense (hybrid) | Fusion (e.g., RRF) + metadata filters + top-k tuning | Mixed query styles; high recall requirements |
| Precision boost | Reranker | Cross-encoder/LLM rerank of top-k candidates | When top-k contains near-misses/noise |
| Grounding | Output contract + citations | Quote/ID citations; answerability gate; refuse on missing evidence | Compliance, trust, and auditability |
| Evaluation | Offline + online eval | Retrieval metrics + answer metrics + regression tests | Prevent silent regressions and staleness failures |
## Decision Tree: RAG Architecture Selection
```text
Building RAG system: [Architecture Path]
├─ Document type?
│ ├─ Page/section-structured? → Structure-aware chunking (pages/sections + metadata)
│ ├─ Technical docs/code? → Structure-aware + code-aware chunking (symbols, headers)
│ └─ Simple content? → Fixed-size token chunking with overlap (baseline)
│
├─ Retrieval accuracy low?
│ ├─ Query ambiguity? → Query rewriting + multi-query expansion + filters
│ ├─ Noisy results? → Add reranker + better metadata filters
│ └─ Mixed queries? → Hybrid retrieval (sparse + dense) + reranking
│
├─ Dataset size?
│ ├─ <100k chunks? → Flat index (exact search)
│ ├─ 100k-10M? → HNSW (low latency)
│ └─ >10M? → IVF/ScaNN/DiskANN (scalable)
│
└─ Production quality?
└─ Add: ACLs, freshness/invalidation, eval gates, and telemetry (end-to-end)
```
## Core Concepts (Vendor-Agnostic)
- **Pipeline stages**: ingest → chunk → embed → index → retrieve → rerank → pack context → generate → verify.
- **Two evaluation planes**: retrieval relevance (did we fetch the right evidence?) vs generation fidelity (did we use it correctly?).
- **Freshness model**: staleness budget, invalidation triggers, and rebuild strategy (incremental vs full).
- **Trust boundaries**: retrieved content is untrusted; apply the same rigor as user input (OWASP LLM Top 10: https://owasp.org/www-project-top-10-for-large-language-model-applications/).
## Implementation Practices (Tooling Examples)
- Use a **retrieval API contract**: query, filters, top_k, trace_id, and returned evidence IDs.
- Instrument each stage with tracing/metrics (OpenTelemetry GenAI semantic conventions: https://opentelemetry.io/docs/specs/semconv/gen-ai/).
- Add **caches** deliberately: embeddings cache, retrieval cache (query+filters), and response cache (with invalidation).
## Do / Avoid
**Do**
- Do keep retrieval deterministic: fixed top_k, stable ranking, explicit filters.
- Do enforce document-level ACLs at retrieval time (not only at generation time).
- Do include citations with stable IDs and verify citation coverage in tests.
**Avoid**
- Avoid shipping RAG without a test set and regression gate.
- Avoid "stuff everything" context packing; it increases cost and can reduce accuracy.
- Avoid mixing corpora without metadata and tenant isolation.
## When to Use This Skill
Use this skill when the user asks:
- "Help me design a RAG pipeline."
- "How should I chunk this document?"
- "Optimize retrieval for my use case."
- "My RAG system is hallucinating — fix it."
- "Choose the right vector database / index type."
- "Create a RAG evaluation framework."
- "Debug why retrieval gives irrelevant results."
## Tool/Model Recommendation Protocol
When users ask for vendor/model/framework recommendations, validate claims against current primary sources.
### Triggers
- "What's the best vector database for [use case]?"
- "What should I use for [chunking/embedding/reranking]?"
- "What's the latest in RAG development?"
- "Current best practices for [retrieval/grounding/evaluation]?"
- "Is [Pinecone/Qdrant/Chroma] still relevant in 2026?"
- "[Vector DB A] vs [Vector DB B]?"
- "Best embedding model for [use case]?"
- "What RAG framework should I use?"
### Required Checks
1. Read `data/sources.json` and start from sources with `"add_as_web_search": true`.
2. Verify 1-2 primary docs per recommendation (release notes, benchmarks, docs).
3. If browsing isn't available, state assumptions and give a verification checklist.
### What to Report
After checking, provide:
- **Current landscape**: What vector DBs/embeddings are popular NOW (not 6 months ago)
- **Emerging trends**: Techniques gaining traction (late interaction, agentic RAG, graph RAG)
- **Deprecated/declining**: Approaches or tools losing relevance
- **Recommendation**: Based on fresh data, not just static knowledge
### Example Topics (verify with current sources)
- Vector databases (Pinecone, Qdrant, Weaviate, Milvus, pgvector, LanceDB)
- Embedding models (OpenAI, Cohere, Voyage AI, Jina, Sentence Transformers)
- Reranking (Cohere Rerank, Jina Reranker, FlashRank, RankGPT)
- RAG frameworks (LlamaIndex, LangChain, Haystack, txtai)
- Advanced RAG (contextual retrieval, agentic RAG, graph RAG, CRAG)
- Evaluation (RAGAS, TruLens, DeepEval, BEIR)
## Related Skills
For adjacent topics, reference these skills:
- **[ai-llm](../ai-llm/SKILL.md)** - Prompting, fine-tuning, instruction datasets
- **[ai-agents](../ai-agents/SKILL.md)** - Agentic RAG workflows and tool routing
- **[ai-llm-inference](../ai-llm-inference/SKILL.md)** - Serving performance, quantization, batching
- **[ai-mlops](../ai-mlops/SKILL.md)** - Deployment, monitoring, security, privacy, and governance
- **[ai-prompt-engineering](../ai-prompt-engineering/SKILL.md)** - Prompt patterns for RAG generation phase
## Templates
### System Design (Start Here)
- [RAG System Design](assets/design/rag-system-design.md)
### Chunking & Ingestion
- [Basic Chunking](assets/chunking/template-basic-chunking.md)
- [Code Chunking](assets/chunking/template-code-chunking.md)
- [Long Document Chunking](assets/chunking/template-long-doc-chunking.md)
### Embedding & Indexing
- [Index Configuration](assets/indexing/template-index-config.md)
- [Metadata Schema](assets/indexing/template-metadata-schema.md)
### Retrieval & Reranking
- [Retrieval Pipeline](assets/retrieval/template-retrieval-pipeline.md)
- [Hybrid Search](assets/retrieval/Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.