RAG vs Long Context for Code: When to Stuff the Prompt or Retrieve

For RAG vs long context on a codebase, the deciding factor is size. If the code a task needs fits in about half the model's context window after you strip out the noise, paste it as one file. If it doesn't, or you query the same large repository all day, retrieve, and start with grep-style search before you reach for embeddings.

The rest of this post turns that into something you can apply: a size rule you can paste into a team wiki, the specific ways each approach breaks on real code, what the research from 2023 to 2026 actually supports, and a decision flowchart. It assumes you already know what an embedding is and want an architecture call, not a vector database tutorial.

What are the real options when a codebase is too big to just ask about?

Most articles frame long context vs RAG as a two-way choice. For code there are at least three options, and the third is the one most production coding tools ended up shipping.

  1. Stuff the prompt. Concatenate the relevant files (or the whole repository) into one text file with a directory tree and a header per file, then paste it. The model sees everything at once.

  2. Embedding RAG. Split the code into chunks, embed each chunk, store the vectors, and at query time embed the question and pull the top-k nearest chunks into the prompt.

  3. Agentic retrieval. Give the model tools (ripgrep, glob, read file, sometimes a symbol index) and let it search the repository in a loop, reading only what it decides it needs. This is retrieval too, but the retriever is the model and the index is the filesystem.

A fourth pattern sits between the first and third: a compressed map of the repository (a directory tree, or function and class signatures) plus a handful of complete files. Aider's repo map is the best-known version. For mid-sized repositories it is often the right answer, and I'll come back to it.

So "RAG for code" no longer means one thing. When someone proposes RAG instead of pasting the repo, ask which kind: a vector store and a grep loop differ as much as either differs from a pasted file.

RAG vs long context for codebases: what does the research say?

Short version: long context wins on answer quality when the model can afford to read everything relevant, retrieval wins on cost, and both get worse when the context is full of plausible-looking noise. Code is full of plausible-looking noise.

Long context degrades well before the window is full

Stanford researchers (Liu et al., "Lost in the Middle", 2023) found that models used information at the start and end of a long prompt more reliably than information buried in the middle. Two years later, Chroma's July 2025 "Context Rot" report tested 18 frontier models, including GPT-4.1, Claude 4, Gemini 2.5 and Qwen3, and every one of them became less accurate as input length grew, even on simple retrieve-and-repeat tasks.

Two Chroma details matter more for code than the headline does. First, distractors: material that is topically close to the answer but does not answer the question hurt accuracy, one distractor hurt, and four hurt more. Second, in one of their experiments, the decline was driven by length and by how semantically close the question was to the answer, not by where the answer sat.

A repository is a distractor factory. UserService and UserServiceV2. A fake payment gateway in tests/fixtures/ with the same method names as the real one. A deprecated legacy/auth.py that still imports cleanly. Every one of those is exactly the "close but wrong" content the study found most damaging, and a full-repo dump includes all of them by default.

Long context still beats RAG when you can pay for it

A 2024 study from Google DeepMind and the University of Michigan (Li et al., "Retrieval Augmented Generation or Long-Context LLMs? A Comprehensive Study and Hybrid Approach") compared the two directly. Long-context models consistently did better when resources were ample, while RAG was far cheaper. Their proposed method, Self-Route, sends a query through RAG first and lets the model escalate to full context when it judges the retrieved chunks insufficient. That routing idea transfers well to code, and it shows up in the flowchart below.

Repository-level questions are hard for both approaches

Virginia Tech's StackRepoQA benchmark, presented at PROMISE 2026, collected 1,318 real developer questions with accepted answers across 134 open-source Java projects. The authors tested direct prompting and agentic setups against file-level retrieval and graph-based retrieval of structural dependencies. Accuracy improved when structural signals were added but stayed limited overall, and many high scores came from models reproducing Stack Overflow answers rather than reasoning about the code.

The lesson I take from it: for code, the shape of what you retrieve (imports, call relationships, file boundaries) matters more than a raw similarity score between a question and a chunk.

Production coding agents don't use embedding search for code

The most telling evidence is what tool builders actually shipped. A source-code study of eleven coding agents published in July 2026 ("Harness Engineering", Barbaste et al.) examined Claude Code, Codex CLI, Gemini CLI, Mistral Vibe, OpenHands, Aider and five others. None of the eleven retrieved code with vector embeddings. They rely on deterministic tools instead: ripgrep, glob, tree-sitter, and Markdown context files such as CLAUDE.md and AGENTS.md that the agent discovers automatically. Where embeddings appeared at all, they were used for conversation memory, never for reading the source tree.

This matches what Anthropic's Claude Code team said publicly in 2025: an early approach with a local vector index lost out to plain agentic search, which was more accurate and avoided the work of keeping an index fresh, private and secure.

