Availit World How AI really works, in your language

Lesson 34 of 4634 minFacts checked October 21, 2026

Context engineering: choosing what the model sees

At every step, an agent’s model reads its whole context again: the rules, the tools, the task and everything that has happened since. It knows nothing else. What goes into that window, and what comes out, decides whether a long task succeeds, how fast it runs and what it costs.

In this lesson you will

  • List what fills an agent’s context, and explain why every request reads all of it again
  • Explain context rot with the evidence, and why a bigger window is not a better memory
  • Keep the prompt cache working in a loop, and see how fast the tokens add up
  • Choose between clearing, summarising and restarting when the window fills
  • Decide what to load up front and what to fetch just in time
  • Use notes, memory files and subagents on long tasks, and know their risks
On this page
  1. From prompt to context
  2. More context is not better context
  3. The cache, inside a loop
  4. When the window fills up
  5. Load it now, or fetch it later
  6. Notes and memory
  7. Subagents and other lessons from real agents
  8. Remember
  9. Check yourself

From prompt to context

In the APIs lesson you sent one request and got one reply. An agent sends many requests, and each carries far more than your words. Anthropic’s engineers call the work of choosing all of it context engineering, the natural next step after prompt engineering: not only how to word an instruction, but which tokens the model should see at each step, out of everything that could be put in front of it.

What one request of an agent contains
  1. System promptrules and role
  2. Tool definitionsnames, descriptions, parameters
  3. Taskwhat the user asked
  4. Historyevery earlier call, result and thought
  5. Newest resultwhat the last tool returned

The model keeps nothing between requests (the APIs lesson). At every step the harness sends the whole context again, and the model reads it from the first token. An agent that takes 50 steps reads its system prompt 50 times. That is why agents read far more than they write: the team behind the Manus agent reported about 100 input tokens for every output token, with around 50 tool calls in a typical task.

Who writes each part, and how often it changes
Written byChanges
System promptYou, or the harnessAlmost never during a task
Tool definitionsThe harness and any connected tool serversRarely
Instruction files such as AGENTS.mdYouBetween sessions
TaskThe userOnce, at the start
Tool calls and resultsThe model and the toolsEvery step
Notes and memoryThe model, through toolsNow and then

The top of this table changes least. Keep it that way: it is the part the prompt cache can reuse.

Quick check

An agent takes 40 steps to finish a task. How many times does its model read the system prompt?

Show the answer

Answer: 40 times, once per request Each request carries the whole context, system prompt included. Caching makes the repeats cheaper, but the model still reads them every time.

More context is not better context

Context windows keep growing; DeepSeek’s current models accept a million tokens. But the long-context lesson showed that a window that fits is not a window that is used well. Facts in the middle are found less often than facts at the start or end, and RULER found that of 17 models that all claimed at least 32,000 tokens, only half still did well at that length.

In July 2025 Chroma, the company behind an open-source vector database, looked closer. It tested 18 models, including GPT, Claude, Gemini and Qwen models, on deliberately simple tasks, and changed mainly the amount of text around the answer. What it found:

  • Longer input, worse answers. Results fell as the input grew, even on simple tasks, and not evenly: models do not use every part of their context equally well.
  • Look-alikes hurt. One passage that resembled the answer but was wrong, a distractor, lowered accuracy; four lowered it further.
  • Indirect questions suffer first. When the question and the answer shared few words, accuracy dropped sooner and faster as the input grew.
  • Focused beats full. On LongMemEval, a test of memory in long chats, models did clearly better when given only the relevant part, about 300 tokens, than when given the whole history of about 113,000 tokens that contained it.
  • Even copying fails. Asked to repeat a long run of one word with a single different word inside it, models made more mistakes as the run grew, and some refused or produced random text.

Quick check

In Chroma’s LongMemEval test, models got either the 300 tokens that mattered or a 113,000-token chat history that contained them. What happened?

Show the answer

Answer: The focused version did clearly better The answer was in both, but the text around it made it harder to use. Choosing the context carefully is not only cheaper; it gives better answers.

The cache, inside a loop

The APIs lesson gave the rules for prompt caching: the same start, token for token, earns a cache hit at a fraction of the price, and anything that changes near the top spoils it. At DeepSeek in October 2026 a cached input token costs 2 % of a fresh one. In an agent those rules matter far more than in a chat, because of the way the bill grows.

Why agents read so much
tokens read at step k = S + k × t

S tokens of rules, tools and task, plus k tool results of about t tokens each.

whole run = n × S + t × n(n + 1) ÷ 2

Add up all n steps. The history part grows with the square of the number of steps.

S = 10,000, t = 2,000, n = 50 → 3,050,000 tokens

The window never holds more than 110,000 tokens, yet the run reads over 3 million.

