RAG vs Long Context: Why You Can't Just Let Claude Read the Whole Corpus

A 1M-token context window holds 0.17% of a 600M-token corpus, and reading all of it costs $1,204.80 per question at Sonnet 5.5 list prices. One cached window costs $0.108 and an agentic search loop $0.162. The cost model, Python code, the permission problem and a rule for choosing.

RAG vs long context cost chart: per 1,000 questions, one uncached 1M-token window costs $2,008, one cached window $108 and an agentic search loop $162, while a single window covers only 0.17% of a 600M-token corpus and the search loop can reach all of it

Context windows of a million tokens now come at standard prices. Anthropic's documentation lists Claude Opus 5.5, Sonnet 5.5 and Haiku 5.5 with 1M-token windows, and its pricing page says a 900k-token request costs the same per token as a 9k-token one on every current model except Haiku 5.5. So a question keeps coming up from architects building enterprise AI: why build retrieval pipelines, chunking jobs, vector databases and orchestration frameworks at all? Why not deploy Claude, point it at the company corpus and let it read?

The short answer is that retrieval does not go away. What changes is who does the retrieving. A fixed pipeline that embeds 500-token chunks and pastes the top five into a prompt is giving way to an agent that searches, opens whole documents, checks what it found and searches again. That agent still needs an index, a permission model and tools. This piece puts numbers on the "read everything" idea, shows where long context degrades, and ends with a rule for when to cache, when to search and when to query. The Python runs on the standard library.

The context budget

Start with size. Call the corpus C tokens and the context window W tokens. The share of the corpus one prompt can hold is

coverage = W / C

Take an illustrative company with 200,000 documents in SharePoint, Confluence, ticketing and contract systems, averaging 3,000 tokens each. That is C = 600M tokens. With W = 1M tokens, one prompt holds 0.17% of the corpus. Reading all of it for a single question takes 600 full-window calls.

Price is the second constraint. Claude Sonnet 5.5 lists at $2 per million input tokens and $10 per million output tokens, with cache reads at $0.10 per million (0.05 times the input price). Reading the whole corpus once costs

cost_all = C · p_in + n_calls · a · p_out

where p_in and p_out are the per-token prices, n_calls is the 600 window-sized calls and a is an 800-token answer from each. That comes to $1,204.80 per question. At 3,000 employees asking three questions a day, it is about $10.8 million a day.

The sensible version of "let it read" is narrower: put one window of the most relevant documents in front of the model for each question. Uncached, that is $2.008 per question. If the same window is reused and cached, the input cost falls to $0.108.

The agentic alternative is a loop. The model gets a system prompt with tool definitions (S tokens, cached), calls a search or read tool k times, gets r tokens back each time and writes o tokens per call. Every call re-reads everything so far, so the cost is

cost_agent = k S c_r + p_in (r + o) (k(k − 1)) / 2 + k o p_out

where c_r is the cache read price. With S = 10,000, k = 6 calls, r = 4,000 and o = 400, the loop costs $0.162 per question. The growing history term, 66,000 uncached tokens, is most of it.

from dataclasses import dataclass

M = 1_000_000


@dataclass
class Prices:
    input: float = 2.00        # $ per million input tokens (Sonnet 5.5 list)
    output: float = 10.00      # $ per million output tokens
    cache_read: float = 0.10   # $ per million cached input tokens (0.05x input)


