Skip to main content
Back to all articles
AI Engineering 10 min read

Context Engineering for AI Agents: What Actually Belongs in the Context Window?

How I decide what an AI agent should see on each step, what stays outside the prompt, and when to retrieve, compact, or split work.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#context-engineering#ai-agents#context-window#agent-memory#tool-calling#rag#mcp#prompt-caching#typescript#python
On this page

A few months ago I was debugging an agent that kept making worse decisions the longer it ran.

The model was not obviously the problem. The first few steps were good. It could inspect the repository, find the right files, run tests, and make sensible changes.

Then, after enough tool calls, it started missing things it already knew.

A constraint from the user was still technically in the conversation, but it was surrounded by old test output, file contents, tool schemas, previous plans, and decisions that had already changed.

The agent had more context than before, but less clarity.

That is the part of context engineering that matters to me.

It is not about filling the context window. It is about deciding what the model needs for the next decision.

I treat the context window as working memory

A context window is useful, but I do not treat it like a database.

If I am building a coding agent, the repository might contain thousands of files. The agent does not need all of them.

If it is fixing a checkout bug, I would rather give it the failing test, the relevant implementation, the current error, a few important project rules, and the tools it needs to keep investigating.

Everything else can stay outside until it becomes relevant.

That sounds obvious, but many agent systems do the opposite. They keep appending messages, tool results, retrieved documents, and instructions until the prompt becomes a history of everything that has happened.

The model then has to work out which parts still matter.

I would rather make that decision in the application.

What I usually keep around

For most agent steps, I want a small amount of stable information and a small amount of fresh information.

The stable part is usually the system-level behavior: what the agent is allowed to do, how it should behave, and any rules that really matter.

Then I keep the current goal explicit.

If the user originally said "fix the login bug", then later added "do not change the public API", I do not want those instructions living only as old chat messages. The active goal and important constraints should be easy to find every time the model runs.

After that, I add the recent history that explains what just happened.

If the agent edited a file and the compiler failed, that error probably belongs in the next call. The output of a successful package install from forty steps ago probably does not.

Finally, I add whatever evidence is needed for the current step: a source file, a retrieved document, a database record, a browser result, or a tool response.

That is the shape I keep coming back to: a small stable core, plus fresh task-specific evidence.

Do not preload information the agent can fetch later

This is where agents are different from one-shot prompts.

A one-shot request often needs all of its useful information up front.

An agent can go and get more information.

Suppose the task is to fix duplicate payment retries in a large codebase. I would not try to guess the twenty files that might matter and put all of them into the first prompt.

I would let the agent search for the retry path, open the relevant implementation, run the failing test, inspect the error, and then follow the next clue.

The context grows with the investigation.

This has two advantages.

First, the prompt stays smaller and more focused.

Second, the agent keeps reading from the current source of truth instead of carrying an old copy of the world around for the rest of the run.

This is also why I prefer just-in-time retrieval for RAG-heavy agents. Retrieve what the current question needs. Do not make every document compete for attention on every step.

Tool definitions are part of the context too

It is easy to focus on messages and forget that tools also consume context.

If an agent has access to eighty tools, the model has to reason about eighty names, descriptions, and schemas before it can decide what to do.

That may be acceptable for some models and tasks, but I do not think it is a good default.

I prefer to expose tools according to the current phase of work.

While exploring a repository, the agent may only need search and read access.

While implementing, it may need edit, test, and diff tools.

During release verification, it may need CI or deployment tools.

The product can support many capabilities without presenting every capability to the model on every turn.

I went deeper on this in MCP Does Not Mean Every Tool Belongs in Every Prompt.

A correct tool result can still be bad context

One of the easiest ways to damage an agent is to return too much data from a tool.

Imagine a log search that returns 30,000 lines.

The tool succeeded. The next model call is now worse.

I would rather return the useful part: how many matches were found, the main error groups, a small relevant sample, and a reference to the full result if the agent needs to inspect more.

The important distinction is that storage and context are not the same thing.

The complete log can still exist.

It just does not have to sit inside the model's working memory.

I use the same approach for large SQL results, long API payloads, repository files, browser pages, and test logs. I wrote about that pattern separately in Stop Putting Entire Tool Results Back Into the Prompt.

Keep important state outside the chat transcript

The more serious the agent becomes, the less I want the conversation history to be the only source of state.

For a long-running coding task, I may want to track the active goal, important constraints, decisions already made, files changed, test status, and unresolved issues as normal application state.

Then I build the next model input from that state.

A simplified version might look like this:

