技能创建器
skill-creator
创建、改进和评估自定义技能,把专业流程转化为可重复使用的 AI 能力。
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",…
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
name: long-context-vs-rag description: | 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"
rag-architecture;
evaluating RAG - use rag-evaluation;
chunking decisions alone - use chunking-strategies
allowed-tools: Read, Grep, Glob, Write, EditAs of 2025:
This invalidates old heuristics. RAG is no longer automatic; below certain corpus sizes, long-context is cheaper and better.
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:
Claude Sonnet 4.5 pricing (approximate 2025, subject to change):
Stuff without caching
Stuff with caching
RAG (5k retrieved tokens per query)
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).
Stuff with caching
RAG
Rule: above ~300k tokens, RAG dominates on cost regardless of caching.
Research (Liu et al. 2023, Anthropic 2024 needle-in-haystack, Databricks 2024):
| 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.
Use RAG to filter to the top-N relevant documents, then stuff those documents (not chunks) into long context. Best of both:
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 chunking losses; caching makes re-reads cheap.
| Setup | TTFT | Full response |
|---|---|---|
| RAG (hybrid, reranked) | 800-1500ms | 2-4s |
| Long context, first call (cold cache) | 3-10s | 5-20s |
| Long context, cached call | 800-1500ms | 2-5s |
| Hybrid RAG + long context | 1200-2000ms | 3-6s |
Cold long context is slow. Cached long context is competitive. RAG is consistently fast because retrieval + small-context generation has low variance.
Caching helps when:
Caching does not help when:
| Use case | Choose |
|---|---|
| Q&A over 50k-token spec document (single user) | Long context + caching |
| Enterprise KB with 10k documents, 1000 daily users | RAG |
| Legal discovery across one case (2M pages) | Tiered: RAG to surface + long-context to read |
| Customer support chatbot | RAG (dynamic content, citations needed) |
| Code review over a single PR | Long context (whole PR + dependencies) |
| Code review over entire codebase | RAG + long context hybrid |
| Research agent needing 50 sources | RAG + agentic |
| Summarize this one book | Long context |
| News chatbot | RAG (freshness) |
Vendors advertise near-100% recall on needle tests. This is a single-fact retrieval. Real tasks are:
Benchmarks that capture this better: RULER, BABILong, LongBench, HELMET. Consult these, not the marketing chart.
Starting a new project with a corpus under 300k tokens: begin with long context + caching. It's simpler, has fewer moving parts, no vector DB to run. Add RAG when:
| Anti-Pattern | Fix |
|---|---|
| RAG on a 50k-token corpus | Long context + caching is cheaper and better |
| Long context on a 2M-token corpus | Cost + latency punishes you; use RAG |
| Trusting needle-in-haystack claims for synthesis tasks | Benchmark on your own tasks |
| Not enabling prompt caching when prefix repeats | 90% cost miss |
| Same context on every turn without cache | Break it into a stable system + variable suffix; cache the prefix |
| Ignoring long-context latency on first call | Warm the cache during app startup if possible |
| Long context + large chunking overhead | Remove chunking; pass whole docs |
| Hybrid with chunk-level RAG feeding long context | Retrieve at doc level; long context swallows the rest |
| Hardcoded 200k assumption | Model limits change; pull from SDK |
| Not measuring | Decide with your own eval set and cost dashboard |