A Practical Guide to Million-Token Context Agent Engineering
This article explains why a million-token context window is a capacity metric rather than a capability metric, and how to turn long context into reliable long-horizon execution. It covers context budget management, layered memory, tool orchestration, failure recovery and cost control, and evaluation, with sample code and state structures. The conclusion is that long context only becomes deliverable when supported by five engineering pillars: budget management, layered memory, tool orchestration, failure recovery, and evaluation.
1. The Problem: Long Context Does Not Equal Long-Task Capability
As the industry moves into the era of million-token context windows, many teams reach for the same first instinct: pack as much material as possible into the model in one shot and let the agent “read everything, then act.” Engineering practice quickly exposes the flaw in this approach. Context length is a capacity metric, not a capability metric. Capacity determines how much information you can fit; capability determines whether that information can be retrieved, ranked, associated, and converted into actions correctly.
Long-horizon tasks are hard not because any single reasoning step is complex, but because there are many steps, many states, and many dependencies. A typical gritty, hands-on scenario often involves reading large volumes of logs and documents, locating key clues, calling multiple internal systems, choosing among candidate approaches, executing changes, verifying results, and rolling back when something goes wrong. Failures in these tasks usually do not mean the model “does not know how” to do the work. More often, by step fifty it has forgotten a constraint from step two, or it picks the wrong field out of the eightieth tool response.
The core argument of this article is therefore that the value of a million-token context must be unlocked through an engineering mechanism: context budget management, layered memory, tool orchestration, state persistence, and observable evaluation. Without these mechanisms, a larger window only brings higher cost and less controllable drift.
2. Context Budget Management: Treat the Window as a Scarce Resource
No matter how large the window is, it should be managed as a scarce resource. A practical approach is to divide the context into four blocks, each with an explicit quota:
- System constraints block: task goal, boundaries, prohibitions, and acceptance criteria. Keep it resident and as short as possible.
- Working memory block: inputs for the current step, output from the previous step, and hypotheses awaiting verification.
- Long-term memory block: historical conclusions, domain knowledge, and code snippets obtained through retrieval.
- Tool output block: API responses, log fragments, and file contents, which must be trimmed and structured.
The first principle of budget management is “compress first.” Raw tool payloads often consume most of the space, so field filtering, paginated summarization, and anomaly aggregation should happen before the data enters the context. Illustrative code:
def pack_context(system, working, retrieved, tool_outputs, budget=1_000_000):# Reserve a fixed proportion for system constraints and output spacereserve = int(budget * 0.15)remain = budget - reserve - len(system)working = truncate(working, remain // 3)retrieved = rerank_and_truncate(retrieved, remain // 3)tool_outputs = summarize_tool_outputs(tool_outputs, remain // 3)return {"system": system, "working": working,"retrieved": retrieved, "tools": tool_outputs}
The second principle is “structure beats stacked natural language.” Normalizing tool output into key-value structures or tabular summaries significantly lowers the model’s parsing cost. For example, aggregating hundreds of log lines into “error code distribution + top anomaly stacks + key timeline events” works better than pasting the raw text.
The third principle is “rolling by segment.” A long task should not build a complete context in one shot; it should roll forward in stages. After each milestone, compress the process into conclusion entries and release the raw details. This controls size and reduces interference from irrelevant information.
3. Layered Memory: Remembering Step Two at Step Eighty
The goal of layered memory is to solve “remote forgetting.” A three-layer structure is recommended:
- Session layer: holds the real-time state machine of the current task, including completed steps, pending items, and blocking reasons.
- Task layer: holds structured conclusions, such as “the fault boundary is confirmed to be at the access layer” or “configuration center changes have been ruled out.”
- Knowledge layer: holds reusable domain knowledge and summaries of operating manuals, loaded on demand through retrieval.
The key design decision is the write policy. Not every intermediate artifact deserves to be written to a long-term layer; write only “reusable conclusions” and “constraint changes.” For example, if the user adds mid-task that restarting production instances is prohibited, that constraint must enter the session layer and stay resident at high priority, or it is very likely to be forgotten in later steps.
An illustrative state structure:
{"goal": "Locate and fix the rise in error rate during peak hours","constraints": ["Do not restart production instances", "Changes must be rollback-capable"],"done": ["Confirmed errors are concentrated at the access layer", "Ruled out dependency timeouts"],"blocked": [],"next": ["Verify connection pool configuration", "Canary release the patch"]}
4. Tool Call Orchestration: From “Able to Call” to “Able to Deliver”
An agent’s real value lies in execution, and execution quality depends on orchestration. Three rules are recommended:
- Least privilege: grant each tool call only the minimum scope needed for that step, so mistakes do not spread.
- Idempotency first: design all write operations to be retryable and idempotent, for example by deduplicating on a unique task identifier.
- Pre-checks and post-checks: validate parameters and state before execution, validate results after execution, and enter a compensation flow on failure.
Introducing a three-stage “plan-act-check” structure at the orchestration layer converges uncontrolled free generation into an auditable process:
plan: list steps and expected resultsact: call tools and record returns in a structured formcheck: compare expected with actual, decide continue/retry/rollback
Long tasks should also support resume from checkpoints. Persist the state machine to external storage, such as object storage or task records in a message queue, so that after a process restart the agent can recover from the most recent milestone instead of starting over. This saves cost and improves stability.
5. Failure Recovery and Cost Control
The direct consequence of a million-token context is higher cost and higher latency. Control measures include reranking retrieval results and keeping only highly relevant fragments; summarizing and deduplicating tool output; enabling result caching for repeated questions; and applying staged budgets to long tasks to avoid unbounded growth in a single stage.
Failure recovery should distinguish three classes of errors: retryable errors (network jitter), errors requiring compensation (partially successful writes), and unrecoverable errors (constraint conflicts). The corresponding strategies are exponential backoff retries, compensating transactions, and immediately halting and escalating to a human. Never let the model “improvise” when constraints conflict, because that turns a small problem into a production incident.
6. Evaluation: Using Data to Decide Whether the Work Can Be Delivered
Without evaluation there is no engineering. A four-layer evaluation is recommended:
- Single-step correctness: whether tool parameters are valid and returns are parsed correctly.
- Milestone achievement rate: whether each stage goal is completed.
- End-to-end delivery rate: whether the task meets the acceptance criteria and is rollback-capable.
- Safety and compliance rate: whether constraints are violated or privileges exceeded.
The evaluation set should cover three scenario types: long chains, strong interference, and constraint changes. Record a context snapshot at every step so you can tell whether a failure is a retrieval problem, an orchestration problem, or a constraint-retention problem.
7. Implementation Suggestions
If a team wants to build this kind of capability on Baidu AI Cloud, a general combination of services can be used: object storage to keep task snapshots, a message queue to drive stage transitions, a container platform to host executors, and logging plus monitoring and alerting services for full-chain observability. The core is not the components themselves, but turning context budgeting, memory layering, and state machine design into engineering standards.
In summary, a million-token context is only an entry ticket. What really determines whether an agent can finish the gritty work for you is the five pillars: budget management, layered memory, tool orchestration, failure recovery, and the evaluation system. Build them well, and a long window shifts from “able to read” to “able to deliver.”
