Agent Context Engineering
Agent Context Engineering
Agent 上下文工程(Agent Context Engineering) is a set of technical practices for systematically designing and optimizing the context information passed to an AI Agent. Its goal is to enable the Agent to obtain the most effective information within a limited context window, thereby improving the accuracy, efficiency, and reliability of task execution.
Unlike traditional programs with fixed execution logic, the behavior of an AI Agent is entirely dependent on the received context—including system prompts, tool descriptions, conversation history, and externally retrieved information.
The core of context engineering lies in answering one question:What does the Agent need to know most in this call?

Context engineering is not a one-time prompt writing task, but a continuous optimization process throughout the entire lifecycle of Agent system development, testing, and operation.
Core elements
Agent context is composed of the following layers:
| Layer | Content | Characteristics |
|---|---|---|
| System Prompt | Role definition, behavioral rules, output format requirements | Carried with every call, relatively stable |
| Tool Definitions | Name, parameters, and functional description of available tools | Consumes a large number of tokens, needs to be condensed |
| History | Conversation and tool call history of the current session | Continuously growing, requires truncation or summarization strategy |
| Retrieved Context | Content retrieved from external knowledge bases or code repositories | Injected on demand, requires relevance sorting |
| User Input | The user's current instruction or question | Uncontrollable, but can be optimized through clarification |
Core practice
Context budget management
Treat the context window as a finite "budget" and allocate it reasonably to different types of context.
Not all information is worth occupying context space; every piece of context should have a clear ROI.
Original prompt (Chinese, left untranslated)
上下文预算分配建议(以 200K token 窗口为例):
系统提示 ██████████ 10% (20K token)
工具定义 ████████████████ 20% (40K token)
检索上下文 ████████████████████ 25% (50K token)
历史记录 ████████████████████████ 30% (60K token)
用户输入 ████████ 5%~10% (10-20K token)
预留缓冲 ████ 5% (10K token)
The actual proportion should be dynamically adjusted based on the Agent's specific task type.
If the Agent is mainly for code generation, the proportion of context retrieval can be increased.
If the Agent is a multi-turn dialogue assistant, the budget for history should be prioritized.
Engineering of system prompts
System prompts are the foundation of Agent behavior and need to follow structured writing principles.
Writing principles:
| Principle | Description | Example |
|---|---|---|
| Hierarchical organization | Chunk instructions by role, rules, process, and format | Use Markdown headings for separation |
| Positive phrasing | Tell the Agent what to do, rather than what not to do | "Keep the answer concise" is better than "Don't be verbose" |
| Provide examples | Use few-shot examples instead of long descriptions | Output format examples are more efficient than text descriptions |
| Priorities are clear | Which rule should the Agent follow when rules conflict | "Safety rules take precedence over efficiency requirements" |
| Remove redundancy | Delete rules that have never been triggered and duplicate descriptions | Regularly review and refine system prompts |
The following is an example skeleton of a structured system prompt:
Original prompt (Chinese, left untranslated)
## 角色
你是一名 Python 代码审查助手。
## Core Rules
- 每个问题附上修复建议
- 按严重程度排序输出
- 不确定时标注「待确认」
## Workflow
1. 分析代码变更
2. 按严重程度分类问题
3. 逐一输出问题与建议
## Output Format
**Question**: [Problem Description]
**Severity**: [High/Medium/Low]
**Suggestion**: [Fix Suggestion]
Optimization of tool descriptions
Tool descriptions often take up the largest proportion of the context, but many tools are never actually called.
Optimization strategies include:
| Strategy | Method | Effect |
|---|---|---|
| Tool simplification | Removing tool definitions irrelevant to the current task | Reduce tool context by 30%~50% |
| Refine descriptions | Each tool should be described in a single sentence detailing its purpose and parameters | Improve the model's understanding accuracy of tools |
| Parameter constraints | Clearly state the usage scenarios and limitations of parameters in the description | Reduce parameter errors in tool calls |
| Group registration | Dynamically register different sets of tools according to the task stage | Avoid "choice paralysis" caused by too many tools |
A tool definition is a burden if it is not zero. Each retained tool requires a trade-off between description quality and token cost.
History compression strategy
In multi-turn conversations, history grows rapidly and occupies the context.
A suitable compression strategy needs to be chosen to balance context completeness and window limitations.
Original prompt (Chinese, left untranslated)
Comparison of common historical compression strategies:
策略 方法 适用场景
─────────────────────────────────────────────────
滑动窗口 保留最近 N 轮完整记录 短对话、实时交互
阶梯摘要 每轮做一次增量摘要 长对话、客服场景
分层摘要 近期保留完整、远期做摘要 文档生成、复杂任务
关键轮标记 标记重要轮次,其余丢弃 调试、分步执行任务
Hierarchical summarization is the most common strategy: keep the last 3-5 turns intact, and replace earlier conversations with structured summaries.
Structured summaries should include key information from the original conversation: what the user's goal is, what the Agent did, what output was generated, and what errors were encountered.
Context retrieval quality control
When the Agent relies on external knowledge bases, the quality of the retrieved context directly determines the output quality.
Key points to improve the quality of retrieved context:
| Stage | Common problems | Improvement methods |
|---|---|---|
| Query rewriting | User input is not precise enough | Let the Agent rewrite the query before retrieval |
| Relevance filtering | Irrelevant content in the retrieval results | Set a relevance threshold and proactively prompt when it is insufficient |
| Source annotation | The Agent cannot judge the credibility of the information | Attach source path and update time |
| Length cropping | Search results occupy too much context | Truncate by paragraph, retain the most relevant snippets |
Common patterns
Progressive disclosure
Instead of stuffing all information into the context at once, it gradually discloses it according to the execution phase.
The initial context only contains the system prompt and the necessary tools for the current phase; the tools and rules for the next phase are injected after the Agent completes the current phase.
This pattern keeps the "density" of the context within a reasonable range, preventing the Agent from being distracted by irrelevant information.
Context compression chain
When a task requires processing a large amount of data, it is broken down into multiple steps using chained calls, with only key intermediate results retained at each step.
Original prompt (Chinese, left untranslated)
步骤1:读取全部日志文件 → 输出 { 错误数量,时间范围,错误类型列表 }
步骤2:基于步骤1的输出,分析 Top 3 错误 → 输出 { 根因分析,修复建议 }
步骤3:基于步骤2的输出,生成修复 PR → 输出 { PR 标题,描述,代码变更 }
The input for each link is the refined summary from the previous step, not the original data, ensuring the context size remains controllable.
Context Watermarking
Placing "watermark" tags at critical positions in the context helps in monitoring and diagnosing Agent behavior.
Original prompt (Chinese, left untranslated)
Context watermark example:
<system-reminder>
当前使用的上下文策略版本:v2.3
检索到的文档来源:docs/api-reference/ 共 3 个文件
已消耗上下文:85,000 / 200,000 tokens
</system-reminder>
These watermarks do not directly affect Agent behavior, but they allow for quick localization of whether context injection executed as expected during debugging.
Evaluation and Iteration
The effectiveness of context engineering must be verified through evaluation, not judged solely by intuition.
Commonly used evaluation dimensions:
| Dimension | Evaluation method | Key metrics |
|---|---|---|
| Task completion rate | Running Agent on standard test set | Success rate and failure reason distribution |
| Context efficiency | Statistics of context usage per call | Average token consumption, context utilization rate |
| Tool calling quality | Accuracy and parameter correctness rate of tool calls | Proportion of invalid calls, number of retries |
| Response consistency | Testing with the same input multiple times | Output stability, format compliance rate |
Context engineering is not a one-time configuration, but requires an iterative loop of "Test → Analyze → Optimize → Retest".
Notes
A larger context window is not always better. Too much context can dilute the model's attention on key information, thus reducing output quality.
Blindly adding rules can make the system prompt bloated and contradictory. Each new rule must be reviewed for conflicts with existing rules.
Modifications to tool definitions may affect the behavior of existing Agents; regression testing in typical scenarios is required after modification.
The history compression strategy needs to be chosen based on the Agent's task characteristics; no single strategy can be optimal in all scenarios.
Sensitive information in the context (API keys, internal paths, etc.) will propagate in tool calls and logs, so proper de-sensitization must be performed.
Related Concepts
| Concept | Description |
|---|---|
| Prompt Engineering | Prompt design and optimization focused on a single call |
| Context Window | The upper limit of tokens the model can process at once |
| Token | The smallest semantic unit that the model processes text with |
| RAG (Retrieval-Augmented Generation) | Architectural pattern for augmenting context through external retrieval |
| Few-shot Prompting | Providing examples in the context to guide model output |
| Chain-of-Thought | Allowing the model to demonstrate its reasoning process in the context |