all fresh ≈ $0.46; with the cache ≈ $0.025

At DeepSeek’s off-peak Flash prices, if only each step’s new tokens are fresh: about 18 times cheaper, and each step starts sooner.

The Manus team called the cache hit rate the single most important number for an agent in production. Besides the rules you already know, three habits matter in a loop:

  • Write the same data the same way. Many languages and libraries do not promise a fixed order of keys when they turn an object into JSON. The same tool result can then come out as different text, and the cache misses from there on.
  • Keep the tool list fixed. Tool definitions sit near the start, so adding or removing one mid-task makes everything after it fresh. It also confuses the model when earlier steps mention a tool that has gone. Manus keeps every tool defined and instead blocks the ones not allowed at that moment while the next token is chosen, a kind of constrained decoding. Tool names with shared prefixes, such as browser_ and shell_, let it block a whole group at once.
  • Clean up rarely, and late. Every change to the history, even a helpful one, makes everything after it fresh again. So harnesses leave the context alone until it is nearly full, then make room in one go.
A history the cache can followpython
import json

RULES = "You are a careful research assistant. Give a source for every fact."
task = "Find this week's rainfall in Lahore and compare it with the same week last year."

messages = [
    {"role": "system", "content": RULES},  # the same for the whole run
    {"role": "user", "content": task},     # the same once the task has started
]

def as_text(result):
    # The same result must always become exactly the same text
    return json.dumps(result, sort_keys=True, ensure_ascii=False)

def add_result(call_id, result):
    # Only add to the end: never edit, reorder or delete earlier messages
    messages.append({"role": "tool", "tool_call_id": call_id, "content": as_text(result)})
  • Everything before the newest message is exactly what the last request sent, so all of it can be a cache hit.
  • sort_keys=True fixes the order of keys. ensure_ascii=False keeps Urdu or Chinese text as itself instead of escape codes such as \u0644, which also saves tokens.
  • In the full loop from the agent-loop lesson, the model’s reply with its tool calls is appended first, then one result for each call, in order.

Quick check

Halfway through a task, your harness removes three tools the agent no longer seems to need. What does that cost?

Show the answer

Answer: The cache misses from the tool list onwards, and earlier steps now mention tools that no longer exist Tool definitions sit near the start, so everything after them must be read fresh. Keeping the tools and blocking them when the next token is chosen avoids both problems.

When the window fills up

Even with care, a long task fills the window. The harness must make room, and every way of doing it gives something up. From the lightest to the heaviest:

Four ways to make room
What it doesWhat you lose
Clear old tool resultsReplaces old outputs with a short note but keeps the calls, so the model knows what it didThe details, unless it runs the tool again. Anthropic calls this one of the safest and lightest kinds of compaction.
Keep the address, drop the contentRemoves a long page or file from the context but keeps its URL or pathNothing, as long as the agent can open it again. Manus calls this restorable compression.
SummariseThe model summarises the history; the run continues from the summary and the latest turnsWhatever the summary leaves out. Claude Code keeps decisions, unsolved bugs and implementation details, plus the five files it used most recently.
Discard and restartThrows away the tool history, keeps the task and starts againAll progress held in the context. It works like a fresh attempt at the task.
Try itMaking room

Press “Next turn” until the window is about two-thirds full and read the bottom lines: almost every token of each request comes from the cache, because the context only grows at the end. Now press “Elide old tool outputs”. The window shrinks, but the striped cache bar under it shrinks too, back to the first output that changed: the next request must read everything after that point fresh. “Summarise oldest turns” frees even more room and loses even more of the cache, and of the details. Keep going and watch the share of cached tokens for the whole run. This is why harnesses wait until the window is nearly full before they clean up.

This interactive part needs JavaScript.

DeepSeek tested these choices with DeepSeek-V3.2 as a search agent on BrowseComp, a hard test of finding facts on the web (December 2025). Its runs often grew past the 128,000-token window, partly because the model kept re-checking its own findings. When the context passed 80 % of the window, the harness stepped in:

DeepSeek-V3.2 on BrowseComp, by how the harness made room
  • No context management 51.4 % correct
  • Summarise the history 60.2 % correct
  • Discard the tool history and restart 67.6 % correct

From the DeepSeek-V3.2 report, section 4.4. BrowseComp questions need many searches before the answer can be found.

Quick check

Your coding agent’s window is nearly full. Which part of the context is safest to clear first?

Show the answer

Answer: Long tool outputs from many steps ago Old tool outputs are most of the context and can usually be fetched again. The rules and the task are small, and losing them changes what the agent is trying to do.

Load it now, or fetch it later

Some knowledge must be in the context before the model starts; the rest can wait until it is needed. There are two ways to bring it in:

