TL;DR
A 200āÆKātoken context window isnāt a free pass to dump an entire repo. System prompts, tool schemas, fileātree listings, and conversation history can eat 70ā80āÆ% of the budget before the first line of relevant code even appears. Precise token accounting (using the cl100k_base tokenizer from OpenAIās tiktoken library) shows why ājust retrieve lessā isnāt a silver bullet and why structural preāfiltering is the only scalable remedy.
What a ā200K token windowā Actually Has to Hold in a Real Request
When you invoke an AIācoding agent, the request payload is rarely just āhereās the file I need.ā The model must see a complete execution context, which includes several mandatory components:
| Component | Typical Size (tokens) | Why Itās Needed |
|---|---|---|
| System Prompt | 150 ā 400 | Sets the agentās role, behavioural constraints, and safety guardrails. |
| Tool Schemas (e.g., fileāread, search, edit) | 300 ā 800 | Describes the JSON schema for each tool the agent may call; required for toolāuse reasoning. |
| Conversation History (previous userāassistant turns) | 0 ā 30āÆK | Enables continuity across a multiāstep edit session. |
| FileāTree Dump | 5āÆK ā 30āÆK (depends on repo size) | Gives the model a map of the repoās hierarchical layout so it can resolve relative paths. |
| Retrieved Files (raw source code, docs) | 10āÆK ā 80āÆK | The actual content the agent will reason over; often includes many files that are not directly relevant. |
| User Query / Task Description | 50 ā 300 | The concrete request (e.g., āadd validation to order.service.tsā). |
ā ļø Callout: The token budget is consumed as soon as the payload is sent; the model never āskipsā the system prompt or schema. Every extra line reduces the space left for the code you actually want it to see.
Token Accounting Basics
| Tokenizer | Model(s) | Approx. tokens per English word | Approx. tokens per sourceācode line* |
|---|---|---|---|
cl100k_base (OpenAI tiktoken) | GPTā4āTurbo, GPTā4āo | 1.3 | 0.7 ā 1.0 (depends on whitespace, identifiers) |
*The line token count varies widely; a typical TypeScript line averages ~1āÆtoken, while a dense Python line can be ~0.8āÆtokens.
Note: All numbers below are measured with
cl100k_base. Different providers use slightly different tokenizers, so the absolute counts will shift, but the proportional budget pressure remains the same.
A Worked Example ā Token Budget Drain on a MidāSize Repository
Below is a concrete audit of a 400āfile, ~120āÆKB TypeScript/JavaScript monorepo (āāÆ18āÆK source lines). The goal is to understand how many tokens the request consumes before any line of the target file (src/payments/processor.ts) is even present.
1. Assemble the Payload
2. Token Count Breakdown
| Payload Piece | Raw Characters | Tokens (cl100k_base) | Comments |
|---|---|---|---|
| System Prompt | 2āÆ200 | 180 | Minimal āyou are a senior staff engineer ā¦ā |
| Tool Schemas | 5āÆ800 | 560 | 4 tools, each with a 1āÆ400āchar JSON schema |
| Conversation History | 12āÆ400 | 8āÆ100 | 3 prior turns (~4āÆK tokens each) |
| FileāTree Dump | 84āÆ900 | 32āÆ400 | Tree printed with tree -L 3 and fileāsize annotations |
| Retrieved Files (full repo) | 1āÆ310āÆ000 | 92āÆ200 | 400 files Ć avg. 3āÆ250 chars/file |
| User Task Description | 340 | 30 | Short imperative |
| Subtotal (everything except target file) | - | 133āÆ470 | 66āÆ% of a 200āÆK window |
Target file (processor.ts) | 3āÆ200 | 2āÆ900 | First relevant line appears at token #136āÆ371 |
| Total | - | 136āÆ370 | Leaves ~63āÆ630 tokens for model output & further retrieval |
Observations
- Fileātree alone consumes ~32āÆK tokens ā roughly 16āÆ% of the window.
- Conversation history quickly dominates when you have multiāstep interactions; each turn can be a few thousand tokens.
- Retrieving the entire repo is the biggest cost. Even a modest 400āfile codebase eats ~92āÆK tokens, leaving less than 100āÆK for anything else.
If you add a second round of retrieval (common in ārefine & iterateā loops), youāll exceed the window after just two cycles.
3. Visualizing the Token Allocation
ā” Quick Take: Even with aggressive pruning, the noise (prompts, schemas, tree) can swallow half the context window before the model sees the line you care about.
Why āJust Retrieve Lessā Isnāt Free Either
A common reaction is to cut the retrieval size: āOnly fetch the files we think are relevant.ā The intuition feels right, but the tradeāoff is subtle.
| Reduction Strategy | Token Savings | Risk |
|---|---|---|
| Topāk similarity ranking (e.g., 10 most similar files) | ~50āÆK tokens saved | May exclude files that affect the blast radius (indirect dependencies, config, tests). |
| Depthālimited tree (only leaf nodes) | ~15āÆK tokens saved | Loses structural context (module hierarchy, import paths). |
| Static āignore .md/*.test.jsā filter | ~5āÆK tokens saved | Often removes useful documentation or failing test cases that expose regressions. |
The Retrieval Problem This Compounds
When you drop files indiscriminately, you increase the chance of missing the true dependency slice. A downstream regression can slip past the model because the agent never saw the piece of code that caused the bug.
See also: the earlier discussion in Blog #2 ā the retrieval problem this compounds and the followāup on Blog #19 ā how memory and context budgets interact.
In practice, engineers see two symptoms:
- FalseāPositive āNo relevant codeā ā the agent claims it canāt find anything, yet the missing file was simply filtered out.
- Silent Regression ā the agent produces a patch that passes local tests but breaks a distant module that was never part of the prompt.
Both outcomes erode trust faster than a mere ācontext limitā error.
The Actual Fix: Structural PreāFiltering
Instead of feeding the whole tree or a crude similarity list, preāfilter the repo into a minimal, structurally coherent slice that contains all code reachable from the target fileās callāgraph.
How It Works
- Static Dependency Graph Build ā parse the repo once (e.g., using the TypeScript compiler API or a languageāagnostic AST tool) to produce a directed graph of imports/exports.
- Slice Extraction ā given the entry point (
processor.ts), walk the graph to collect every node reachable within N hops (commonly 2ā3). - MetadataāOnly Tree ā send a compact fileātree that lists only the sliced files; each entry includes size and import depth, not the full source.
- Selective Retrieval ā request the raw contents only for the slice; all other files stay on the server, never consuming tokens.
Token Savings (Same 400āFile Repo)
| Payload Piece | Tokens Before | Tokens After | Ī Tokens |
|---|---|---|---|
| FileāTree (full) | 32āÆ400 | 4āÆ800 | ā27āÆ600 |
| Retrieved Files (full) | 92āÆ200 | 14āÆ500 | ā77āÆ700 |
| Total Savings | 124āÆ600 | 19āÆ300 | ā105āÆ300 |
Result: The same request now fits comfortably under 50āÆK tokens, leaving ample room for multiāturn dialogue, richer tool usage, and higherāquality output.
Benefits Beyond Token Economy
| Benefit | Why It Matters |
|---|---|
| Full BlastāRadius Visibility | The slice includes all transitive dependencies, so the model can reason about side effects. |
| Deterministic Retrieval | The slice is defined by static analysis, not by heuristic similarity that can drift over time. |
| Predictable Token Budget | Token count becomes a function of graph depth, not repo size, making capacity planning trivial. |
CodeFundi ā Structural PreāFiltering Done Right
CodeFundiās API delivers the structural slice automatically. By feeding the model a dependencyāaware payload instead of a raw fileātree, we guarantee that the context window is spent on meaningful code, not on the surrounding noise. The service also returns a tokenābudget estimate for each request, letting you stay safely under the modelās limit while preserving the full blastāradius view required for safe AIādriven edits.
FAQ
Why does my AI coding tool run out of context on large repos?
Because every component of the request - system prompt, tool schemas, fileātree, conversation history, and retrieved source - consumes tokens. In typical multiāturn sessions the nonācode overhead can exceed half the window before the first line of your target file is even seen.
How many tokens does a typical codebase use?
A 400āfile JavaScript/TypeScript monorepo (āāÆ18āÆK source lines) consumes roughly 90āÆK tokens when the entire repo is retrieved, plus 30āÆK tokens for the fileātree and other scaffolding. The exact number varies with language density and tokenizer, but the pattern holds: the bulk of the context budget is eaten by metadata and irrelevant files.
Does a bigger context window fix AI coding accuracy?
A larger window alleviates the raw tokenābudget pressure but does not solve the underlying problem of noisy payloads. Without structural preāfiltering, even a 400āÆK token window will still be dominated by tree listings and history, leaving less room for actual reasoning. Accuracy improves only when the modelās attention is focused on the relevant dependency slice.
Take Action
Seeing the math in your own repo is the fastest way to stop guessing. Try the live blastāradius demo and instantly see how many tokens your request actually consumes, then let CodeFundi trim the excess.