type AgentState = {  goal: string;  constraints: string[];  summary: string;  recentMessages: string[];};​function buildContext(state: AgentState, evidence: string[]) {  return {    goal: state.goal,    constraints: state.constraints,    summary: state.summary,    recentMessages: state.recentMessages,    evidence,  };}

The code is intentionally boring.

The useful part is that the application owns the important state instead of hoping the model reconstructs it from a long transcript.

This also makes debugging much easier. If the model violated a constraint, I can check whether the constraint was actually included in that step.

Memory is not the same as context

This distinction is easy to blur.

Memory is information that may be useful again later.

Context is the information the model needs right now.

A user might have hundreds of stored preferences and project facts. That does not mean all of them should appear in every prompt.

The application should retrieve the small subset that is relevant to the current task.

For example, if a project uses pnpm and PostgreSQL, those facts may matter while the agent is modifying the repository. A preference about how reports should be formatted probably does not.

I think of long-term memory as application data with normal lifecycle concerns: scope, provenance, updates, expiry, and deletion.

Then context engineering decides when some of that memory should be brought into the model.

I covered the storage side in Agent Memory Is a Database Problem Before It Is an LLM Problem.

Long-running agents still need compaction

Even with careful retrieval, a long task creates history.

At some point, the agent may have inspected dozens of files, run many commands, and changed direction several times.

I do not want to keep replaying all of that forever.

Instead, I create a handoff for the next part of the run.

A useful handoff says what the agent is trying to achieve now, what has already been done, which decisions still apply, what is failing, and where the important artifacts are.

Then I keep a short recent tail beside that handoff.

The raw history can remain in storage for debugging or replay. It simply stops being sent to the model every time.

That is different from deleting history.

It is just choosing not to make old history part of the current reasoning step.

This is the problem I explored in more detail in Long-Running Agents Need Context Budgets, Not Just Bigger Windows.

Sub-agents can help by keeping investigations separate

I used to think about sub-agents mainly as a way to do work in parallel.

Now I also think about them as context boundaries.

If one agent is investigating a flaky test, an API compatibility problem, and a database migration at the same time, its context gets messy quickly.

Three focused workers can investigate those questions separately and return short conclusions to the lead agent.

The lead agent does not need every command each worker ran. It needs the result, the evidence, and anything that affects the final decision.

That separation is useful even when the workers are not running at the same time.

The main benefit is that unrelated intermediate work does not accumulate in one giant context.

More context is not always better

Large context windows are useful. I use them.

But I still try not to spend them carelessly.

A large window gives the model more capacity. It does not guarantee that the model will use every part of that capacity equally well.

It also affects latency and cost.

So I do not ask, "How much context can this model accept?"

I ask, "What information would I be unhappy to remove from this step?"

That question usually produces a much smaller working set.

For a coding task, I would almost always keep the current goal, hard constraints, the code being changed, the latest test result, and the tools needed for the next action.

Older investigation details can often be summarized or fetched again.

The exact context should be debuggable

When an agent makes a bad decision, I want to know what it actually saw.

Not what was somewhere in the database.

Not what was present twenty turns earlier.

What was in the model input for that exact step?

I usually want enough observability to answer things like: Was the current goal present? Did an old instruction conflict with a new one? Which documents were retrieved? Which tools were available? Was the test output truncated? Was the state stale?

For production systems, I also like recording token usage by major context section, along with the model, retrieved evidence IDs, tool set, and state version.

You do not need to log sensitive raw content to get useful visibility.

But if the context builder is a black box, agent failures become much harder to explain.

I would start simple

For a new agent, I would not begin with a complicated memory system, several summarizers, a vector database, tool routing, and a hierarchy of sub-agents.

I would start with a clear goal, a few hard constraints, a short recent history, task-specific evidence, and only the tools needed for the current job.

Then I would add things when I can point to a real failure.

If the history becomes too long, add compaction.

If durable facts are needed across sessions, add memory.

If tool results are huge, move the full payload outside the prompt.

If retrieval is noisy, fix retrieval.

If unrelated investigations are colliding, split them.

If the stable prefix is expensive, look at prompt caching.

The architecture should get more complicated because the product needs it, not because every agent diagram on the internet contains the same boxes.

Final thought

I do not see context engineering as a replacement for prompt engineering.

Good instructions still matter.

The difference is that an agent does not work from one carefully written prompt. It keeps receiving a new working set as the task changes.

That working set is something we have to design.

The question I keep coming back to is simple:

What does the model need to make the next good decision?

Not everything it has ever seen.

Not everything the application knows.

Just what matters now.

That is context engineering.

Further reading

KEEP READING

Related engineering notes