一行要約
通常の RAG はチャンク化の時点で文脈を破壊してしまうため、各チャンクの前に「この断片が文書全体のどこに位置するか」を Claude に 50〜100 トークンで書かせて埋め込むだけで、検索失敗率が 35〜67% 下がる。
要点
まず「RAG が要るか」を疑う
20万トークン(およそ 500 ページ)未満の知識ベースなら、RAG を組まずにプロンプトに全部入れてしまえばよい。prompt caching を併用すればレイテンシは 2倍以上改善し、コストは最大 90% 下がる。
通常の RAG の問題
典型的な RAG は6段階(チャンク化 → 埋め込み → ベクタ DB → BM25 による字句一致 → rank fusion → 上位 K 件をプロンプトに追加)。
traditional RAG solutions remove context when encoding information, which often results in the system failing 従来の RAG は情報を符号化する際に文脈を落としてしまい、その結果としてシステムが失敗することが多い
チャンクは通常数百トークン。その単位で切ると、「その数値が何の会社の、いつの話か」といった情報が失われる。
Contextual Retrieval のやり方
埋め込みとインデックスの前に、各チャンクへチャンク固有の説明文脈を前置する。この文脈は Claude に自動生成させる。
前処理の流れ:
- 文書全体を Claude に渡す
- 個別のチャンクを取り出す
- Claude が 50〜100 トークンの文脈説明を生成する
- contextualized chunk = 説明 + 元のチャンク
- これを埋め込み、インデックスする
効果(top-20 チャンクの検索失敗率)
| 手法 | 失敗率 | 削減 |
|---|---|---|
| ベースライン | 5.7% | — |
| Contextual Embeddings | 3.7% | 35%減 |
| Contextual Embeddings + Contextual BM25 | 2.9% | 49%減 |
| 上記 + Reranking | 1.9% | 67%減 |
- top-20 が top-10 / top-5 より良かった
- Reranking は最初に取得した top-150 を top-20 に絞り込む形でテストされた
コスト
prompt caching を使った場合の一度きりの前処理コストは 100万文書トークンあたり $1.02(800トークンのチャンク、8kトークンの文書、50トークンの文脈指示、チャンクあたり100トークンの文脈という条件)。
実装上の注意
- チャンクの境界 — サイズ、境界、オーバーラップが性能に効く
- 埋め込みモデル — Gemini と Voyage の埋め込みが特に有効だった
- ドメイン特化の contextualizer プロンプトを書くと改善しうる
- チャンク数 — 5 / 10 / 20 の比較では 20 が最良
- 必ず eval を回す。 出力において文脈部分とチャンク本体を区別できるようにしておく
そのまま使える具体例
文脈を生成させるプロンプト(「簡潔な文脈だけを答えよ、他は何も言うな」が要点):
<document>
{{WHOLE_DOCUMENT}}
</document>
Here is the chunk we want to situate within the whole document
<chunk>
{{CHUNK_CONTENT}}
</chunk>
Please give a short succinct context to situate this chunk within the overall document for the purposes of improving search retrieval of the chunk. Answer only with the succinct context and nothing else.変換の実例:
original_chunk = "The company's revenue grew by 3% over the previous quarter."
contextualized_chunk = "This chunk is from an SEC filing on ACME corp's performance in Q2 2023; the previous quarter's revenue was $314 million. The company's revenue grew by 3% over the previous quarter."判断のしきい値:
知識ベース < 200,000 トークン(約500ページ) → RAG を組まずプロンプトに全部入れる + prompt caching
それ以上 → Contextual Retrieval(+ BM25、+ Reranking)原典で言及されている関連文書
- effective-context-engineering-for-ai-agents — 「retrieval よりまず context に載せる」という現在の立場との対比
- develop-tests — 「必ず eval を回す」の具体化
- demystifying-evals-for-ai-agents — リサーチエージェントの groundedness / coverage チェック