Skip to content

Context Engineering Is Choosing What Gets In

By Maksym Kuzmitskyi
6 min read
Context Engineering Is Choosing What Gets In

Context Engineering Is Choosing What Gets In

The search found twenty documents. The question needs one current policy and the exception directly below it.

Sending all twenty is easy. Explaining why those twenty belong in this request is the more useful job.

Context engineering is the work of selecting and maintaining the information available during model inference. That includes instructions, a question, relevant conversation, source material and descriptions of available tools. Prompt engineering remains part of it; writing instructions is one selection decision among several.

I like this framing when it leads to code someone can inspect. I like it less when it becomes a grand name for pasting the whole repository into a text box.

Start with different responsibilities

The application has instructions it intends to enforce, a current task it must preserve and evidence it may need to select. Those inputs shouldn't all compete through one relevance score.

An instruction defining the permitted task doesn't become optional because a long document has a higher search score. A current question shouldn't be truncated halfway through a restriction. And a relevant document doesn't gain permission to enter the request merely because it fits.

For our fictional documentation assistant, authorization happens before selection. The assembler receives evidence records already marked readable by trusted application code. A model or document cannot mark itself readable by supplying a field with the right name.

Anthropic's context-engineering article describes curation across these sources and repeated decisions over a running task. Its examples are useful patterns, not a requirement to adopt a particular agent framework.

Budget the assembled request

A context window limits what an invocation can use. An output reserve leaves capacity for generation. The input representation also includes formatting and message overhead, so adding separate document token estimates is not always enough.

The following assembler measures its complete serialized representation through an injected counter. An injected dependency is a function supplied by the caller; it lets tests substitute a controlled fixture without pretending to implement a real tokenizer.

type Evidence = { id: string; text: string; priority: number; readable: boolean; }; function assembleContext( instructions: string, question: string, evidence: readonly Evidence[], limits: { capacity: number; outputReserve: number }, measure: (serialized: string) => number, ) { if (!instructions.trim() || !question.trim()) throw new Error('Missing required input'); const { capacity, outputReserve } = limits; if (![capacity, outputReserve].every((value) => Number.isSafeInteger(value) && value >= 0)) { throw new Error('Invalid limits'); } const budget = capacity - outputReserve; const selected: Array<{ id: string; text: string }> = []; const omitted: string[] = []; const serialize = () => JSON.stringify({ instructions, question, evidence: selected }); const fits = () => { const size = measure(serialize()); if (!Number.isSafeInteger(size) || size < 0) throw new Error('Invalid measurement'); return size <= budget; }; if (!fits()) throw new Error('Required input exceeds budget'); const candidates = evidence.filter((item) => item.readable); if (candidates.some((item) => !Number.isFinite(item.priority))) throw new Error('Invalid priority'); for (const item of [...candidates].sort((left, right) => right.priority - left.priority)) { selected.push({ id: item.id, text: item.text }); if (!fits()) { selected.pop(); omitted.push(item.id); } } return { serialized: serialize(), selectedIds: selected.map((item) => item.id), omitted }; }

This is a greedy selector: it considers high-priority evidence first, without trying every possible combination. It preserves whole records, not arbitrary text prefixes. If an oversized record doesn't fit, a smaller later record can still be considered.

The priority values are application input, not a universal measure of truth. The function neither performs semantic search nor establishes that a selected policy is current. Those questions must be answered before or alongside assembly.

Test the choice with an honest measuring unit

This fixture measures UTF-8 bytes, not model tokens. The deliberately tiny byte budget makes admission behavior easy to verify offline:

const result = assembleContext( 'Use supplied evidence only.', 'Does production need approval?', [ { id: 'long', text: 'x'.repeat(1_000), priority: 10, readable: true }, { id: 'policy-v3', text: 'Human approval is required.', priority: 9, readable: true }, { id: 'private', text: 'Not authorized for this request.', priority: 100, readable: false }, ], { capacity: 400, outputReserve: 50 }, (serialized) => new TextEncoder().encode(serialized).byteLength, );

The long record is omitted, the small policy is selected and the private record never enters the serialized evidence. That is a selection-policy test, not a measurement of context-window usage for any real model.

A production adapter must count the actual provider payload, including roles, schemas, tool descriptions and any model-specific overhead. If the counting facility is asynchronous, the assembly path must support that rather than quietly substituting character counts. Recount the final request after any adapter transformation.

The output reserve here uses the same fictional unit as capacity. Real token budgets need one consistent model-specific accounting contract. A provider may accept a request that later exhausts its window; this application chooses to stop earlier rather than rely on that behavior.

Omission is an outcome worth keeping

The useful return value isn't just serialized text. Selected and omitted identifiers explain a decision without requiring a second copy of every document in logs.

If the necessary exception was omitted, I would want the application to know that before interpreting a confident answer as sufficient. It could retrieve a smaller section, make another bounded pass or ask for a narrower question. Quietly losing the exception is not an optimization.

Even whole-record selection needs care. Our records happen to be independently interpretable. A paragraph containing "this exception" may depend on its parent section. A tool result may depend on a preceding call. Those dependencies should be represented as units that enter or leave together.

I would evaluate assembly with deliberately awkward cases: the relevant record is large, an irrelevant record has a high rank, required instructions alone exceed the allowance, or a measurement is unavailable. Failing explicitly is often more useful than constructing an input whose omissions nobody can describe.

Passing the size check only establishes that selected content fits the declared budget. A separate fixture should name the evidence the question actually requires and check whether it reached the assembled request. Otherwise a selector can be perfectly compliant with its allowance while consistently choosing the wrong policy. Capacity and retrieval quality need different assertions.

The prompt is the result of a policy

The assembler is not a recipe for the best context in every system. It makes a few choices inspectable: preserve required inputs, exclude unauthorized evidence, select whole records and report budget omissions.

Those choices can be changed and compared against actual task outcomes. That is more useful than treating context quality as a feeling attached to a long prompt.

Eventually even useful history will outgrow the allowance. Then the question changes from choosing evidence for this call to preserving the right task state across a smaller next call. That is where trimming and compaction need a more careful contract.

What does your context assembler tell you when the most useful source does not fit? Silence there makes the eventual answer unnecessarily difficult to trust.

A note from the author

I’m Maksym Kuzmitskyi, a senior software developer working mainly with React and TypeScript. I build frontend applications and design workflows for working with AI in software delivery. If this article connects with something you’re working on, I’d love to hear from you.

Telegram

More than a blog post

I share frontend news and the reasoning behind it throughout the day. Pick the language that feels natural to you.

Need to discuss your project? Get in touch.