That doesn't make embeddings useless for code; some IDE products do index repositories that way, and semantic search helps when you don't know a name. But the RAG vs long context question for code, in late 2026, is increasingly "paste or let the model grep", not "paste or stand up a vector store".

How big is too big to paste? A size-threshold rule of thumb

Here is the rule I'd put on a team wiki. It is a judgment call informed by the research above, not a benchmark result, so tune it to your models and tasks.

The half-window rule: if the filtered code a task needs fits in about half of the model's context window, paste it as one file. If it fits only by filling the window, trim harder. If it doesn't fit after trimming, or the same large repository will be queried hundreds of times, retrieve.

Why half rather than whatever the window allows? Because the window is a ceiling, not a target. Context rot says quality slides as length grows. The model needs room for its reasoning and its answer. And a real debugging session adds a lot of back-and-forth on top of the first paste. Half the window leaves headroom for all three.

Windows have been big enough for this to matter for a while: Google brought a 1-million-token window to developers with Gemini 1.5 Pro in 2024, and Anthropic's documentation in 2025 listed 200K tokens as Claude's standard window, with 1 million tokens in beta for higher-tier API organisations. Limits change with every model release, so check the current model page for the one you use. Applied to those sizes, the rule works out roughly like this:

Filtered size of what the task needs

What I'd do

Why

Under ~50K tokens

Paste all of it

Fits every current frontier model with plenty of headroom

~50K to ~100K

Paste, after dropping lockfiles, generated code and fixtures

Still comfortable; removing noise pays off more than retrieval would

~100K to half the window

Paste a curated slice: full-repo tree plus the modules in scope

Distractor risk climbs; careful selection beats both a full dump and top-k chunks

Half the window to the full window

Repo map plus selected files, or hand it to an agent

No room left for conversation; quality and cost both suffer

Larger than the window

Retrieve: agentic search first, embeddings if names are unknown

No longer a choice

Any size, queried hundreds of times a day by many people

Build retrieval

Re-sending the same large context per question adds up fast

Notice the first column says "what the task needs", not "the repository". A monorepo far bigger than any window can still be a paste job if the bug lives in one service whose files come to 60K tokens.

How to measure the real token count of a repository

Don't estimate from the line count. Code tends to tokenize less efficiently than English prose, and the files that inflate a repository (lockfiles, SVGs, minified bundles, test snapshots) are rarely the ones you want the model to read.

  1. Get a raw baseline from the command line: git ls-files -z | xargs -0 cat | wc -c. The familiar "about four characters per token" rule is calibrated on English text, so treat characters divided by four as a lower bound for code.

  2. Find what is eating the budget: git ls-files -z | xargs -0 wc -c | sort -n | tail -20. Lockfiles, generated clients and vendored code usually top the list.

  3. Paste the GitHub URL into the repo to text converter, adding a branch, tag or tree/<ref>/<path> subfolder if you only need part of the project. It shows an approximate token, word, character and file count for your current selection.

  4. Turn on Smaller output, which drops comment-only lines and extra blank lines and skips lockfiles, minified and generated files. Use the Code Only preset or the extension filters to drop docs and assets the task doesn't need.

  5. Untick folders outside the task in the checkbox tree and watch the count fall. The directory tree at the top of the output can cover the full repository even when only some files are included, so the model still sees the project's shape.

  6. Compare the final number with half your model's window. That comparison, not the size of the repo on disk, tells you which side of the line you're on.

Private repositories work with an optional GitHub token kept in your browser's local storage. The count is approximate, so leave a margin.

Code RAG pipeline vs single file: which should you build?

The real difference isn't accuracy. It's what you're signing up to maintain.

A single file is a build artifact. You make it in seconds and throw it away after the task. It needs no infrastructure, it's tied to a git ref (same commit, same file), and it's reviewable: open the .txt and you see exactly what the model saw. When an answer is wrong, you can check whether the right code was even in the prompt.

A code RAG pipeline is a service. It needs a chunker that respects syntax, an embedding model, a vector store, an indexing job that reruns on every push (or the index drifts from main), a retrieval step with k and score thresholds to tune, and an evaluation set to tell you whether any of it works. When an answer is wrong, you first have to work out which stage dropped the relevant code.

Build the pipeline when use is repeated and shared: an internal "ask the codebase" bot across dozens of repositories, a support assistant over code plus docs, a bot that comments on every pull request. Use the single file for one-off and per-task work: getting oriented in an unfamiliar repository, a design review, a refactor plan, a bug hunt in a module you can name.

Several tools produce the single file, and they suit different workflows:

Where does pasting the whole repository go wrong?

These failures are easy to miss because the model still answers fluently.

Oversized pastes fail quietly

