long-context-vs-rag
БесплатноБез исполняемых скриптовНе проверенDecision framework: when long-context (Gemini 2M, Claude 200k, GPT 128k) beats RAG, hybrid approaches (RAG narrows, long-context reads), cost-quality-latency…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Long Context vs RAG
The Decision Has Shifted
As of 2025:
- Claude Sonnet 4.5: 200k tokens native, 1M in extended context mode.
- Gemini 2.5 Pro: 2M tokens.
- GPT-4o family: 128k typical.
- Prompt caching makes re-reading large prefixes ~10x cheaper.
This invalidates old heuristics. RAG is no longer automatic; below certain corpus sizes, long-context is cheaper and better.
Decision Tree
Total corpus tokens?
< 50k -> Stuff the prompt. No RAG. No caching needed.
50k-200k
Query volume high and prompt is stable? -> Long context + prompt caching.
Low volume or rapidly changing? -> Long context, no caching.
200k-2M
Single user, interactive? -> Long context (Gemini 2M, Claude 1M).
High concurrency? -> RAG.
> 2M -> RAG, no choice.
Additional overrides:
- Need auditability with citations? -> RAG (citations harder in long context).
- Content changes hourly? -> RAG (cache invalidates).
- Regulatory requirement to prove what was retrieved? -> RAG.
Cost Math: The Real Numbers
Claude Sonnet 4.5 pricing (approximate 2025, subject to change):
- Input: $3 / M tokens
- Output: $15 / M tokens
- Cache write: 1.25x input
- Cache read: 0.1x input (10% of base)
Example 1: 150k token corpus, 10 queries/min
Stuff without caching
- Per query: 150k in + 500 out = $0.4575
- 10/min * 60min = 600 queries/hour = $274/hour
Stuff with caching
- Cache write (once / 5min): 150k * 1.25 * 12 (per hour) = 2.25M = $6.75
- Cache read per query: 150k * 0.1 = 15k effective = $0.045
- Per query: $0.045 + (500 * 0.000015) = ~$0.053
- 600 queries: $6.75 + 600 * $0.053 = ~$38/hour
- Savings: 86%
RAG (5k retrieved tokens per query)
- Retrieval: ~$0.0003 (OpenAI text-embedding-3-small)
- LLM: 5k in + 500 out = $0.0225
- Per query: ~$0.023
- 600 queries: $14/hour
- Cheapest — but infra cost (vector DB, reranker) is amortized
At > 10 queries/min and corpus < 200k tokens, cached long-context is competitive with small-corpus RAG once you include RAG's infra cost (vector DB, reranker API, maintenance).
Example 2: 1M token corpus, 1 query/min
Stuff with caching
- Cache write: 1M * 1.25 = 1.25M = $3.75 per 5-min window = $45/hour
- Read per query: 1M * 0.1 = 100k = $0.30
- 60 queries: $45 + 60 * $0.30 = $63/hour
RAG
- 60 queries * $0.023 = $1.38/hour
- RAG wins 45x
Rule: above ~300k tokens, RAG dominates on cost regardless of caching.
Quality: The Lost-in-the-Middle / Context Rot Problem
Research (Liu et al. 2023, Anthropic 2024 needle-in-haystack, Databricks 2024):
- Accuracy drops when relevant info is in the middle of a long context.
- Claude, GPT-4, and Gemini all show degradation > 100k tokens on multi-fact synthesis tasks (even when needle retrieval is ~100%).
- Distractors hurt: 20 irrelevant chunks + 1 relevant is harder than 1 relevant alone.
| Task type | Long context strength | RAG strength |
|---|---|---|
| Needle retrieval (1 fact) | Strong ~100% up to context limit | Strong if retrieval works |
| Synthesis across many parts | Degrades above 50-100k | Works — the parts are selected |
| Comparison across sources | Good if all fit | Better — explicit top-K |
| Summarization of whole corpus | Unique strength of long context | Cannot — RAG sees only top-K |
| Reasoning over many entities | Degrades | RAG focuses on the relevant entities |
Choose long context when the query needs the whole document. Choose RAG when the query needs a small fraction.
Hybrid: RAG Narrows, Long Context Reads
Use RAG to filter to the top-N relevant documents, then stuff those documents (not chunks) into long context. Best of both:
- RAG avoids paying for 90% irrelevant content.
- Long context keeps doc-level coherence (no chunking artifacts).
from langchain_anthropic import ChatAnthropic
from anthropic import Anthropic
retriever_client = Anthropic()
llm = ChatAnthropic(model="claude-sonnet-4-5-20250929", max_tokens=2048)
def hybrid_long_rag(question: str, top_doc_ids_k: int = 5):
# Step 1: RAG at document granularity (not chunk)
doc_ids = doc_level_retriever.invoke(question)[:top_doc_ids_k]
full_docs = [document_store.get(did) for did in doc_ids]
# Step 2: stuff full docs into long context with caching
total_tokens = sum(count_tokens(d.text) for d in full_docs)
use_cache = total_tokens > 20_000 # cache breakeven threshold
system_blocks = [
{"type": "text", "text": f"[DOC {d.id}]\n{d.text}",
"cache_control": {"type": "ephemeral"} if use_cache else None}
for d in full_docs
]
# Filter None cache_control fields
system_blocks = [{k: v for k, v in b.items() if v is not None} for b in system_blocks]
resp = retriever_client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
system=system_blocks,
messages=[{"role": "user", "content": question}],
)
return resp.content[0].text
Doc-level retrieval avoids chunki
Установить long-context-vs-rag в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл long-context-vs-rag?
Decision framework: when long-context (Gemini 2M, Claude 200k, GPT 128k) beats RAG, hybrid approaches (RAG narrows, long-context reads), cost-quality-latency tradeoffs, lost-in-the-middle / context rot research, needle vs synthesis tasks, prompt caching economics, concrete $ per query math. USE WHEN: user mentions "long context vs RAG", "Gemini 2M", "lost in the middle", "context rot", "when not to use RAG", "stuff the prompt", "prompt caching cost" DO NOT USE FOR: implementing RAG - use `rag-architecture`; evaluating RAG - use `rag-evaluation`; chunking decisions alone - use `chunking-strategies`
Как установить скилл long-context-vs-rag?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл long-context-vs-rag запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
agent-skill-stack
Find, evaluate, and assemble the smallest compatible set of AI Agent Skills for an end-to-end natural-language goal. Use when a user wants Skills for a…
от GitHubbuild-evidence-map
Build an auditable evidence map for a contested technical choice, research synthesis, proposal review, or consequential decision. Use when Copilot must…
от GitHubpinecone-rag
Build production RAG pipelines and persistent agent memory using Pinecone as the vector database backend. ALWAYS USE THIS SKILL when the user mentions…
от GitHubqdrant-monitoring-debugging
Diagnoses Qdrant production issues using metrics and observability tools. Use when someone reports 'optimizer stuck', 'indexing too slow', 'memory too high'…
от GitHub