Context Engineering for AI Agents: Six Hard-Won Lessons from Building Manus
Context Engineering for AI Agents: Six Lessons from Building Manus
Author: oil欧哟
Original author: Yichao 'Peak' Ji (Manus team) (English original: https://manus.im/zh-cn/blog/Context-Engineering-for-AI-Agents-Lessons-from-Building-Manus), Chinese translation and engineering concept supplements: Oil Ouyou.
At the start of the Manus project, my team and I faced a critical road choice: Should we train a full end-to-end agent model on top of an open-source foundation model, or should we build directly on the in-context learning capabilities of frontier large models?
Looking back at my first decade in NLP, we did not have such a choice. In the distant BERT era (yes, seven years ago), models had to be fine-tuned (and pre-trained before that) before transferring to new tasks. Even though the models were tiny compared to today's LLMs, each iteration could easily take weeks.
For applications that require rapid iteration, especially before product-market fit (PMF), waiting weeks per iteration is fatal. That is a painful lesson I learned in my previous startup: I trained an internal model from scratch for open information extraction and semantic search. Soon after, GPT-3 and Flan-T5 appeared, and my hard-trained model became scrap metal overnight. Ironically, it was these models that displaced the old approach and also pointed us to a new path.
This hard-earned lesson made us choose decisively: Manus would bet entirely on context engineering. This allows us to ship improvements on the scale of hours rather than weeks, and keeps our product architecture orthogonally decoupled from the underlying model: If model capability evolution is a rising tide, we want Manus to be a boat floating on the surface, not a pillar nailed to the seabed.
Oil's perspective supplement: What's the difference between "fine-tuning" and "in-context learning"? In the past, to make a model handle a new task, you had to collect thousands of labeled examples, retrain, and modify the model's internal weights (that's fine-tuning), often taking weeks per run. Now frontier large models have crossed a threshold: you don't need to change internal parameters; just organize rules, environment info, and reference examples in the context you send, and the model can follow them on the spot. That's in-context learning.
Once you actually start building, you realize context engineering is far from simple. It is an experimental science. While building Manus, we have rewritten the agent framework four times, each time because we discovered a better way to shape context.
In machine learning, the process by which algorithms automatically find optimal parameters is called stochastic gradient descent (SGD). We jokingly call our manual process of fiddling with architecture, tweaking prompts, and iterating by trial and error "stochastic graduate descent" (also SGD). It is not elegant, but it works.
Oil's perspective supplement: What is "stochastic gradient descent (SGD)"? Why is this a pun? When training an AI model, the algorithm doesn't know which parameters are best at first, so it acts like a person walking down a hill blindfolded: it randomly picks a small batch of data, tests a step, checks how far the result is from the correct answer, and follows the slope of decreasing error (mathematically the gradient). It keeps stepping until it reaches the bottom, the optimal parameters. The author's "stochastic graduate descent" puns on the word "gradient" (changed to "graduate"). It means that when adjusting agent context, no mathematical formula automatically finds the best solution. Engineers must manually edit prompts, run tests, and iterate by trial and error, like hard-working graduate students in a lab.
This article shares the six local optima we found through our own "human SGD." If you are building your own AI agent, hopefully these principles will help you avoid detours.
1. Design around KV cache
If I had to pick only one core metric for a production-grade AI agent, I would unhesitatingly choose KV-cache hit rate. It directly impacts latency and cost. To understand why, let's look at how a typical agent operates:
After receiving user input, an agent works through a series of tool calls: Action -> Observation -> Action -> Observation... In each loop:
- The model selects an action from its action space (all available tools) based on the current context.
- That action executes in the environment (e.g., Manus's VM sandbox), producing an observation.
- The system appends the action and observation to the end of the existing context, which becomes the input for the next loop.
As steps advance, the context grows like a snowball, but the model's output each step (usually a short structured tool call) stays tiny. Compared to a normal chatbot, an agent's input-to-output token ratio is extreme. In Manus, the average input-to-output ratio is around 100:1.
The good news: as long as the context has an identical prefix, you can use KV cache, whether self-hosting or calling a commercial API. It drastically lowers time-to-first-token (TTFT) and inference cost. The savings are substantial: for Claude Sonnet, cached input tokens cost $0.30 / million tokens, while uncached ones cost $3 / million tokens, a 10x difference!
Oil's perspective supplement: What are KV cache and TTFT? Why does changing one character invalidate the whole cache? Large models generate responses in two steps. First they read and compute over the entire input context (the wait from request until the first output token is the TTFT). Then they generate token by token. In agent tasks, the context sent at round 30 has the same first 29 rounds as before. KV cache is like the model's "calculation notes": if the prefix is unchanged, the service reuses the previous computation from GPU memory, only computing the newly appended parts. That makes it fast and cheap (10x cheaper). But LLMs are autoregressive: each token's computation depends strictly on all preceding tokens, like a chain of dominoes. If any character earlier in the context changes (even a punctuation mark or a second-level timestamp), all cache after that point collapses and the entire following tens of thousands of tokens must be recomputed at full cost.
From a context engineering perspective, here are key practices to raise KV-cache hit rate:
Keep the prompt prefix stable. Due to autoregression, even a single token difference invalidates all cache from that point onward. A common mistake is putting a precise-to-the-second timestamp at the start of the system prompt. That lets the model know the current time but destroys your cache hit rate.
Make the context strictly append-only. Avoid modifying earlier actions or observations. Also ensure serialization is deterministic. Many programming languages and libraries do not guarantee stable key order when serializing JSON objects, which can silently break cache.
Oil's perspective supplement: Why does changing JSON serialization order break cache? Before sending data to the model, you convert it to a string (serialization). For example, the same history entry might serialize as
{"url": "...", "status": 200}one round, but if the fields swap order to{"status": 200, "url": "..."}, even though it's identical to a human, the KV cache matches characters strictly in order and declares a miss.Explicitly mark cache breakpoints when needed. Some providers or frameworks don't support automatic incremental prefix caching; you must insert manual cache breakpoints. When setting breakpoints, you need to estimate cache expiration and at least ensure the breakpoint covers the end of the system prompt.
Additionally, if you self-deploy with vLLM or similar, make sure prefix caching (aka KV cache) is enabled, and route requests for the same task to the same worker node via session ID to ensure it works.
2. Mask, don't remove
As your agent's features grow, its action space gets more complex, meaning tool count explodes. The recent MCP (Model Context Protocol) worsens things. If you let users bring their own tools, trust me, some users will shove hundreds of ambiguous tools into your carefully tuned action space. The result: the model is more likely to pick wrong actions or take inefficient routes. In short, an agent with too many tools gets dumber.
Naturally, you'd think of designing a dynamic action space, e.g., loading tools on demand with something like RAG. We tried that in Manus. But experiments led to a clear principle: unless absolutely necessary, do not add or remove tools in the middle of a loop. Two main reasons:
- In most LLMs, tool definitions serialize to the very front of the context (before or right after the system prompt). Any addition or removal invalidates the KV cache for all subsequent actions and observations.
- When earlier actions or observations reference tools no longer defined in the current context, the model gets confused. Without constrained decoding, this often causes schema violations or even hallucinated actions.
To solve this, Manus uses a context-aware state machine to manage tool availability. It doesn't delete or edit tool definitions; instead, it masks token logits during decoding, forbidding or forcing specific actions based on the current context state.
In practice, most model platforms and inference frameworks support some form of response prefill, letting you constrain the action space without touching the tool definitions at the top. Using NousResearch's Hermes format as an example, there are typically three function-calling modes:
- Auto mode: The model may call a tool or not. Implementation: prefill the reply with
<|im_start|>assistant. - Required mode: The model must call a tool, but which one is unrestricted. Implementation: prefill to the tool_call tag:
<|im_start|>assistant<tool_call>. - Specified mode: The model must choose from a specified subset. Implementation: prefill to the opening of a tool name:
<|im_start|>assistant<tool_call>{"name": "browser_.
In this way, we constrain action choices by directly masking token logits. For example, when a user sends a new message, Manus must immediately reply rather than call an action. We also intentionally gave tool names consistent prefixes, e.g., all browser tools start with browser_, all shell tools with shell_. This makes it easy to force the agent to choose from a specific set without a stateful tokenizer.
These designs keep Manus's agent loop stable even under a model-driven architecture.
Oil's perspective supplement: What are masking token logits, response prefill, and do they conflict with on-demand Skill loading?
- Masking token logits: When an LLM generates a token, it first computes scores (logits) for tens of thousands of candidate tokens in its vocabulary, then samples from them. Masking means suppressing the scores of disallowed tool tokens at decoding time, preventing the model from selecting them.
- Response prefill: The model generates by continuing from the preceding context. As the three modes show, if you prefill the reply with
<|im_start|>assistant<tool_call>{"name": "browser_, the model can only continue by completing a browser-tool name, without modifying the tool list at the top.- Conflict with on-demand Skill loading? Not at all; the underlying principle is identical. On-demand loading doesn't add or remove tool definitions at the top. It keeps a fixed
Readtool and a short list of Skill names at the top (prefix stable, so KV cache hits). When a Skill is triggered, it callsReadto append the correspondingSKILL.mdas a new observation at the end of the context, following the same "head stable, tail append" rule.
3. Treat the file system as context
Modern frontier models offer 128K or even longer context windows. But in real agent scenarios, that often isn't enough, and sometimes it's a burden. Three pain points:
- Observations can be enormous, especially when dealing with unstructured data like web pages or PDFs; a few steps can easily blow through the context limit.
- Model performance degrades significantly beyond a certain context length, even if technically within the window.
- Long inputs are expensive; even with prefix caching, you still pay for every token of transfer and prefill each round.
To address this, many agent systems implement truncation or compression strategies. However, overly aggressive compression inevitably loses information. This is fundamental: an agent needs all previous state to predict the next action, and you can't reliably know which seemingly irrelevant observation will become critical ten steps later. Logically, any irreversible compression carries risk.
That's why in Manus we treat the file system as the ultimate context: unlimited capacity, inherently persistent, and directly operable by the agent. The model learns to read and write files on demand, using the file system not just as storage but as structured externalized memory.
Our compression strategy is always designed to be restorable. For example, if we keep the URL of a web page, we can remove the page's content from context; if we keep the path of a document in the sandbox, we can omit the document's content. This lets Manus shorten contexts without permanently losing information.
While developing this, I often wondered: what would it take for state space models (SSMs) to work effectively in agent settings? Unlike Transformers, SSMs lack full attention, so they struggle with long-range backward dependencies. But if they could master file-based external memory, offloading long-term state to files instead of keeping it in the model's internal state, then the speed and efficiency advantages of SSMs could enable a whole new class of agents. In that sense, an agent-capable SSM might be the true modern successor to the Neural Turing Machine.
Oil's perspective supplement: What are state space models (SSM) and Neural Turing Machines?
- State space models (e.g., Mamba): Current GPT and Claude models are Transformers. They remember every detail of prior context by re-reading all previous tokens each step, which gets slower and more memory-intensive as context grows. SSMs, by contrast, compress what they've read into a fixed-size "summary state" and discards the original text. They run fast and use little memory, but can't look back into the original text for fine details. The author suggests that if SSMs could read and write files for fine-grained details, they could combine extreme speed with infinite memory.
- Neural Turing Machines: DeepMind proposed this in 2014. Instead of relying solely on the neural network's internal memory, they attach an external memory tape (like RAM or disk) that the model can read and write. Manus having the LLM read and write a sandbox file system is essentially bringing that decade-old idea into practice.
4. Manipulate attention through recitation
If you've used Manus, you've probably noticed something interesting: when handling complex tasks, it often creates a todo.md file and updates it step by step, checking off completed items.
This is not just a user-pleasing interaction detail. It's a deliberate mechanism to manipulate attention.
In Manus, a typical task averages about 50 tool calls. That's a long loop. Since Manus relies on LLMs for decisions, it can easily drift off course or forget early goals, especially with longer contexts or complex tasks.
By continuously rewriting todo.md, Manus is reciting its goal at the very end of the context. This pushes the overall plan into the model's recent attention window, avoiding "lost in the middle" problems and greatly reducing goal misalignment. It's essentially using natural language to steer attention toward the task goal, without any special architectural changes.
5. Keep the wrong stuff in
Agents make mistakes. This is not a rare bug; it's a fact of life. Language models hallucinate, environments return errors, external tools fail, and unexpected edge cases happen. In multi-step tasks, failure is not an exception; it's part of the loop.
Yet a common impulse is to hide errors: clean up traces, retry the action, reset the model state, and rely on mystical temperature parameters. That might seem safer and more controllable, but it has a cost: erasing failure removes evidence; without evidence, the model can't correct itself.
Based on our experience, one of the most effective ways to improve agent behavior is surprisingly simple: leave failed attempts in the context. When the model sees a failed action and its observation or stack trace, it implicitly updates its internal beliefs, lowering the prior probability of repeating similar mistakes.
In fact, we believe error recovery is one of the clearest indicators of an agent's intelligence. Yet it's sorely neglected in most academic benchmarks and research, which focus only on success rates in ideal, single-pass conditions.
6. Don't fall into the few-shot trap
Few-shot prompting is a common technique for improving LLM output. But in agent systems, it can backfire in unexpected ways.
Oil's perspective supplement: What is few-shot prompting? When you want a model to produce output in a specific format or style, writing abstract requirements isn't always enough. The common approach is to include 2-3 example pairs of input -> expected output in the prompt, letting the model mimic the pattern. That's few-shot prompting.
LLMs are strong imitators; they mimic patterns in the context. If your context is full of similar historical action-observation pairs, the model tends to follow that pattern even when it's no longer optimal.
This is dangerous in tasks involving repetitive decisions or actions. For example, when using Manus to review 20 resumes, the agent often falls into a mechanical rhythm, repeating similar actions just because it saw a chain of similar operations earlier. That causes deviation, overgeneralization, and sometimes hallucinations.
The solution is to increase diversity. Manus introduces small structured variations in actions and observations, such as different serialization templates, synonym substitutions, or tiny noise in ordering or formatting. This controlled randomness breaks fixed patterns and re-engages the model's attention.
In other words, don't few-shot yourself into a rut. The more monotonous your context, the more fragile your agent.
Conclusion
Context engineering is still an emerging science, but for agent systems it's already an essential foundational skill. Models may get stronger, faster, cheaper, but no amount of raw model power can replace the need for memory, environment, and feedback. How you shape context ultimately defines how your agent behaves: how fast it runs, how well it recovers, and how far it can go.
At Manus, we learned these lessons through repeated rewrites, dead ends, and real production testing with millions of users. What we share is not universal truths, but they are the patterns that work best for Manus. If they help you avoid even one painful iteration, this article has served its purpose.
The future of agents will be built on every context. Engineer them well.
This article is compiled from Oil Ouyou's "Oil Book" AI practical notes series.