Chat apps don't always say how they handled a paste that exceeded the limit, and an answer built from part of your code reads just as confidently as one built from all of it. Measure before you paste, and make the first turn a check: "List every file path you can see in the input." If src/billing/ is missing from the list, you know before it matters.

Distractors outnumber the signal

You ask why refund charges twice. The dump contains payments/refund.py, payments/legacy_refund.py, tests/mocks/fake_gateway.py with its own refund method, and a vendored SDK with a fourth. The model explains the legacy path in detail. That is Chroma's distractor result in code form.

The fix is editorial. Exclude tests/, vendor/, legacy/ and fixtures unless they matter to the question, and say which entry point is live: "The route handler is api/routes/refunds.py; legacy_refund.py is dead code."

Generated and lock files eat the budget

package-lock.json, poetry.lock, *.min.js, protobuf output, generated OpenAPI clients and Jest snapshots carry almost no reasoning value and a lot of tokens. Tools that follow .gitignore catch some of this. Repo2Txt's Smaller output option skips lockfiles, minified and generated files. Check the file list anyway; generated code checked into the repo often isn't marked as such.

Every question pays for the whole repository

With long context, you pay per token for everything in the window, on every turn. In a long session that adds up, and latency grows with input size too. Prompt caching, where your provider offers it, reduces the cost of re-sending an identical prefix, but it doesn't make the model read less. Once you've located the problem, start a fresh conversation with a narrower dump.

The snapshot goes stale

A pasted repository is frozen at the moment you generated it. Three edits later, the model is reasoning about code that no longer exists. Regenerate from the new commit, or paste only the changed files with their paths and say they replace the earlier versions.

When to use RAG for code search

Retrieval earns its keep when at least one of these is true:

Agentic search or embeddings?

Identifiers are exact strings, and exact strings are what grep is for. rg -n "def validate_iban" finds the function every time; an embedding search may rank a nearby validate_bic higher because the two look alike. Agents chain these searches: find the definition, then every caller outside the tests, then fall back to a concept search when the name is unknown.

rg -n "def validate_iban" --type py
rg -n "validate_iban\(" --type py -g '!tests/**'
rg -il "throttle|rate.?limit" src/ | head -20

Grep struggles when you don't know the vocabulary. "Where do we stop users from sending too many emails?" might live in a class called OutboundQuota that never says "throttle". That gap is where embeddings help, and it's why I'd add them to a grep-first system rather than start with them.

Agentic search costs round trips and latency, and needs a tool-capable environment such as a CLI agent or IDE. In a plain chat window, you do the grepping and paste the results.

How to chunk code and the docs around it

If you do build embedding retrieval for source code, split on syntax boundaries (whole functions and classes, using a tree-sitter-based splitter), not on fixed character counts. A chunk that starts halfway through a function and ends halfway through the next one embeds as nonsense. Prefix every chunk with its file path and enclosing class, so def save(self) in models/invoice.py doesn't look identical to every other save.

For the prose half of the corpus (READMEs, ADRs, runbooks, exported issue threads), a general text chunker for embeddings and RAG is the right tool. Repo2Txt's chunker runs in the browser, splits by sentences, paragraphs, Markdown headings or lines, offers token presets of 512/64, 1024/128, 256/32 and 8000/400 (chunk size and overlap), and exports .txt, .json or .jsonl ready for an embedding script. Splitting docs by Markdown headings keeps each section intact. It is not syntax-aware, so for source files use a code splitter, or split by lines with overlap as a rough fallback.

Full repo in context window vs embeddings: how do they compare?

 

Full repo or slice in context

Embedding RAG

Agentic search (grep + read)

Setup

Seconds; no infrastructure

Chunker, embedder, vector store, reindex job

A tool-capable agent or IDE

Cost per question

High; whole context every turn

Low; only top-k chunks

Medium; several tool calls and file reads

Cross-file reasoning

Best, if everything relevant is included

Weakest; chunks lose their surroundings

Good; the agent follows imports and callers

Exact identifier lookup

Good, if the file is present

Unreliable for look-alike names

Excellent

Fuzzy "where do we do X"

Good at small sizes

Best

Depends on guessing the right terms

Freshness

Snapshot; regenerate by hand

Only as fresh as the last reindex

Always reads the current files

Seeing what the model saw

Open the file

Log the retrieved chunks

Read the tool-call transcript

Size ceiling

The context window (practically half of it)

Effectively unlimited

Effectively unlimited, but slower as repos grow

Typical failure

Distracted by close-but-wrong code

Relevant code never retrieved

Searched for the wrong term, stopped early

The "typical failure" row decides how you debug. Long context gives confident answers about the wrong code; RAG ignores code that exists; agents report "not found" for code that lives under another name.