Load it up front

  • Search a prepared index for the passages closest in meaning to the question, and paste the best few into the prompt
  • Fast: one search, one request
  • Suits large collections that rarely change, such as manuals or a help centre
  • Can miss, or paste a passage that looks right but is not; the index goes out of date

Fetch it just in time

  • Give the agent tools to list, search and open things, and keep only addresses and paths in the context
  • Slower: every lookup is a step
  • Suits code, files and the web, which change all the time
  • The agent sees what is there now and can follow one clue to the next

The first is retrieval-augmented generation, RAG, from the embeddings lesson. The second, just-in-time retrieval, is how coding agents work: Claude Code loads its instruction files at the start, then uses search tools such as grep to find and open only the files a step needs. Many systems mix the two.

Tools that fetch must not flood the context in turn. A tool that returns a whole 5,000-line file in one go undoes all the care above. Return a page at a time, and say how to get more:

A file reader that returns one page at a timepython
def read_file(path, start=1, count=200):
    """Return up to `count` lines of a text file, starting at line `start`."""
    with open(path, encoding="utf-8") as f:
        lines = f.read().splitlines()
    if start > len(lines):
        return f"[The file has only {len(lines)} lines.]"
    end = min(start - 1 + count, len(lines))
    page = [f"{n}: {lines[n - 1]}" for n in range(start, end + 1)]
    if end < len(lines):
        page.append(f"[Lines {start} to {end} of {len(lines)}. "
                    f"Call read_file again with start={end + 1} for more.]")
    return "\n".join(page)
  • Line numbers let the model point to an exact place when it edits or quotes.
  • The last line tells the model that the file goes on, and exactly how to read more, so a cut-off page is never mistaken for the whole file.
  • Search tools should do the same: return the first matches and say how many there are in total.

Quick check

An agent must answer questions about a codebase that changes every day. Which approach fits best?

Show the answer

Answer: Give the agent search and read tools, and let it open files as it needs them Fetching just in time always sees the current files and opens only what a step needs. A prepared index goes stale, and pasting everything wastes the window.

Notes and memory

Information that must outlive the window has to be written somewhere else. Agents do this through tools:

  • Notes for this task. The agent keeps a file such as NOTES.md or a to-do list, and reads it back after the context has been summarised. Anthropic describes Claude playing a Pokémon game over thousands of steps: it kept tallies of its progress, maps of where it had been and notes on which attacks worked, and carried on from its notes after each reset of the context.
  • Instruction files. AGENTS.md and similar files (the harnesses lesson) carry your rules into every session.
  • Memory across sessions. Anthropic’s memory tool (September 2025) lets a model create, read, change and delete files in a memory folder that you host. In Anthropic’s own test of a search agent, memory together with clearing old tool results did 39 % better than the agent without them; clearing alone, 29 %. In a 100-turn web search test, clearing alone cut token use by 84 %.
  • Memory as a system. MemGPT (2023, University of California, Berkeley) treated the context like a computer’s working memory and outside storage like its disk, with the model moving information between them. MemOS (2025), from MemTensor in Shanghai with several Chinese universities, goes further and manages three kinds of memory together: plain text, saved KV caches and changes to the model’s weights.
Where an agent can keep what it knows
LastsCostsMain risk
In the contextUntil it is cleared or the session endsPaid again on every requestCrowded out by everything else
In files it reads and writesAs long as the files existOnly when openedOld or wrong notes that keep misleading it
In a searchable storeAs long as the store existsOne search per lookupFinding something similar but wrong
In the model’s weightsUntil the model is trained againTraining, onceHard to check, correct or remove (the fine-tuning lesson)

Quick check

An agent works for hours, and its context is summarised several times. Where should it keep the list of steps still to do?

Show the answer

Answer: In a notes file it rewrites as it works and reads back after each summary A file survives every summary, and rewriting it puts the plan back at the end of the context, where the model attends well.

Subagents and other lessons from real agents

A subagent (the harnesses lesson) is the strongest way to keep a context clean. The main agent hands one job, such as finding the cause of a crash in the logs, to a second agent that starts with a fresh context. The subagent may read tens of thousands of tokens and returns a summary, often of 1,000 to 2,000 tokens, Anthropic writes. The main agent sees the result, not the search. The price is more tokens in total, and a summary can drop the one detail that turns out to matter; the multi-agent lesson looks at both.

Three more lessons from the Manus team:

  • Keep the mistakes in. When a step fails, leave the failed action and its error message in the context. Seeing what went wrong makes the model less likely to try the same thing again. Hiding errors hides the evidence.
  • Avoid ruts. Models copy the patterns in their context. Reviewing 20 CVs in a row, an agent fell into a rhythm and repeated similar actions because that is what its context showed, even where they no longer fitted. Small, deliberate variations in wording and order break the pattern.
  • Use the file system as memory. Files are unlimited, they last, and the agent can use them directly. Write big things to files and keep only their paths in the context.

