A Practical Guide to Million-Token Context Engineering for AI Agents
This article explains how to build reliable, testable, and cost-controlled AI agents when working with million-token context windows. It covers context budgeting across system, task, evidence, and scratch layers; tiered memory that combines the session window with external storage; tool orchestration safeguards such as idempotency, least privilege, and sandboxing; three-layer acceptance and regression testing; and cost, security, and observability practices. The goal is to move long-context agents from demo-ready to production-ready.
1. The Problem: Long Context Improves Visibility, Not Task Completion
Over the past two years, open-weight models with large parameter counts have commonly adopted context windows of one million tokens or more. Feeding an entire code repository, a full set of API documentation, and dozens of log files into a model at once has gone from a thought experiment to routine practice. The initial expectation was straightforward: with a long enough context, an agent could read requirements, browse code, run commands, modify files, and write tests on its own, completing in one pass the tedious work that previously required people to shuttle information back and forth.
In real engineering environments, however, long context only solves information reachability, not task completion. A model that can absorb one million tokens still makes typical mistakes in long-chain tasks: it forgets early constraints after reading a middle section, misconstructs tool call arguments, repeats the same side-effect operation, amplifies noise during failure retries, and finally produces output that looks complete but fails acceptance.
This article therefore does not discuss the capabilities of any specific model. Instead, it frames the topic as a general engineering problem: how to build a reliable, testable, and cost-controlled agent system under extremely long context conditions. The following six areas are what move an agent from “works in a demo” to “works in production.”
2. Context Budget: Treat the Window as a Finite Resource
The biggest trap of million-token context is the assumption that filling it up is optimal. In practice, effective attention utilization drops on extremely long sequences, and irrelevant content dilutes critical instructions. A more robust engineering approach is to set layered budgets:
- System layer (about 1%): role, safety boundaries, output format, and prohibited behaviors. This must always sit at the front of the sequence and must never be compressed.
- Task layer (about 10%): goals, acceptance criteria, and constraints, reproduced consistently on every call.
- Evidence layer (about 60%): retrieved code snippets, documentation passages, and log excerpts, sorted by relevance and tagged with their sources.
- Scratch layer (about 29%): intermediate reasoning, tool returns, and open questions, which may be summarized and compressed.
Illustrative budget control logic:
def build_prompt(system, task, evidence, scratch, limit=1_000_000):# Keep the system and task layers intact first, then trim the evidence layerreserved = len(system) + len(task)budget = limit - reservedevidence = rank_by_relevance(evidence)[:budget // 2]scratch = summarize(scratch)[:budget // 2]return system + task + evidence + scratch
The key point is that evidence must be traceable and scratch must be discardable. If a piece of information cannot be traced back to a specific file, API, or log line, it should not influence the final decision.
3. Tiered Memory: Short Term in the Window, Long Term in External Storage
A single million-token context cannot carry a project’s evolution across days. Mature designs split memory into three tiers:
- Working memory: the current session window, holding the files being processed and command output.
- Project memory: structured summaries such as module responsibilities, API contracts, build methods, and known defects, persisted as versionable text or index entries.
- Archive memory: historical conversations and artifacts, placed in object storage and retrieved on demand through search.
General-purpose capabilities such as object storage, log services, and monitoring and alerting on Baidu AI Cloud are suitable for archiving and observability: artifacts and intermediate states are written to object storage with versions retained; key steps are reported in structured form to the log service; and metrics such as error rate, average step count, and token consumption per task are connected to monitoring and alerting to trigger threshold-based automatic notifications. No proprietary interfaces are involved here; selection only needs to consider whether versioning, access control, and pay-as-you-go billing are supported.
4. Tool Orchestration: Keep Side Effects in a Cage
Agents do real work through tool calls, and tool calls are where risk concentrates. Three hard rules are recommended:
- Idempotency first: design all write operations to be re-entrant and carry a unique request identifier, so retries do not cause duplicate submissions.
- Least privilege: issue credentials temporarily per task, grant no write permission to read-only tasks, and require a second confirmation for deletion operations.
- Sandbox isolation: perform code execution, dependency installation, and network access inside a container platform, with egress traffic going through an allowlist.
A reusable execution skeleton:
def run_step(step, ctx):if step.side_effect and not ctx.approved(step):return {"status": "pending_confirm", "step": step.id}result = sandbox.call(step.tool, step.args, idempotency_key=step.id)log_service.report(step.id, result.status, result.elapsed_ms)return result
Combined with a state machine that manages the task lifecycle (pending confirmation, executing, pending acceptance, completed, rolled back), this significantly reduces the chance of an agent “talking to itself” and damaging the environment.
5. Evaluation and Regression: Automation Without Acceptance Criteria Cannot Ship
Long-chain tasks must be closed out with executable criteria. An effective practice is three-layer acceptance:
- Static checks: format, types, required fields, static analysis, and style rules all pass.
- Dynamic checks: unit tests and integration tests pass, build artifacts run, and coverage does not drop.
- Human spot checks: sample a proportion of outputs to review semantic correctness, with particular attention to boundary conditions and security-related changes.
Also build a regression set: turn historical failure cases into test cases and rerun them after every change to prompts, retrieval strategy, or the toolset, watching three curves: success rate, average step count, and rollback rate. If the success rate rises while the average step count surges at the same time, it usually means the model is using redundant attempts to mask a strategy defect. In that case, optimize retrieval and planning rather than enlarging the context further.
6. Cost, Security, and Observability
Token consumption grows roughly superlinearly with task complexity, so cost governance must come first: deduplicate and summarize evidence, cache repeated requests, route small tasks to smaller model tiers, and set step and time limits for long tasks. On the security side, ensure end-to-end auditing: who approved which step, what commands were executed, and what data changes were produced must all be queryable and reviewable.
7. Conclusion
Million-token context is necessary infrastructure, but not a sufficient condition for completing tasks. What truly lets agents take over repetitive work is the combination of four things: strict context budgeting, tiered memory, controlled tool orchestration, and executable acceptance and regression. Engineering these four, and using the standard storage, logging, and monitoring capabilities of general cloud products to fill in observability and governance, is what turns long context from “can read a lot” into “can deliver results.”