A decision flowchart for long context vs RAG

This is the routing logic I'd follow, written out so it can be drawn as a diagram or pasted into a design doc. It borrows the Self-Route idea from the 2024 DeepMind and Michigan study: start with the cheaper path you trust, and escalate when it isn't enough.

START: a code task (question, bug, review, refactor)
│
├─ Q1. Will many people ask many questions over this repo, on an ongoing basis?
│ └─ YES → build retrieval (agentic search first; add embeddings for
│ docs and fuzzy concept search). Keep single-file dumps for deep dives.
│
├─ Q2. Do you know which modules the task touches?
│ ├─ YES → measure those files after filtering
│ │ ├─ ≤ half the window → PASTE them as one file (with the full tree)
│ │ └─ > half the window → split the task, or repo map + key files,
│ │ or hand it to an agent
│ │
│ └─ NO → measure the whole filtered repo
│ ├─ ≤ half the window → PASTE it, ask the model to locate the code,
│ │ then start fresh with a narrower paste
│ └─ > half the window → RETRIEVE: grep or an agent to locate,
│ then PASTE the located files in full
│
└─ After any answer: did the model cite code that is actually in the input?
 └─ NO or UNSURE → narrow the input and ask again

In most paths retrieval and pasting aren't rivals: retrieval locates, pasting reasons. And the expensive branch, building a pipeline, is triggered by usage pattern rather than repo size alone.

What does a sensible hybrid look like?

For mid-sized repositories, the two-pass approach usually beats both extremes.

Pass 1: locate. Give the model a map, not the territory. That can be the directory tree alone, or the tree plus signatures. Aider's repo map shows how little this needs to be: according to the 2026 Harness Engineering study, it ranks tree-sitter symbols by relevance within a default budget of 1,024 tokens. Ask: "Which files would you need to read to answer this? List paths only."

Pass 2: reason. Paste those files in full, with the tree on top so the model knows where they sit in the project, and ask the real question in a fresh conversation. You get long-context reasoning over a small, relevant input, which is the combination the research favours.

A prompt for pass 2 might be laid out like this:

Context: directory tree of the full repo, then 6 files from it.
Live entry point: api/routes/refunds.py
Ignore: anything under legacy/ (dead code, kept for reference)

<directory tree>

--- api/routes/refunds.py ---
<file contents>

--- payments/refund.py ---
<file contents>
...

Question: why can a refund be issued twice when the client retries?
Cite file paths and function names for every claim.

The last line matters. Asking for paths and function names turns a fluent answer into a checkable one.

Common mistakes on both sides

The whole RAG vs long context decision comes down to two inputs: the filtered size of what the task needs compared with half the window, and how often the question will be asked. Below the line, a well-trimmed single file is simpler and easier to audit than any pipeline. Above it, retrieve with grep first, then paste what you found.

Frequently asked questions

Is RAG dead now that models have million-token context windows?

No. Large windows make pasting viable for far more codebases, but Chroma's 2025 Context Rot report found all 18 frontier models it tested lost accuracy as inputs grew. Retrieval still wins when the code exceeds the window, when many people query the same repository, or when answers must cite sources. For code specifically, retrieval has shifted from vector stores toward agents that search files with grep.

How many tokens of code can I paste into an LLM before quality drops?

There is no fixed cutoff, because accuracy declines gradually with length rather than at a cliff. A practical rule of thumb is to keep the filtered code a task needs under about half the model's context window, leaving room for the conversation and the answer. Below roughly 100K tokens, pasting a well-trimmed file is usually the simplest choice for most current frontier models.

Does Claude Code use RAG or embeddings to search a codebase?

No vector embeddings. A July 2026 source-code study of eleven coding agents found that Claude Code searches code with ripgrep, shell commands and on-demand file reads, plus CLAUDE.md context files. The same study found none of the eleven agents, including Codex CLI, Gemini CLI and Aider, retrieved code with embeddings. Anthropic said in 2025 that agentic search beat its earlier vector-index approach.

Can I use a general text chunker to split source code for embeddings?

For prose such as READMEs, design docs and runbooks, yes: splitting by Markdown headings or paragraphs keeps sections intact. For source files, a syntax-aware splitter that cuts at function and class boundaries works better, because fixed-size chunks split functions and confuse similarity search. Repo2Txt's Text Chunker splits by sentences, paragraphs, headings or lines, so use line mode with overlap only as a rough fallback for code.

Is long context more expensive than RAG for code questions?

Usually, per question. With long context you pay for every token in the window on every turn, while RAG sends only the retrieved chunks. A 2024 Google DeepMind and University of Michigan study found long context gave better answers when resources were ample but RAG was far cheaper. Prompt caching narrows the cost gap for repeated prefixes, but the model still processes the whole input.