def read_everything(corpus_tokens, window, p: Prices, answer_tokens=800):
    """Read the whole corpus for one question, one full window per call."""
    calls = -(-corpus_tokens // window)  # ceiling division
    cost = corpus_tokens * p.input / M + calls * answer_tokens * p.output / M
    return calls, cost


def one_window(window_tokens, p: Prices, cached: bool, answer_tokens=800):
    """Stuff one full window of documents into the prompt for each question."""
    rate = p.cache_read if cached else p.input
    return window_tokens * rate / M + answer_tokens * p.output / M


def agentic_search(p: Prices, system=10_000, calls=6, result=4_000, out=400):
    """A tool-use loop: each call re-reads the cached system prompt plus
    everything retrieved and written so far (that growing part is not cached here)."""
    cost = 0.0
    for i in range(calls):
        history = i * (result + out)
        cost += system * p.cache_read / M
        cost += history * p.input / M
        cost += out * p.output / M
    return cost


if __name__ == "__main__":
    p = Prices()
    corpus = 200_000 * 3_000
    window = 1_000_000
    calls, everything = read_everything(corpus, window, p)
    print(f"one 1M window holds {window / corpus:.2%} of the corpus")
    print(f"read everything:      {calls} calls, ${everything:,.2f} per question")
    print(f"one window, uncached: ${one_window(window, p, cached=False):.3f} per question")
    print(f"one window, cached:   ${one_window(window, p, cached=True):.3f} per question")
    a = agentic_search(p)
    print(f"agentic search:       ${a:.3f} per question")
    print(f"break-even cached corpus size: {a / (p.cache_read / M) / M:.2f}M tokens")

It prints:

one 1M window holds 0.17% of the corpus
read everything:      600 calls, $1,204.80 per question
one window, uncached: $2.008 per question
one window, cached:   $0.108 per question
agentic search:       $0.162 per question
break-even cached corpus size: 1.62M tokens

The cached window beats the agentic loop on price. That result matters, and the rule at the end of this piece is built on it. But the cached window answers from a fixed 0.17% of the corpus, chosen before anyone asked the question, while the loop can reach all of it. Which documents go in the window is a retrieval decision, made once, with no knowledge of the question.

Long context degrades as it grows

Even when the documents fit, more context is not free in quality. Three lines of evidence point the same way.

Liu and colleagues' "Lost in the Middle" study (2023) put the one relevant document among 20 retrieved ones and moved it around. GPT-3.5-Turbo answered correctly 75.8% of the time when the document came first and 53.8% when it sat in the middle, below the 56.1% it scored with no documents at all. Burying the answer did more harm than leaving it out.

NoLiMa (Modarressi and colleagues, ICML 2025) removed the literal word overlap between question and answer that makes needle tests easy. Of 13 models that claim at least 128K tokens of context, 11 fell below half of their short-context score at 32K tokens. GPT-4o went from 99.3% to 69.7%.

Chroma's "Context Rot" report (July 2025) tested 18 models, including Claude Opus 4 and Sonnet 4, and found performance grew less reliable as input length grew in every experiment. Distractors hurt, and four hurt more than one. On a long conversation-memory task, focused prompts of about 300 tokens beat full prompts of about 113,000 tokens for every model family tested.

These studies used models a generation or two older than today's, and newer models do better on long inputs. The direction has held across every evaluation, though: a focused context of the right twenty pages usually beats two thousand pages where most are distractors. That is an argument for retrieval even when the window could hold more.

Permissions decide the architecture

The constraint that ends most "load the corpus" plans in an enterprise is access control. Each user may see only the documents they are entitled to. HR case files, the M&A data room and the board deck cannot sit in one shared context that every employee's question runs against, and a model instruction to "only use documents this user can see" is not an access control.

The check has to happen in the retrieval tool, per user, before anything reaches the model. The toy example below indexes five documents with group labels and runs the same question for three users. Trimming happens before scoring, so a document a user cannot open is never ranked, returned or counted.

import math
import re
from collections import Counter

DOCS = [
    {"id": "hr-07", "groups": {"hr"}, "text": "Reorganization plan: the analytics team moves under finance in March, two roles eliminated."},
    {"id": "fin-12", "groups": {"finance", "exec"}, "text": "Q3 forecast revision: data platform budget cut 15 percent, analytics headcount frozen."},
    {"id": "eng-03", "groups": {"all"}, "text": "Data platform runbook: how to request a new analytics workspace and service principal."},
    {"id": "eng-09", "groups": {"all"}, "text": "Analytics team onboarding guide: access requests, workspace naming, budget codes."},
    {"id": "leg-02", "groups": {"legal", "exec"}, "text": "Acquisition target diligence memo: analytics vendor, purchase price under negotiation."},
]

TOKEN = re.compile(r"[a-z0-9]+")


def tokenize(text):
    return TOKEN.findall(text.lower())


class BM25:
    def __init__(self, docs, k1=1.5, b=0.75):
        self.docs = docs
        self.k1, self.b = k1, b
        self.tf = [Counter(tokenize(d["text"])) for d in docs]
        self.lengths = [sum(tf.values()) for tf in self.tf]
        self.avg_len = sum(self.lengths) / len(docs)
        df = Counter(term for tf in self.tf for term in tf)
        n = len(docs)
        self.idf = {t: math.log(1 + (n - f + 0.5) / (f + 0.5)) for t, f in df.items()}

    def score(self, i, query_terms):
        tf, length = self.tf[i], self.lengths[i]
        s = 0.0
        for t in query_terms:
            if t in tf:
                num = tf[t] * (self.k1 + 1)
                den = tf[t] + self.k1 * (1 - self.b + self.b * length / self.avg_len)
                s += self.idf[t] * num / den
        return s

    def search(self, query, user_groups, k=3):
        terms = tokenize(query)
        allowed = user_groups | {"all"}
        # Trim first: a document the user cannot open is never scored, returned or counted.
        candidates = [i for i, d in enumerate(self.docs) if d["groups"] & allowed]
        ranked = sorted(candidates, key=lambda i: self.score(i, terms), reverse=True)
        return [(self.docs[i]["id"], round(self.score(i, terms), 3)) for i in ranked[:k] if self.score(i, terms) > 0]


if __name__ == "__main__":
    index = BM25(DOCS)
    question = "what is happening to the analytics team budget"
    for user, groups in [("analyst", {"eng"}), ("cfo", {"finance", "exec"}), ("hr partner", {"hr"})]:
        print(f"{user:>10}: {index.search(question, groups)}")
   analyst: [('eng-09', 1.96), ('eng-03', 1.397)]
       cfo: [('eng-09', 1.96), ('eng-03', 1.397), ('fin-12', 0.948)]
hr partner: [('hr-07', 2.228), ('eng-09', 1.96), ('eng-03', 1.397)]

The analyst gets the onboarding guide and the runbook. The CFO also gets the forecast revision, and the HR partner gets the reorganization plan at the top. Put all five documents in one cached context instead and the analyst's answer about "the analytics team budget" could quote the reorganization plan. In production the same filter runs inside the search service, with group IDs from the identity provider passed through on each request, so the trimming happens next to the index rather than in application code.

There are two more reasons an index stays. Documents change hourly, and an index can be updated incrementally while a prompt has to be rebuilt. Answers also need citations to a specific document version, which an index can supply and a prompt cannot.

What changed: the model does the searching

The classic RAG pipeline was built for models with small windows that could not reason about where to look: split documents into 500-token chunks, embed them, retrieve the five most similar to the question, paste them in. When the chunk boundary cut a table in half or the right passage ranked sixth, the answer was wrong and nothing in the pipeline noticed.

Agentic search moves the retrieval decisions into the model. Anthropic's engineering post on context engineering (September 2025) describes the pattern as "just in time" context: the agent keeps lightweight references such as file paths, stored queries and links, and loads the data with tools when it needs it. It describes Claude Code as a hybrid, with project notes loaded up front and files found with glob and grep as the work goes, which avoids keeping a separate index in sync. The post's advice is to do the simplest thing that works.

For enterprise documents, the agent gets a small set of tools: keyword search, semantic search, open a whole document, run a read-only query against curated views, and call a model endpoint. It plans a search, reads what comes back, notices what is missing and searches again. Long windows help here in a different way than the "read everything" idea assumes. They let the agent open whole documents and sections instead of fragments, so chunking decisions matter less.

Orchestration frameworks matter less for the same reason. Much of what chains and output parsers did was hold weaker models on a fixed path. Native tool use, the Model Context Protocol for exposing tools, and vendor agent SDKs now cover most of that. The vector database becomes one tool among several rather than the architecture.

A rule for choosing

The break-even formula turns the cost comparison into a rule. A cached corpus is cheaper per question than the agentic loop while

C < C^* = cost_agent / c_r

With the loop above at $0.162 and cache reads at $0.10 per million tokens, C* is 1.62M tokens, larger than the 1M window. So on price alone, anything that fits in the window is cheaper to cache than to search. The other constraints then decide.

Small and stable corpora that everyone may read (a policy manual, a product spec set, a glossary, the tool instructions themselves) belong in a cached prefix, kept well below the window so quality holds. Large, changing or permissioned corpora belong behind a search tool over a hybrid keyword and vector index with per-user filtering, called by the agent as often as the question needs. Numbers belong in neither: revenue by region comes from a read-only query against curated warehouse views, and a churn score or forecast comes from the model endpoint that produces it, called as a tool, never from a retrieved paragraph that quoted last quarter's figure.

Where this breaks

The cost model is simple on purpose. Real agent loops vary in length, and a hard question can take 15 calls rather than six; at k = 15 the history term grows by a factor of about seven. Caching the growing conversation as well as the system prompt cuts the agentic cost, which favors the loop. Cache writes are not counted for the cached window: a 1-hour write of 1M tokens costs $4 at Sonnet 5.5 list prices, which disappears across thousands of questions but not across a dozen. Haiku 5.5 charges more for prompts over 100,000 tokens, which changes the arithmetic for long prompts on that model. Latency is not modeled at all.

The corpus is illustrative. Plenty of companies have ten times as many documents, and some have a tenth. The quality studies used older models, and newer ones degrade less. None of that changes the shape of the result: a window holds a small, fixed slice of a large corpus, permissions cannot be enforced inside a shared prompt, and the cheapest correct design caches what is small and shared and searches the rest.

What to do with this

Measure your own corpus before arguing about architecture: total tokens by source system, how fast each changes, and which ones carry permissions. Put your real prices and a sample of real agent traces into the cost model above. Then build the first use case on the cheapest design that respects permissions, which is usually a cached prefix of shared reference material plus one search tool over a permission-aware index, and add tools as questions demand them. Related work on retrieval, knowledge graphs and production AI is in the Knowledge Graphs and Production AI research area, and the LLM inference cost calculator covers the per-token side.

The paid edition on Substack turns this into a build plan on Azure: a layered reference architecture with Claude in Microsoft Foundry, Azure AI Search and an API Management gateway; the break-even model extended to cache writes, traffic patterns and loop length; working MCP tool servers for permission-trimmed search, read-only SQL and ML model scores; an evaluation gate for CI; and a five-phase build order with the criteria that end each phase. Subscribe free for new articles by email, or get a Team License for the whole architecture and data team.

Sources

Related research