4. Context Management

Fitting a world into a window

Every language model has a context window — a hard limit on how many tokens it can see at once. For GPT-4 it's 128K tokens. For Claude it's 200K. That sounds like a lot until you start reading files, accumulating tool results, and maintaining conversation history. A single large codebase exploration can burn through 100K tokens in minutes.

Context management is the art of deciding what goes into that window and what gets left out. Get it wrong and the model hallucinates, forgets instructions, or misses the one file that matters. Get it right and a 200K window feels infinite.

Why Context Is Finite

The transformer architecture processes all tokens in the context simultaneously through self-attention. Every token attends to every other token, which means the computational cost scales quadratically with context length. Even with optimizations like FlashAttention and KV-cache, there's a practical ceiling on how much context a model can handle efficiently.

But the harder limit is attention quality. Research on the "lost in the middle" problem shows that models pay less attention to information in the middle of long contexts compared to the beginning and end. Stuffing your context window to capacity doesn't mean the model will actually use everything in it.

This has practical implications:

  • Put important instructions at the beginning (system prompt) and end (recent messages)
  • Don't pad context with "just in case" information — it dilutes attention
  • Summarize and compress aggressively for older conversation history

Anatomy of a Context Window

In a typical coding assistant conversation, the context window contains:

┌─────────────────────────────────────────┐
│ System prompt                    ~2-5K  │  ← Behavioral instructions
├─────────────────────────────────────────┤
│ Conversation history            10-50K  │  ← Previous messages + tool results
├─────────────────────────────────────────┤
│ Current tool results             5-30K  │  ← Files just read, command output
├─────────────────────────────────────────┤
│ Current user message             0.1-2K │  ← The actual request
├─────────────────────────────────────────┤
│ Generation budget               1-8K   │  ← Space for the model's response
└─────────────────────────────────────────┘

The system prompt is non-negotiable — it defines the model's behavior. The generation budget is non-negotiable — the model needs room to respond. Everything else is a tradeoff: more conversation history means less room for file contents, and vice versa.

Conversation Summarization

The simplest context management technique: when conversation history grows too long, summarize older messages and replace them with the summary.

Original (12K tokens):
  User: Read src/auth.ts and explain the token validation logic.
  Assistant: [calls read_file] The file contains... [2K explanation]
  User: What about the refresh token flow?
  Assistant: [calls read_file, calls grep] The refresh flow... [3K explanation]
  User: Can you add rate limiting to the refresh endpoint?
  Assistant: [reads 3 files, edits 2 files, runs tests] Done... [4K explanation]

Summarized (800 tokens):
  [Summary: Explored auth.ts token validation and refresh flow.
   Added rate limiting to refresh endpoint in src/auth.ts and
   src/middleware/rate-limit.ts. Tests passing. Key context:
   tokens expire after 1h, refresh tokens after 7d, rate limit
   is 10 requests per minute per user.]

The summary preserves the decisions and outcomes while discarding the verbose back-and-forth. The model can continue the conversation with full awareness of what happened, using a fraction of the tokens.

When to summarize:

  • When conversation history exceeds ~40% of the context window
  • When older messages contain large tool results (file contents) that are no longer relevant
  • Before starting a new sub-task that doesn't depend on the details of previous work

What to preserve in summaries:

  • Decisions made and their rationale
  • Files that were modified and why
  • Key facts learned about the codebase
  • Errors encountered and how they were resolved
  • User preferences expressed during the conversation

Sliding Window

A simpler approach: keep the N most recent messages and drop everything older. This works surprisingly well for many use cases because the most recent context is usually the most relevant.

function slidingWindow(
  messages: Message[],
  maxTokens: number
): Message[] {
  let totalTokens = 0;
  const result: Message[] = [];

  // Always keep the system message
  // Walk backwards through messages, keeping recent ones
  for (let i = messages.length - 1; i >= 0; i--) {
    const msgTokens = countTokens(messages[i]);
    if (totalTokens + msgTokens > maxTokens) break;
    totalTokens += msgTokens;
    result.unshift(messages[i]);
  }

  return result;
}

The downside: if the model made a critical decision 20 messages ago and the window slides past it, that context is gone. Summarization handles this better, but sliding window is simpler to implement and has no risk of summarization errors.

Hybrid approach: keep a summary of everything before the window plus full detail for recent messages. This is what most production systems use.

Smart Context Selection

Not all context is equal. Reading a 500-line file into context when you only need lines 40-60 wastes 90% of those tokens. Smart context selection means being surgical about what goes in.

