Llm Rag Retrieval Internalsのロゴ

Llm Rag Retrieval Internals

コミュニティ
j4flmao
llm-rag-retrieval-internals

Use this skill when the user says 'HNSW parameters', 'IVF-PQ', 'ANN index tuning', 'efSearch', 'nprobe', 'recall vs latency', 'Self-RAG', 'DSPy', 'optimize RAG pipeline', 'hybrid search fusion'. Covers retrieval engine internals (HNSW, IVF, PQ), index tuning for recall/latency/memory, hybrid dense+sparse fusion, reranking, and adaptive/optimized RAG pipelines (Self-RAG, DSPy). Do NOT use for: query rewriting and prompt-side RAG design (prompt-engineering/rag-design), agent memory (ai/ai-agents/memory-systems), or choosing a vector database product (ai vector-databases / data skills).

概要

公開者j4flmao
リポジトリagent-skills
スキル名llm-rag-retrieval-internals
スター
41
フォーク
6
同梱ファイル
指示のみ
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    j4flmaoがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Llm Rag Retrieval Internals」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-engineering/rag-architecture
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/ai/llm-engineering/rag-architecture .claude/skills/llm-rag-retrieval-internals
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでLlm Rag Retrieval Internalsを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にLlm Rag Retrieval Internalsを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Llm Rag Retrieval Internalsは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

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

IndexMemoryBuildQueryUpdatesUse when
Flat (exact)N·d·4 BNoneO(N·d)Trivial< ~100k vectors, ground truth
HNSWVectors + graph (~M·2 links/node at layer 0)Slow-ishSub-linear, empirically ~log N hopsInserts OK, deletes awkwardDefault for low-latency, high recall in RAM
IVF-FlatVectors + centroidsk-means trainingScans nprobe/nlist of dataNeeds retraining on driftLarge corpora, batch updates
IVF-PQm·nbits/8 bytes per vectorTrainingFast table lookups (ADC)Retrain on driftBillion-scale, memory-bound
DiskANN-styleGraph on SSDSlowFew SSD readsVariesLarger 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.

ParamEffectTypical
MLinks per node; recall and memory up16-48
efConstructionBuild-time candidate list; graph quality and build time up100-400
efSearchQuery-time candidate list; recall and latency up (must be ≥ k)50-400, tune per SLO

IVF-PQ

  • IVF: k-means into nlist cells; query scans the nprobe closest cells, roughly nprobe/nlist of the data.
  • PQ: split each vector into m sub-vectors, quantize each to one of 2^nbits centroids (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

python
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)

python
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([dense_ids, sparse_ids])[:50]
    scored = cross_encoder_scores(query, candidates)  # e.g. a bge/Cohere/Jina reranker
    return [doc for doc, _ in sorted(scored, key=lambda x: x[1], reverse=True)[:top_n]]

Sparse search rescues exact identifiers (SKUs, error codes, names) that dense embeddings miss; reranking with a cross-encoder fixes ordering at the top where it matters.

Adaptive and Optimized Pipelines

  • Self-RAG (Asai et al., 2023): a model fine-tuned to emit reflection tokens deciding whether to retrieve (Retrieve) and critiquing relevance (ISREL), support (ISSUP), and usefulness (ISUSE); decoding prefers segments with favourable critiques. Prompted approximations: a cheap "is retrieval needed?" gate plus a groundedness check on the answer.
  • Corrective RAG: grade retrieved passages; if weak, rewrite the query or fall back to another source.
  • DSPy: write the pipeline as modules with signatures ("context, question -> answer"), then let an optimizer (e.g. BootstrapFewShot, MIPROv2) search instructions and few-shot demos against your metric on a training set. It optimizes prompts by search and bootstrapped examples, not by gradients through the LLM.

Evaluation

LayerMetricHow
ANNrecall@k vs exactrecall_at_k above on sampled queries
Retrievalhit rate@k, MRR, nDCGLabeled query → relevant chunk ids
Generationfaithfulness, answer correctnessLLM-judge with rubric + human spot checks
Systemp95 latency, cost/queryLoad test

Anti-Patterns

  • Tuning efSearch/nprobe without measuring recall against exact search.
  • Dense-only retrieval for queries with identifiers.
  • Sending 20+ unreranked chunks to the LLM (cost up, answer quality often down).
  • Mixing embeddings from different models/versions in one index.
  • IVF trained on a tiny or stale sample.

Checklist

  • Index type matches size/memory/update pattern.
  • Parameters tuned on a recall-latency curve.
  • Hybrid retrieval + RRF + cross-encoder rerank.
  • Structure-aware or parent-child chunking.
  • Embedding model/version stored with every vector.
  • Retrieval and generation evals in CI.

References

  • Malkov & Yashunin, "Efficient and robust approximate nearest neighbor search using HNSW graphs" (TPAMI 2018).
  • Jégou et al., "Product Quantization for Nearest Neighbor Search" (TPAMI 2011); FAISS wiki.
  • Cormack et al., "Reciprocal Rank Fusion" (SIGIR 2009); Asai et al., "Self-RAG" (ICLR 2024); Khattab et al., "DSPy" (ICLR 2024).

よくある質問

AIスキル「Llm Rag Retrieval Internals」では何ができますか?

Use this skill when the user says 'HNSW parameters', 'IVF-PQ', 'ANN index tuning', 'efSearch', 'nprobe', 'recall vs latency', 'Self-RAG', 'DSPy', 'optimize RAG pipeline', 'hybrid search fusion'. Covers retrieval engine internals (HNSW, IVF, PQ), index tuning for recall/latency/memory, hybrid dense+sparse fusion, reranking, and adaptive/optimized RAG pipelines (Self-RAG, DSPy). Do NOT use for: query rewriting and prompt-side RAG design (prompt-engineering/rag-design), agent memory (ai/ai-agents/memory-systems), or choosing a vector database product (ai vector-databases / data skills).

TypingMindでLlm Rag Retrieval Internalsを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Llm Rag Retrieval Internalsはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにLlm Rag Retrieval Internalsをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-engineering/rag-architectureを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Llm Rag Retrieval Internalsを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Llm Rag Retrieval Internalsで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもLlm Rag Retrieval Internalsを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Llm Rag Retrieval Internals」は無料ですか?

はい。j4flmaoがMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