Context Engineering
When to Use
Trigger phrases:
"context engineering"
"Design and manage the context window for AI coding agents"
When setting up AI agent instructions for a project
When optimizing agent performance on large codebases
When managing context window limits for complex tasks
When designing multi-agent systems with shared context
When NOT to Use
- For simple one-off prompts
- When the codebase fits entirely in context
Overview
Context Engineering is the practice of designing what information an AI agent sees and in what order. The right context produces correct output; the wrong context produces hallucinations.
Workflow
- Map information needs - What does the agent need to know?
- Prioritize - Critical context first, nice-to-have last
- Structure - AGENTS.md, .cursor/rules/, system prompts
- Manage loading - Progressive disclosure, lazy loading
- Optimize tokens - Compress, deduplicate, summarize
- Test - Does the agent produce correct output with this context?
Anti-Rationalization Table
| Rationalization |
Reality |
| "More context is always better" |
Context window has limits. Noise degrades signal. Prioritize ruthlessly. |
| "The agent will figure it out" |
Without explicit context, agents hallucinate patterns and APIs |
| "README is enough" |
Agents need different context than humans - code structure, conventions, gotchas |
Context Architecture
# AGENTS.md (loaded first, always)
- Project overview (2-3 sentences)
- Key commands (test, build, lint)
- File structure map
- Coding conventions
- Known gotchas
# System prompt (agent-specific)
- Role definition
- Quality gates
- Anti-rationalization rules
Process
- Prepare — Gather requirements, verify prerequisites, set up environment
- Execute — Run context engineering workflow with configured parameters
- Verify — Validate output meets requirements, document results
Verification
Code Examples
Python — Token Counting
import tiktoken
def count_tokens(text: str, model: str = "gpt-4") -> int:
"""Count tokens for a given text and model."""
try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
encoding = tiktoken.get_encoding("cl100k_base")
return len(encoding.encode(text))
def truncate_to_limit(text: str, max_tokens: int, model: str = "gpt-4") -> str:
"""Truncate text to fit within token limit, preserving complete tokens."""
encoding = tiktoken.encoding_for_model(model)
tokens = encoding.encode(text)
if len(tokens) <= max_tokens:
return text
return encoding.decode(tokens[:max_tokens])
# Usage
prompt = "You are a senior engineer. Follow these rules..."
print(count_tokens(prompt)) # ~11 tokens
truncated = truncate_to_limit(prompt * 50, 200)
Python — Context Window Manager with Priority Eviction
class ContextManager:
"""Manages context window with priority-based eviction.
Highest-priority content survives when the total exceeds max_tokens.
"""
def __init__(self, max_tokens: int = 8000, model: str = "gpt-4"):
self.max_tokens = max_tokens
self.sections: list[dict] = []
self._encoding = tiktoken.get_encoding("cl100k_base")
def add(self, content: str, priority: int = 5):
tokens = len(self._encoding.encode(content))
self.sections.append({
"content": content,
"priority": priority,
"tokens": tokens,
})
self._evict()
def _evict(self):
total = sum(s["tokens"] for s in self.sections)
if total <= self.max_tokens:
return
self.sections.sort(key=lambda s: s["priority"])
while total > self.max_tokens and self.sections:
removed = self.sections.pop(0)
total -= removed["tokens"]
def build(self) -> str:
"""Assemble context string, highest priority first."""
ordered = sorted(self.sections, key=lambda s: (-s["priority"], s["tokens"]))
return "\n\n---\n\n".join(s["content"] for s in ordered)
# Usage
ctx = ContextManager(max_tokens=4000)
ctx.add("Project overview and architecture decisions", priority=10)
ctx.add("Full API reference with all endpoints", priority=5)
ctx.add("Historical changelog and edge cases", priority=1)
agent_prompt = ctx.build()
Node.js — Token Counting
import { encoding_for_model } from "tiktoken";
function countTokens(text, model = "gpt-4") {
const enc = encoding_for_model(model);
const count = enc.encode(text).length;
enc.free(); // tiktoken requires explicit free
return count;
}
function truncateToLimit(text, maxTokens, model = "gpt-4") {
const enc = encoding_for_model(model);
const tokens = enc.encode(text);
if (tokens.length <= maxTokens) {
enc.free();
return text;
}
const result = enc.decode(tokens.slice(0, maxTokens));
enc.free();
return result;
}
Node.js — Progressive Context Loader
import { readFileSync } from "fs";
import { encoding_for_model } from "tiktoken";
class ProgressiveContext {
constructor(maxTokens = 8000, model = "gpt-4") {
this.maxTokens = maxTokens;
this.enc = encoding_for_model(model);
this.sections = [];
}
add(name, content, priority = 5) {
const tokens = this.enc.encode(content).length;
this.sections.push({ name, content, priority, tokens });
this.sections.sort((a, b) => b.priority - a.priority);
}
/** Build prompt fitting within maxTokens, highest priority first */
compile(separator = "\n\n---\n\n") {
let result = "";
for (const s of this.sections) {
const candidate = result ? result + separator + s.content : s.content;
if (this.enc.encode(candidate).length > this.maxTokens) break;
result = candidate;
}
return result;
}
cleanup() {
this.enc.free();
}
}
// Usage
const ctx = new ProgressiveContext(6000);
ctx.add("rules", readFileSync("AGENTS.md", "utf-8"), 10);
ctx.add("types", readFileSync("types.d.ts", "utf-8"), 7);
ctx.add("docs", readFileSync("README.md", "utf-8"), 3);
const prompt = ctx.compile();
ctx.cleanup();
Setup & Configuration
# Python — install tokenizer
pip install tiktoken
# Node.js — install tokenizer
npm install tiktoken
# lighter alternative with no WASM dependency
npm install gpt-tokenizer
# Verify installation works
python -c "import tiktoken; print(tiktoken.get_encoding('cl100k_base').encode('hello'))"
Common Issues & Troubleshooting
| Problem |
Solution |
| Context window exceeded mid-task |
Break task into subtasks; use progressive disclosure; summarize intermediate results before continuing |
| Agent ignores instructions at end of prompt |
Place critical instructions first (primacy effect); use AGENTS.md loaded at session start |
| Token count differs between environments |
Use the same tokenizer library (tiktoken) everywhere; always specify the exact model name |
| File loading order affects output quality |
Load critical-path files first; use dependency ordering, not alphabetical |
| Multi-turn context drift over long sessions |
Re-inject core instructions every N turns (summary + system prompt re-insertion pattern) |
| Agent hallucinates file paths or APIs |
Include an explicit file tree map and API surface summary in the context block |
Monetization
- Context audit consulting — Charge $500-2000 per engagement to audit and optimize context setups for teams using AI coding agents. Identify wasted tokens, structural gaps, and priority misalignments across their AGENTS.md, rules files, and system prompts.
- Template marketplace — Sell project-specific context templates ($20-100 each) for popular stacks (Next.js, Django, FastAPI, Rails, Spring Boot) with pre-optimized token budgets, priority ordering, and file structure maps.
- Training workshops — Run 2-day remote workshops ($3000-8000) covering token economics, progressive disclosure design, multi-agent context sharing, CI-based context validation, and debugging session drift.
- CI context validation SaaS — Build a service that checks PRs for context health: token budgets, stale references, duplicate sections, priority inversions, and missing critical paths. $10-50/month per repo.
- Internal tooling development — Build custom context management tooling for enterprise teams: token budget dashboards, auto-summarization pipelines that compress verbose docs into agent-optimal chunks, and collaborative context editors with diff/review workflows.
1---2name: context-engineering3description: Use when design and manage the context window for AI coding agents. Structure prompts, manage file loading, and optimize token usage for maximum agent effectiveness. Use when designing and manage the context window for ai coding agents.4license: Apache-2.05---678# Context Engineering910## When to Use11**Trigger phrases:**12- "context engineering"13- "Design and manage the context window for AI coding agents"141516- When setting up AI agent instructions for a project17- When optimizing agent performance on large codebases18- When managing context window limits for complex tasks19- When designing multi-agent systems with shared context2021## When NOT to Use2223- For simple one-off prompts24- When the codebase fits entirely in context2526## Overview2728Context Engineering is the practice of designing what information an AI agent sees and in what order. The right context produces correct output; the wrong context produces hallucinations.2930## Workflow31321. **Map information needs** - What does the agent need to know?332. **Prioritize** - Critical context first, nice-to-have last343. **Structure** - AGENTS.md, .cursor/rules/, system prompts354. **Manage loading** - Progressive disclosure, lazy loading365. **Optimize tokens** - Compress, deduplicate, summarize376. **Test** - Does the agent produce correct output with this context?3839## Anti-Rationalization Table4041| Rationalization | Reality |42|---|---|43| "More context is always better" | Context window has limits. Noise degrades signal. Prioritize ruthlessly. |44| "The agent will figure it out" | Without explicit context, agents hallucinate patterns and APIs |45| "README is enough" | Agents need different context than humans - code structure, conventions, gotchas |4647## Context Architecture4849```markdown50# AGENTS.md (loaded first, always)51- Project overview (2-3 sentences)52- Key commands (test, build, lint)53- File structure map54- Coding conventions55- Known gotchas5657# System prompt (agent-specific)58- Role definition59- Quality gates60- Anti-rationalization rules61```626364## Process65661. **Prepare** — Gather requirements, verify prerequisites, set up environment671. **Execute** — Run context engineering workflow with configured parameters681. **Verify** — Validate output meets requirements, document results6970## Verification7172- [ ] AGENTS.md is under 500 lines73- [ ] Key commands are copy-pasteable74- [ ] File structure map is accurate75- [ ] No redundant information across context files76- [ ] Agent produces correct output with this context7778## Code Examples7980### Python — Token Counting8182```python83import tiktoken8485def count_tokens(text: str, model: str = "gpt-4") -> int:86 """Count tokens for a given text and model."""87 try:88 encoding = tiktoken.encoding_for_model(model)89 except KeyError:90 encoding = tiktoken.get_encoding("cl100k_base")91 return len(encoding.encode(text))929394def truncate_to_limit(text: str, max_tokens: int, model: str = "gpt-4") -> str:95 """Truncate text to fit within token limit, preserving complete tokens."""96 encoding = tiktoken.encoding_for_model(model)97 tokens = encoding.encode(text)98 if len(tokens) <= max_tokens:99 return text100 return encoding.decode(tokens[:max_tokens])101102103# Usage104prompt = "You are a senior engineer. Follow these rules..."105print(count_tokens(prompt)) # ~11 tokens106truncated = truncate_to_limit(prompt * 50, 200)107```108109### Python — Context Window Manager with Priority Eviction110111```python112class ContextManager:113 """Manages context window with priority-based eviction.114 115 Highest-priority content survives when the total exceeds max_tokens.116 """117 118 def __init__(self, max_tokens: int = 8000, model: str = "gpt-4"):119 self.max_tokens = max_tokens120 self.sections: list[dict] = []121 self._encoding = tiktoken.get_encoding("cl100k_base")122 123 def add(self, content: str, priority: int = 5):124 tokens = len(self._encoding.encode(content))125 self.sections.append({126 "content": content,127 "priority": priority,128 "tokens": tokens,129 })130 self._evict()131 132 def _evict(self):133 total = sum(s["tokens"] for s in self.sections)134 if total <= self.max_tokens:135 return136 self.sections.sort(key=lambda s: s["priority"])137 while total > self.max_tokens and self.sections:138 removed = self.sections.pop(0)139 total -= removed["tokens"]140 141 def build(self) -> str:142 """Assemble context string, highest priority first."""143 ordered = sorted(self.sections, key=lambda s: (-s["priority"], s["tokens"]))144 return "\n\n---\n\n".join(s["content"] for s in ordered)145146147# Usage148ctx = ContextManager(max_tokens=4000)149ctx.add("Project overview and architecture decisions", priority=10)150ctx.add("Full API reference with all endpoints", priority=5)151ctx.add("Historical changelog and edge cases", priority=1)152agent_prompt = ctx.build()153```154155### Node.js — Token Counting156157```javascript158import { encoding_for_model } from "tiktoken";159160function countTokens(text, model = "gpt-4") {161 const enc = encoding_for_model(model);162 const count = enc.encode(text).length;163 enc.free(); // tiktoken requires explicit free164 return count;165}166167function truncateToLimit(text, maxTokens, model = "gpt-4") {168 const enc = encoding_for_model(model);169 const tokens = enc.encode(text);170 if (tokens.length <= maxTokens) {171 enc.free();172 return text;173 }174 const result = enc.decode(tokens.slice(0, maxTokens));175 enc.free();176 return result;177}178```179180### Node.js — Progressive Context Loader181182```javascript183import { readFileSync } from "fs";184import { encoding_for_model } from "tiktoken";185186class ProgressiveContext {187 constructor(maxTokens = 8000, model = "gpt-4") {188 this.maxTokens = maxTokens;189 this.enc = encoding_for_model(model);190 this.sections = [];191 }192193 add(name, content, priority = 5) {194 const tokens = this.enc.encode(content).length;195 this.sections.push({ name, content, priority, tokens });196 this.sections.sort((a, b) => b.priority - a.priority);197 }198199 /** Build prompt fitting within maxTokens, highest priority first */200 compile(separator = "\n\n---\n\n") {201 let result = "";202 for (const s of this.sections) {203 const candidate = result ? result + separator + s.content : s.content;204 if (this.enc.encode(candidate).length > this.maxTokens) break;205 result = candidate;206 }207 return result;208 }209210 cleanup() {211 this.enc.free();212 }213}214215// Usage216const ctx = new ProgressiveContext(6000);217ctx.add("rules", readFileSync("AGENTS.md", "utf-8"), 10);218ctx.add("types", readFileSync("types.d.ts", "utf-8"), 7);219ctx.add("docs", readFileSync("README.md", "utf-8"), 3);220const prompt = ctx.compile();221ctx.cleanup();222```223224## Setup & Configuration225226```bash227# Python — install tokenizer228pip install tiktoken229230# Node.js — install tokenizer231npm install tiktoken232# lighter alternative with no WASM dependency233npm install gpt-tokenizer234235# Verify installation works236python -c "import tiktoken; print(tiktoken.get_encoding('cl100k_base').encode('hello'))"237```238239## Common Issues & Troubleshooting240241| Problem | Solution |242|---|---|243| Context window exceeded mid-task | Break task into subtasks; use progressive disclosure; summarize intermediate results before continuing |244| Agent ignores instructions at end of prompt | Place critical instructions first (primacy effect); use AGENTS.md loaded at session start |245| Token count differs between environments | Use the same tokenizer library (tiktoken) everywhere; always specify the exact model name |246| File loading order affects output quality | Load critical-path files first; use dependency ordering, not alphabetical |247| Multi-turn context drift over long sessions | Re-inject core instructions every N turns (summary + system prompt re-insertion pattern) |248| Agent hallucinates file paths or APIs | Include an explicit file tree map and API surface summary in the context block |249250## Monetization251252- **Context audit consulting** — Charge $500-2000 per engagement to audit and optimize context setups for teams using AI coding agents. Identify wasted tokens, structural gaps, and priority misalignments across their AGENTS.md, rules files, and system prompts.253- **Template marketplace** — Sell project-specific context templates ($20-100 each) for popular stacks (Next.js, Django, FastAPI, Rails, Spring Boot) with pre-optimized token budgets, priority ordering, and file structure maps.254- **Training workshops** — Run 2-day remote workshops ($3000-8000) covering token economics, progressive disclosure design, multi-agent context sharing, CI-based context validation, and debugging session drift.255- **CI context validation SaaS** — Build a service that checks PRs for context health: token budgets, stale references, duplicate sections, priority inversions, and missing critical paths. $10-50/month per repo.256- **Internal tooling development** — Build custom context management tooling for enterprise teams: token budget dashboards, auto-summarization pipelines that compress verbose docs into agent-optimal chunks, and collaborative context editors with diff/review workflows.257