Relevant line ranges

Instead of reading entire files, read the specific functions or sections that matter:

// Bad: reads the entire 2000-line file
read_file({ path: "src/server.ts" });

// Good: reads just the route handler
read_file({ path: "src/server.ts", line_start: 142, line_end: 185 });

Coding assistants achieve this by first searching for relevant symbols (function names, class definitions) and then reading only those ranges.

Tree-sitter and AST-aware context

Advanced tools use syntax-tree parsers to understand code structure. Instead of raw line ranges, they extract:

  • The function being modified, plus its type signatures
  • Import statements (to understand dependencies)
  • The enclosing class or module definition
  • Related test functions

This gives the model exactly the context it needs — the function, its types, its dependencies — without the noise of hundreds of unrelated functions in the same file.

Relevance scoring

When the model needs information from multiple files, rank them by relevance:

  • Files mentioned by the user score highest
  • Files imported by relevant files score high
  • Files matching search terms score medium
  • Recently modified files get a small boost

Include files in priority order until you hit the budget. This is essentially what RAG does for unstructured data — and we'll cover that in the next article.

Token Counting

You can't manage context without knowing how much space things take. Token counts don't map neatly to character or word counts:

Text Characters Tokens (approx)
"hello" 5 1
"antidisestablishmentarianism" 28 6
A line of Python code ~40 ~12
1KB of English prose 1,024 ~250
1KB of minified JSON 1,024 ~400

Code and structured data tend to use more tokens per character than prose because tokenizers handle natural language more efficiently.

Practical rule of thumb: 1 token ≈ 4 characters for English, ≈ 3 characters for code. For precise counts, use the tokenizer directly (most providers offer a token counting API or library).

Budget your context window with comfortable margins. If your window is 200K tokens, don't try to use 199K — leave headroom for the model's response and any system overhead.

Caching and Prefixes

A significant optimization: if the first part of your context doesn't change between requests (system prompt, tool definitions, project context), many providers cache the KV-cache for that prefix. This means:

  • Faster responses — the model doesn't reprocess the cached prefix
  • Lower cost — cached input tokens are often billed at a discount

To take advantage of this:

  • Put stable content first: system prompt, then tool definitions, then project context
  • Put volatile content last: recent conversation, current request
  • Don't reorder or modify the stable prefix between requests
┌──────────────────────────────┐
│ System prompt (stable)       │ ← cached
│ Tool definitions (stable)    │ ← cached
│ Project context (stable)     │ ← cached
├──────────────────────────────┤
│ Conversation history (grows) │ ← reprocessed
│ Current message (changes)    │ ← reprocessed
└──────────────────────────────┘

Context Window Strategies for Different Tasks

Short, focused tasks (explain this function, fix this bug):

  • Minimal history needed
  • Load only the relevant file(s)
  • Budget: 10-20K tokens of context, rest for generation

Long, exploratory tasks (understand this codebase, refactor this module):

  • Conversation history grows fast
  • Summarize aggressively after each sub-task
  • Use search tools to load context on-demand rather than pre-loading
  • Budget: rolling 50-80K, with summaries for older work

Multi-file edits (add a feature touching 5 files):

  • Need to hold multiple files simultaneously
  • Load file skeletons (function signatures, class outlines) rather than full contents
  • Read full details only for the section being edited
  • Budget: 30-60K for file context, 10-20K for history

The Attention Tax

Every token in the context window has a cost — not just in API pricing, but in attention quality. The model has a finite amount of "attention" to distribute across all tokens. The more tokens compete for attention, the less each individual token receives.

This is why removing irrelevant context often improves output quality more than adding relevant context. A 10K context with exactly the right information outperforms a 100K context where the right information is buried in noise.

Practical guidelines:

  • Remove boilerplate, comments, and whitespace from code context when the model only needs logic
  • Don't include entire config files when only one setting matters
  • Strip tool results that have been fully processed and aren't needed for the next step
  • Use headings and markers to help the model navigate: "=== RELEVANT FILE ===" or XML tags

Try It — Context Window Budget Planner

Drag the sliders to allocate tokens across the 200K context window. Watch how the budget fills up and how the "lost in the middle" effect distributes attention.

What's Next

Context management tells you how to fit information into a fixed window. But what if the information you need isn't in the conversation at all — it's in a vector database, a documentation site, or a knowledge base? That's retrieval-augmented generation, the subject of the next article.