Architecture and Engineering Practice for Million-Token Context Agents
Million-token context is a practical requirement for tool-using, long-running agents, not a parameter race. This article covers typical agent workloads, sparse MoE and attention designs, KV cache and serving-stack work, explicit context budgeting, and evaluation that separates window length from effective context.
1. Long context is not a parameter race; agent load makes it a hard requirement
In general chat, a few thousand tokens can be enough. Once a model sits in an agent framework that runs continuously, calls tools, and keeps memory, token use rises quickly. Three typical loads illustrate the point.
Scenario 1: Multi-turn task agents. A coding agent that runs 30 turns stacks, each turn: user instructions (hundreds of tokens), three or four source files (thousands to tens of thousands), commands and stdout (thousands more), and the model’s own reasoning traces (thousands). Linear accumulation makes hundreds of thousands of tokens the norm, not the exception. Early systems dropped historical traces when a new user message arrived not by preference, but because the window was too small—keeping them hurt both quality and cost.
Scenario 2: Repository-scale understanding and refactoring. A mid-size project of about 300 files and 150k lines of code often tokenizes to roughly 800k–1.2M tokens. “Retrieve snippets and rewrite locally” breaks cross-file dependencies, implicit contracts, and call chains. The model sees only local optima, and refactors often fail at integration.
Scenario 3: Persistent memory and long-document reasoning. Long-running assistants accumulate structured memory, prior conclusions, and user preferences; contracts, logs, and monitoring snapshots need a full read and cross-comparison. The hard part is not “reading a lot,” but stably locating information and doing multi-hop association in very long context.
A minimal budget model:
def estimate_context(turns, files_per_turn, avg_file_tokens,stdout_tokens, trace_tokens):per_turn = 300 + files_per_turn * avg_file_tokens \+ stdout_tokens + trace_tokensreturn turns * per_turn# 30 turns, 4 files per turn, 3000 tokens per fileprint(estimate_context(30, 4, 3000, 2000, 1500))# ~495k tokens, excluding system prompt and tool definitions
The conclusion is clear: a 128K window overflows after a few real agent turns. Million-token context is the line between “usable” and “good.”
2. Two architectural pillars for million-token context
Pillar 1: Sparse mixture-of-experts. Leading open models often use a large total parameter count with a small activated count—for example ~1.6T total with ~49B activated per token, or ~284B total with ~13B activated. Parameter capacity sets the knowledge ceiling; activation size sets per-forward compute. Decoupling them keeps the compute blow-up from long context manageable. Two misconceptions: the smaller tier is not a distillation of the larger one—they are independently pretrained siblings that differ in scale and sparsity, so latency-sensitive results should not be treated as a “shrunken” version of the large tier. Million-token context is not a toggle; both tiers support it by default, so the serving stack no longer routes long vs. short models and avoids inconsistent behavior.
Pillar 2: Sparse and hierarchical attention. Full attention scales quadratically with sequence length and is not feasible at a million tokens. Common practice mixes local windows, global anchors, and sparse selection: local windows model nearby dependencies, global anchors keep topic consistency across sections, and sparse selection provides cheaper “look back on demand.” With positional encoding extrapolation and interpolation, the model can stay stable beyond the training length.
3. System rewrite: from kernels to the serving stack
Architecture is only the entry ticket; most engineering sits in kernels and serving.
- KV cache management: Paged cache, prefix sharing, and cache quantization dominate long-context cost. In multi-turn agents, system prompts, tool definitions, and already-read files repeat heavily; prefix reuse often covers most of the compute.
- Operator fusion and memory access: For long sequences the bottleneck is usually memory bandwidth, not FLOPs. Fusing attention and cutting intermediate tensor reads/writes often beats simply raising parallelism.
- Parallelism and communication overlap: Tensor parallel on weights, context parallel on the sequence, and pipeline parallel on layers must overlap communication with compute, or communication share on long sequences erodes the gains.
- Scheduling and batching: Continuous batching with chunked prefill keeps one long request from blocking a batch of short ones and improves tail latency.
On the cloud these map to generic building blocks: containers for inference, object storage for models and long documents, queues for burst control, and logging/monitoring for hit rate and tail latency. Platforms such as Baidu AI Cloud offer combinations of these capabilities; choose against your own load profile.
4. Context budget management and effectiveness evaluation
Budgets must be explicit. Do not expect the model to “figure it out.” Allocate quotas in the application:
class ContextBudget:def __init__(self, limit=1_000_000):self.limit = limitself.reserve = int(limit * 0.1) # reserve for output and tool defsdef allocate(self, system, memory, files, history):fixed = system + memoryremain = self.limit - self.reserve - fixedfile_quota = int(remain * 0.5)hist_quota = remain - file_quotareturn self._trim(files, file_quota), self._trim(history, hist_quota)
Beyond quotas, use eviction: compress duplicate file content, fold completed-turn tool output, and summarize reasoning traces instead of keeping them in full.
Evaluate “window length” separately from “effective context.” Run four tracks in parallel: coding (cross-file completion and refactor), math (multi-step reasoning), agents (long-horizon tool use and state consistency), and long text (multi-hop retrieval and global synthesis). Long-text cases must bury key facts and require multi-hop links; testing only the first and last segments badly overestimates capability.
Load-test a baseline before launch: fixed input lengths (32K / 128K / 512K / 1M), record time-to-first-token, throughput, cache hit rate, and cost per request, and keep a capacity model you can regress against.
5. Closing
The value of million-token context is not the number itself, but moving agents from snippet Q&A to whole-repo understanding, long-horizon execution, and persistent memory. Experience depends on sparse architecture, attention design, cache management, and kernel work acting together—and on whether the application has a clear context budget. Get those layers right and long context becomes measurable business value, not a paper spec.
