What “Context” Means in AI Terms
In AI,
context is any
structured, attributed information supplied at inference time that shapes model reasoning. It is not “more text”; it is
information with metadata and accountability.
Constituents- Evidence: documents, tables, schemas, logs, tickets, code blocks.
- State: user/tenant identity, roles, locale, feature flags, session history.
- Signals: freshness (timestamps/ETags), provenance (URIs/commits), data-quality scores, risk classifications.
- Controls: system instructions, refusal policies, output schemas, tool/function contracts.
Five accountability questions (must be answerable for each item)- Why is this here? (salience/intent)
- Where did it come from? (provenance/lineage)
- Who may see it? (ACL/jurisdiction)
- How fresh is it? (SLA/expiry)
- What if removed? (impact/ablation)
A well-built context layer turns a model from a generic generator into a
policy-compliant reasoning system. If you can’t answer the five questions, you’re not doing context engineering—you’re pasting data.
Anti-patterns to avoid- Monolithic “wall-of-text” pastes with no provenance nearby.
- Mixing user content and system policies in the same section.
- Relying on embeddings alone without ACL filters or recency bounds.
- Letting output schemas float (no validation/repair loop).
The Context Budget: Beyond Token Windows
Every production AI system operates under a
context budget — a finite set of computational, temporal, and governance constraints that determine how much information can safely and efficiently be fed into a model at inference time.
A context budget isn’t simply about the
maximum token window; it’s an engineering equilibrium between
space, speed, risk, and cost.
Why a Budget Exists
Large Language Models process every token in their context window using quadratic attention.
This means that doubling the text size quadruples compute time and GPU memory consumption.
As a result, adding “just a bit more context” can push inference latency from 200 ms to several seconds, breaking the real-time experience users expect.Equally, not all context tokens are created equal.
Some carry operational rules or schemas (system prompts), while others carry user data, retrieved facts, or metadata.
Balancing these types is essential: an overly large system prompt suffocates retrieval; too much evidence crowds out control signals.A well-engineered distribution typically reserves:
- ~30% for system policies, instructions, schemas, and summaries
- ~70% for retrieved evidence and state context
This ratio keeps the model grounded in governance while leaving sufficient semantic room for reasoning.
The Four Axes of the Context Budget
- Token Space — Physical capacity (e.g., 128k window).
Tokenization and structure determine how efficiently context fits.
Compact formatting, deduplication, and structured sections preserve meaning with fewer tokens.
- Latency — User tolerance thresholds.
Aim for 200 ms p99 for assistive interactions, up to 800 ms for analytical or batch responses.
Above one second, perceived system intelligence drops sharply, even if answers are accurate.
- Risk — Security and compliance boundaries.
Apply tenant isolation, PII/PHI exclusion, and export-control filters before retrieval.
The cost of leaking one unauthorized line far exceeds the benefit of adding another relevant one.
- Cost — The economics of context.
Each token has a monetary and environmental cost (GPU seconds, power).
Reuse embeddings, deduplicate aggressively, and schedule non-urgent re-indexing in off-peak windows.
Engineering Principles
- Hard caps per corpus: limit evidence to ≤2 chunks per source, ≤8 total per prompt. Beyond this, marginal accuracy gains plateau while latency and token costs rise steeply.
- Fail early: if authorization, schema validation, or freshness checks fail, stop retrieval and respond safely — don’t pad context with uncertain data.
- Breadth vs. clarity: prefer fewer, highly relevant items that explicitly cover distinct sub-questions over broad, redundant snippets.
- Precision layering: maintain separation between system context (rules, tone, output schemas) and evidence context (facts, documents). Mixing the two dilutes both clarity and controllability.
Optimization Techniques
Latency controls:- Parallelize dense and sparse retrieval; stream tokens as soon as the first chunk is ready.
- Keep warm caches for frequent queries or templates.
- Use CPU SIMD (AVX-512/AMX) for vector pre-filtering.
- Maintain warm per-tenant shards to avoid cold-start penalties.
Cost controls:- Use diff-aware re-embeddings so only changed documents are re-encoded.
- Deduplicate aggressively at ingestion.
- Apply LRU caching to retrieval results.
- Schedule embedding refresh jobs during low-load windows.
Safe Operating Boundaries
Empirically, optimal configurations balance quality and efficiency when:
- System + schema context ≤ 35% of window
- Retrieved evidence ≤ 8 chunks or 3–5k tokens total
- Full request end-to-end ≤ 200 ms p95 latency
Crossing these limits introduces non-linear degradation in both responsiveness and reasoning precision.Ultimately,
context engineering is resource engineering:
not about filling the model’s memory, but about
curating the minimal, verifiable information necessary for correct reasoning within defined constraints.
The Context Supply Chain
In modern AI systems, context is not a static input; it’s a
supply chain that moves data through defined, verifiable stages.
Each stage transforms raw information into a structured, trusted context before it reaches the model, ensuring
data integrity, traceability, and auditability.A well-engineered supply chain guarantees:
- Integrity: no unauthorized alteration or corruption.
- Traceability: every evidence item links to its origin.
- Auditability: the entire path from data source to prompt is reproducible.
Source Registration
Register every data domain — documents, databases, knowledge bases, or log streams — with explicit metadata.
Record ownership, lineage, refresh SLA, access level, and compliance scope.
Tag each dataset with jurisdictional attributes (e.g., EU-only, HIPAA, export-controlled) to prevent downstream policy conflicts.
Normalization & Enrichment
Normalize content into consistent formats such as Markdown, JSON, or Parquet.
Extract logical structures: titles, anchors, tables, and captions.
Compute quality metrics including OCR confidence, duplication rate, and table integrity.
Attach provenance metadata — URI, commit hash, content hash, and last update timestamp — so each entry is a verifiable artifact.
Indexing & Routing
Build hybrid indices optimized for different retrieval modes:
- Dense (vector) for semantic similarity.
- Sparse (BM25) for lexical precision.
- Structured (SQL) for deterministic lookups.
- Graph for relationships and overrides.
Assign routing metadata such as tenant, locale, risk class, and retention period.
This allows retrieval systems to target the correct shard with full isolation and precision.
Retrieval Plan
Retrieval should be
declarative and version-controlled.
Each query follows a defined retrieval plan — not a heuristic.Example (YAML):plan:
- dense: KB.en, k: 20, filter: {tenant: A, risk: "medium", lang: "en"}
- sparse: Policies.en, k: 10, must: ["refund", "RMA"], updated_within: "90d"
fuse: RRF(alpha: 0.7)
caps: {total_items: 8, per_corpus: 2}Plans define how to search, fuse, and cap results.
They are
diffable, testable, and auditable, forming a governance layer between data and inference.
Packaging & Delivery
Serialize retrieved results into consistent sections with co-located metadata:
SYSTEM_POLICY,
FACT_EVIDENCE[],
TABLE_SLICE,
FUNCTION_SCHEMAS, and
USER_QUERY.
Apply redaction masks before injection and include valid-as-of timestamps to ensure both security and temporal accuracy.
Boundary Controls & Artifacts
At the delivery boundary, enforce output schemas, apply refusal policies, and validate compliance.
Every context package generates traceable artifacts — retrieval plan version, evidence handles, index versions, latency metrics, and verification logs.
These form the
audit trail of how each answer was constructed.
Selection & Structuring: Designing for Salience, Diversity, Coverage
Selection, not “top-N”—match the
intent and cover its
sub-tasks within budget.
Selection logic- Salience score = f(semantic similarity, query type, source credibility, recency).
- Diversity: penalize near-dupes; enforce multi-corpus representation.
- Coverage: decompose query; choose items covering distinct sub-questions.
- Hard includes: domain-critical clauses (e.g., effective dates, eligibility rules).
- Hard excludes: stale/archived, outside ACL, low-quality/OCR.
Structuring logic (sections beat walls of text)