llm-rag-retrieval-internals
Use when the user asks to build a RAG pipeline over documentation, tune HNSW (M, efSearch) or IVF-PQ (nprobe), hybrid dense + BM25 search, reciprocal rank…
от j4flmao★ 47 звёзд на GitHub
Установить llm-rag-retrieval-internals в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
RAG Retrieval Internals
Purpose
Retrieval quality caps RAG quality: the generator cannot use a passage that was never retrieved. This skill explains how approximate nearest neighbour (ANN) indexes trade recall for speed and memory, how to tune them, and how to build the repo-standard pipeline: hybrid retrieval (dense + BM25), fusion, cross-encoder reranking, and measured end-to-end evaluation.
Agent Protocol
Trigger
"HNSW", "IVF", "product quantization", "efSearch", "nprobe", "ANN recall", "hybrid search", "reciprocal rank fusion", "reranker", "Self-RAG", "DSPy".
Input Context
- Corpus size (vectors), embedding dimension, update rate.
- Latency SLO, memory budget, required recall@k.
- Current pipeline and failure examples (missed passages, wrong answers).
Output Artifact
Index choice and parameters, hybrid/rerank pipeline, evaluation plan with retrieval and answer metrics.
Response Format
Corpus: {N} vectors × {d} dims Memory budget: {GB}
Index: {HNSW|IVF-Flat|IVF-PQ|flat} params: {M, efConstruction, efSearch | nlist, nprobe, m, nbits}
Hybrid: dense top-{k1} + BM25 top-{k2} -> RRF(k=60) -> rerank top-{n}
Metrics: recall@{k} vs exact, nDCG@{n}, answer faithfulness
Completion Criteria
- ANN recall measured against exact (flat) search on a sample.
- Hybrid retrieval and reranking in place (repo rule).
- Chunking is structure-aware or parent-child, not blind fixed-size (repo rule).
- Labeled eval set for retrieval and generation.
Index Families
| Index | Memory | Build | Query | Updates | Use when |
|---|---|---|---|---|---|
| Flat (exact) | N·d·4 B | None | O(N·d) | Trivial | < ~100k vectors, ground truth |
| HNSW | Vectors + graph (~M·2 links/node at layer 0) | Slow-ish | Sub-linear, empirically ~log N hops | Inserts OK, deletes awkward | Default for low-latency, high recall in RAM |
| IVF-Flat | Vectors + centroids | k-means training | Scans nprobe/nlist of data | Needs retraining on drift | Large corpora, batch updates |
| IVF-PQ | m·nbits/8 bytes per vector | Training | Fast table lookups (ADC) | Retrain on drift | Billion-scale, memory-bound |
| DiskANN-style | Graph on SSD | Slow | Few SSD reads | Varies | Larger than RAM |
HNSW
A multi-layer proximity graph: upper layers are sparse (nodes promoted with exponentially decreasing probability), layer 0 contains every vector. Search greedily descends from the top entry point, then runs a best-first search with a candidate list of size efSearch on layer 0. Neighbour selection uses a diversity heuristic rather than plain k-NN, keeping the graph navigable.
| Param | Effect | Typical |
|---|---|---|
M |
Links per node; recall and memory up | 16-48 |
efConstruction |
Build-time candidate list; graph quality and build time up | 100-400 |
efSearch |
Query-time candidate list; recall and latency up (must be ≥ k) | 50-400, tune per SLO |
IVF-PQ
- IVF: k-means into
nlistcells; query scans thenprobeclosest cells, roughlynprobe/nlistof the data. - PQ: split each vector into
msub-vectors, quantize each to one of2^nbitscentroids (usually 8 bits → 1 byte per sub-vector). Distances use precomputed query-to-centroid tables (asymmetric distance computation). Re-rank the top candidates with full vectors when memory allows.
FAISS Examples
import faiss
import numpy as np
d = 1024
xb = np.load("corpus_embeddings.npy").astype("float32") # normalize for cosine
faiss.normalize_L2(xb)
# HNSW (inner product on normalized vectors = cosine)
hnsw = faiss.IndexHNSWFlat(d, 32, faiss.METRIC_INNER_PRODUCT)
hnsw.hnsw.efConstruction = 200
hnsw.add(xb)
hnsw.hnsw.efSearch = 128
# IVF-PQ for large corpora
nlist, m = 4096, 64 # d must be divisible by m
quantizer = faiss.IndexFlatIP(d)
ivfpq = faiss.IndexIVFPQ(quantizer, d, nlist, m, 8, faiss.METRIC_INNER_PRODUCT)
ivfpq.train(xb[np.random.choice(len(xb), 200_000, replace=False)])
ivfpq.add(xb)
ivfpq.nprobe = 32
def recall_at_k(index, queries: np.ndarray, k: int = 10) -> float:
exact = faiss.IndexFlatIP(d)
exact.add(xb)
_, gt = exact.search(queries, k)
_, got = index.search(queries, k)
return float(np.mean([len(set(g) & set(t)) / k for g, t in zip(got, gt)]))
Hybrid Retrieval + Rerank (repo standard)
from collections import defaultdict
def rrf(rankings: list[list[str]], k: int = 60) -> list[str]:
"""Reciprocal rank fusion: score(d) = sum over lists of 1 / (k + rank)."""
scores: dict[str, float] = defaultdict(float)
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] += 1.0 / (k + rank)
return sorted(scores, key=scores.__getitem__, reverse=True)
def retrieve(query: str, top_n: int = 5) -> list[str]:
dense_ids = dense_search(query, k=50) # ANN index above
sparse_ids = bm25_search(query, k=50) # e.g. Postgres FTS, OpenSearch, Tantivy
candidates = rrf(
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл llm-rag-retrieval-internals?
Use when the user asks to build a RAG pipeline over documentation, tune HNSW (M, efSearch) or IVF-PQ (nprobe), hybrid dense + BM25 search, reciprocal rank fusion, cross-encoder reranking, Self-RAG or DSPy. Produces index choice and parameters, a hybrid+rerank pipeline and recall evals. Not for query rewriting and RAG prompts (use prompt-rag-query-design).
Как установить скилл llm-rag-retrieval-internals?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл llm-rag-retrieval-internals запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
frontend-design
AnthropicGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making…
webapp-testing
AnthropicToolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing…
brand-guidelines
AnthropicApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand…
web-artifacts-builder
AnthropicSuite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use…