Architecting AI Agents for Million-Token Contexts: Engineering Practices

    This article explains why the traditional "good enough" context window assumption is breaking down as applications evolve from simple Q&A into task-executing agents. It covers the correct way to understand parameter scale and sparse activation in large Mixture-of-Experts models, the system-level attention and kernel redesign required for long contexts, and a practical framework for context budget governance that treats the window like memory management. The article also outlines evaluation dimensions and a phased rollout path, showing that the feasibility of million-token contexts comes from the combination of sparse architecture, kernel optimization, and budget governance.

    1. Why the “Good Enough” Assumption Is Failing

    When evaluating a conversational application in the past, a window of a few thousand tokens was usually sufficient: one question, one answer, and the context discarded when the session ended. But as software evolves from “Q&A” into “agents that execute tasks,” the usage pattern of context has changed structurally. It is no longer a temporary scratchpad; it is the single carrier of task state.

    Three typical scenarios illustrate where the pressure comes from:

    • Multi-turn coding tasks: A coding agent workflow running thirty turns accumulates user instructions, source file snippets, command execution results, and the model’s own reasoning traces on every turn. The per-turn increment may look small, but the cumulative total routinely reaches hundreds of thousands of tokens.
    • Persistent memory: To make an assistant “remember,” the system repeatedly injects historical conclusions, preferences, and environment constraints into the prompt. The longer the memory, the higher the fixed overhead per request.
    • Long-document and log analysis: Whole-repository retrieval, full-log troubleshooting, and long-report comparison inherently require a large context visible at once.

    The conclusion is direct: context length is not a marketing parameter but a hard constraint on task completion rate. When the window is insufficient, the system is forced into lossy truncation, which shows up as “forgetting earlier constraints,” “repeating completed steps,” and “losing the goal in long tasks.”

    2. Understanding Parameter Scale and Sparse Activation Correctly

    Take two configurations of an open-source ultra-large-scale Mixture-of-Experts model as an example (for technical illustration only): one has trillions of total parameters with roughly five billion parameters sparsely activated per token; the other has hundreds of billions of total parameters with roughly ten billion activated. Two common misconceptions need clarification:

    1. The smaller tier is not a distilled product of the larger one. Both are independently pre-trained sparse expert networks; the difference lies in total capacity and sparsity, not in being a “compressed version.”
    2. Long context is not a toggle. Both tiers have million-level context capability by default, and the serving side no longer distinguishes between long and short models, which simplifies the routing layer.

    The point of sparse activation is this: total capacity determines breadth of knowledge, while activation volume determines the compute cost per token. Only when the two are decoupled can a balance be struck between a “large model” and “affordable inference.”

    3. System-Level Redesign of Attention and Kernels

    The real engineering difficulty is not the parameter table but the complexity of attention. Standard full attention grows quadratically with sequence length and is infeasible at one million tokens. Common redesign directions in the industry include:

    • Sparse and block attention: Change global visibility into “local window + a few global anchors + block summaries,” pushing complexity close to linear.
    • Multi-query / grouped-query attention: Compress the number of key-value heads to reduce memory bandwidth pressure, which is the main bottleneck in long-context inference.
    • Positional encoding extrapolation: Use frequency scaling and interpolation strategies so that generalization beyond the training length does not collapse.
    • Co-design of operators and kernels: Fuse attention, normalization, and expert routing into a few efficient kernels to reduce round trips of intermediate tensors; combined with paged key-value cache management to reduce fragmentation and copying.

    Illustration (pseudocode, expressing only the idea of block visibility):

    1. # Each query can only see: local window + global anchors + summary of its block
    2. def build_mask(q_pos, seq_len, window=4096, block=8192):
    3. local = (q_pos - window) <= k_pos <= q_pos
    4. anchor = k_pos < 64 # global anchors
    5. summary = block_id(k_pos) == block_id(q_pos) # in-block summary
    6. return local | anchor | summary

    4. Context Budget Governance: Treat the Window Like Memory Management

    Without budget constraints, a million-token window is quickly filled with ineffective content. It is advisable to establish an explicit budget table and perform admission checks before each request:

    Category Suggested Share Eviction Strategy
    System instructions and tool definitions 5%–10% No eviction; versioned compression
    Task state and plan 10%–15% Retain structurally, remove redundancy
    Retrieval and file snippets 40%–50% Relevance ranking + summary replacement
    Historical traces 20%–30% Layered summaries, keep conclusions only
    Reserved output 10% Mandatory retention

    Supporting engineering measures:

    • Prefix cache reuse: Fixing system instructions and tool definitions allows cache hits to significantly reduce repeated computation.
    • Layered memory: A three-tier structure of recent raw text, mid-term summaries, and long-term vector retrieval, fetched on demand rather than injected in full.
    • Externalized structured state: Put plans and variables into object storage or a key-value store, keeping only pointers in the context, avoiding “using the prompt as a database.”
    • Observability: Perform attribution statistics on token sources, monitor cache hit rate, truncation counts, and the correlation between task failures and context length, and close the loop through logging services and monitoring alerts.

    5. Evaluation and Deployment Recommendations

    Evaluation should cover four dimensions: code generation and repair, mathematical reasoning, tool calling and long-horizon planning, and long-document understanding. Beyond accuracy, record “effective context utilization” (the share of content actually referenced) and “cost per task.” A suggested deployment path: first run comparative stress tests with the two configurations on a container platform to determine concurrency and memory watermarks; then scale up gradually while keeping fast rollback available; finally, move the budget table and eviction strategies into a configuration center for adjustable and controllable operation.

    In summary, the value of ultra-long context comes from task completion rate, while its feasibility comes from the product of three things: sparse architecture, kernel optimization, and budget governance. If any one of them is missing, a million-token window is just a number on paper.