A July 2025 survey of more than 1,400 papers maps the whole field: getting context (retrieval and generation), processing it, and managing it, then building on those with RAG, memory, tools and multi-agent systems. Its authors note a gap that remains: models have become good at understanding long, complex context, but much weaker at writing equally long and complex output.

In practice, context engineering comes down to four questions at every step: what does the model need now, what can it fetch later, what can go, and what must be written down so that it is never lost?

Does each one help an agent’s context, or hurt it?

0 of 8 sorted
  • Returning a file’s path and first 200 lines instead of the whole 5,000-line file

    Answer: Helps

  • Putting the current time, to the second, at the top of the system prompt

    Answer: Hurts

  • Deleting a failed command and its error from the history

    Answer: Hurts

  • A to-do list the agent rewrites as it works

    Answer: Helps

  • Loading 80 tools from every connected server, just in case

    Answer: Hurts

  • Asking a subagent to search the logs and report back in a few lines

    Answer: Helps

  • Writing JSON keys in the same order every time

    Answer: Helps

  • Twenty nearly identical examples in a row

    Answer: Hurts

Remember

  • An agent’s context is everything the model reads at each step, and all of it is sent again with every request.
  • More context is not better: answers get worse as the window fills, and look-alike distractors hurt most. This is context rot.
  • In a loop the tokens read grow with the square of the steps, so keep the start fixed and only add to the end; cached tokens cost a small fraction of fresh ones.
  • When the window fills, clear old tool results first, then summarise or restart. Each frees room and loses something.
  • Load knowledge that rarely changes up front with retrieval; fetch changing things just in time, with tools that return a page at a time.
  • Notes, memory files and subagents keep knowledge outside the window. Review what they store, because their mistakes last.
  • Keep errors in the history and vary repeated patterns, so the model learns from mistakes and does not fall into ruts.

Words to know

Context engineering
Choosing which tokens a model sees at each step: rules, tools, history, retrieved text and notes.
Context rot
Answers getting worse as the context grows, even when the information needed is in it.
Attention budget
The idea that every token in the context competes for the model’s limited attention, so each extra token has a cost.
Distractor
Text that looks like the answer but is not, and draws the model away from the right one.
Cache hit rate
The share of input tokens that were read from the prompt cache instead of computed again.
Append-only history
A history that only grows at the end, so each request starts with exactly what the last one sent.
Tool result clearing
Replacing old tool outputs with a short note to free room in the context. Anthropic calls it context editing.
Restorable compression
Dropping content from the context but keeping its path or address, so it can be fetched again.
Discard-all
Throwing away the whole tool history when the context gets too long, and starting the task again.
Just-in-time retrieval
Letting an agent fetch information with tools when it needs it, instead of loading it in advance.
Recitation
Rewriting the plan or to-do list near the end of the context, so the goal stays in the model’s recent attention.
Memory tool
A tool that lets a model save and read files that last beyond one context or one session.
Optical compression
Storing text as an image so it takes fewer tokens, as studied in DeepSeek-OCR.

Go to the source

This lesson is built on these papers and documents. Paper links open arxiv.org, a separate site.

Check yourself

5 questions. Tap the answer you think is right.

0 of 5 answered

Why do agents read far more tokens than they write?

Show the answer

Answer: Every request sends the whole context again, and it grows with each step Manus reports about 100 input tokens for every output token: the history is read again at every step.

What is context rot?

Show the answer

Answer: Answers getting worse as the context grows, even when the information needed is in it Chroma found it in 18 models: more text around the answer, especially look-alike distractors, makes the answer harder to use.

Halfway through a run, the harness clears old tool results. What happens to the prompt cache?

Show the answer

Answer: Everything from the first changed token onwards must be read fresh on the next request The cache matches an identical start. Everything before the first change still hits; everything after it is computed again once, then cached.

On BrowseComp, which way of making room gave DeepSeek-V3.2 its best score?

Show the answer

Answer: Discarding the tool history and starting again 67.6 % against 60.2 % for summarising and 51.4 % without management. On search, a fresh start works like another attempt.

Your agent’s memory file holds a wrong note that keeps causing mistakes. What should you do?

Show the answer

Answer: Correct or delete the note: memory lasts, and so do its mistakes The agent reads its memory as true at the start of every session. Fix the source.

Lesson complete

Answer every question above to complete this lesson.

Your progress is saved on this device only.

Next lessonMCP: one plug for every tool
Previous lesson All lessons

Choose your language