Engineering Long-Horizon Agents for Million-Token Context Models
Long-horizon agents shift large models from single-turn generation toward sustained work across planning, tools, and delivery. This article covers memory governance for million-token windows, evaluation of code and terminal tasks, scaled post-training reinforcement learning, inference throughput, managed agent infrastructure, API cost control, and a staged path to production with clear risk boundaries.
The main line of large-model progress is moving from single-turn generation quality to whether a model can keep completing complex work. Very large parameter counts, million-token context windows, code and terminal operations, 3D tool use, financial research, and long-horizon agents are now judged inside the same engineering system. For developers, what matters is not only a benchmark score, but how model capability is organized into a production system that can run, be observed, and be governed. This article is not about a specific product. It focuses on the general technical problems of putting long-horizon agents into production.
1. The capability shift: from answering to sustained work
A long-horizon agent does not simply generate one block of text. Over a longer span of time it keeps planning, calling tools, reading results, revising its strategy, and eventually delivering the task. That shift creates at least three changes.
First, context changes from a prompt into working memory. A million-token window can hold more repository fragments, task traces, tool results, and past decisions, but a larger window does not make memory management simpler. Irrelevant content, repeated logs, and stale state dilute attention and raise inference cost. Engineering therefore needs layered memory: short-term traces keep raw results, mid-term memory compresses them into summaries, and long-term memory stores task constraints, domain knowledge, and lessons from failure.
Second, tool use changes from an optional enhancement into the execution backbone. A coding agent must run commands, read files, and execute tests. A financial-research agent must retrieve data, compute metrics, and produce reports. A 3D creation agent must call modeling and rendering tools. Tool results are often unstructured, long, and noisy. The model has to judge whether a result is trustworthy and, on failure, retry or switch strategy.
Third, evaluation changes from a single correct point to a process that can be checked. Long-horizon tasks are hard to judge by the final answer alone. Intermediate steps must be checked against resource limits, safety boundaries, and irreversible side effects. A deployable agent system should split work into verifiable subgoals and attach a test, assertion, or human review point to each one.
2. Million-token context: memory governance beyond the window size
The value of a million-token context is that it reduces frequent truncation and information loss. It also makes context engineering more important. Common problems in practice include higher time-to-first-token and inference cost as context grows, lower cache hit rates when the same background is pasted repeatedly, and later steps being pulled off course by wrong conclusions already stored in the trace.
A practical loop is write, compress, retrieve, and evict:
- Write: store tool results, code diffs, and test output as structured events, with timestamps, sources, and confidence.
- Compress: summarize long logs. For code diffs, keep the intent of the change, the scope of impact, and the test results rather than every raw line of output.
- Retrieve: on each planning turn, inject only the fragments relevant to the current subgoal instead of stuffing the entire history into the prompt.
- Evict: tag failed hypotheses that have already been ruled out, expired tool results, and duplicate information so they rank lower in later retrieval.
The following pseudocode illustrates the idea:
def build_context(task, memory, step):constraints = memory.get_long_term("constraints")recent = memory.get_recent(window=step_recent)relevant = memory.retrieve(task.current_goal, top_k=8)compressed = compress(recent + relevant)return assemble(constraints, compressed, task.current_goal)
The point is not a specific interface. Context should be treated as a governed data asset. Caching matters as well: stable system prompts, tool instructions, and domain constraints should keep a stable prefix so cache hits stay high. Dynamic traces should be injected only when needed, not concatenated without order.
3. Code and terminal tasks: the metric defines the optimization
Code and terminal work are typical tests of long-horizon agents because they have real resource limits, clear success criteria, and results that can be checked automatically. Public terminal-environment programming benchmarks usually ask an agent to finish a complex task in a constrained environment and then judge the result with dedicated tests. That is closer to real development than code completion alone: the agent must understand the repository, locate the problem, edit files, run tests, handle failures, and control side effects.
From an engineering view, a coding agent should be judged on four metrics:
- Task completion: not only whether code was generated, but whether tests pass.
- Long-horizon stability: whether the goal stays consistent after many tool calls.
- Output efficiency: whether explanations are verbose, retries are repeated, or commands do nothing useful.
- Safety boundaries: whether the agent accesses resources beyond its authority, runs dangerous commands, or pollutes the environment.
Uneven capability and verbosity remain common. Strong coding ability does not mean balanced performance on general reasoning, financial research, or 3D tool use. Verbose output raises token use and review cost. Useful directions include a broader mix of domains in training and post-training, output budgets and stop conditions at inference time, and process scoring in evaluation that penalizes useless steps.
4. Scaling post-training RL across hundreds of domains
Pretraining scale alone is not enough to improve long-horizon agents. Post-training compute and the breadth of reinforcement learning coverage become critical. Extending RL to hundreds of downstream domains means the training system must handle different tool environments, reward functions, task durations, and failure modes at the same time. That creates infrastructure pressure:
- RL framework: support asynchronous sampling, distributed rollouts, trajectory replay, and reward aggregation so long-tail tasks do not stall overall throughput.
- Long-context inference: both training and inference must handle long traces. KV cache, batching, and GPU memory become bottlenecks.
- Training efficiency: task length varies widely across domains, so dynamic batching and load balancing are required.
- Sandbox infrastructure: code execution, tool calls, and network access must be isolated, and failed environments must be reclaimed quickly.
- Scheduling: mix long tasks, short tasks, and high-priority tasks so utilization and fairness both hold.
- Environment quality checks: reward functions can be gamed. Automatically check whether an environment is reproducible, whether the reward is sound, and whether the task leaks the answer.
A robust practice is to manage environments as code. Each domain environment has a version, dependencies, an initial state, and a validation script. Every RL sample records the environment version and random seed. Environments with high failure rates are automatically down-weighted or taken offline. Otherwise the model learns bad strategies from low-quality environments.
5. Faster inference: throughput at the same level of capability
Long-horizon agents often need many turns, so the speed of a single response directly affects total task time. A high-speed variant is usually not just a smaller model. It keeps capability roughly the same and raises throughput through inference-system techniques such as continuous batching, KV-cache reuse, operator fusion, parallel scheduling, speculative decoding, or quantization. Developers should separate single-request latency from system throughput. Latency shapes interactive experience; throughput shapes the cost of batch work.
Architecturally, split interactive work from batch work. Interactive tasks favor low latency; batch tasks favor high throughput. Stable prefixes go through the cache; dynamic traces are computed on demand. Long tasks should have checkpoints and timeouts so one call cannot stall the queue. A high-speed path fits latency-sensitive long-horizon work, but it should not sacrifice observability. Each turn still needs records of latency, token use, and tool failure rate.
6. Managed agents: the runtime becomes infrastructure
When agents must run around the clock and coordinate with other agents, the runtime itself becomes infrastructure. The core value of a managed agent service is to package the task queue, state store, sandbox execution, tool gateway, trace logs, failure retry, and access control as cloud capabilities so developers can focus on task logic.
On Baidu AI Cloud, developers can combine general capabilities such as a container platform, object storage, message queues, logging, and monitoring and alerting to build their own sandbox pool, trajectory store, and task-scheduling path. For example, the container platform hosts isolated execution environments, object storage keeps task traces and artifacts, a message queue decouples task dispatch, and logs plus monitoring track the health of long-running work. The point is composing general capabilities, not depending on one proprietary interface.
Multi-agent collaboration also needs an explicit protocol: who plans, who executes, and who reviews; how shared memory is partitioned; how conflicts are resolved; and how failures are escalated. Give each agent a role boundary and a tool allowlist, persist every cross-role message, and require human confirmation or a second check for critical actions.
7. API and cost governance: cache, tiers, and quotas
Token-based APIs fit elastic agent calls, but long-horizon tasks can lose control of cost. General controls include differentiated pricing for cached input, context compression, output budgets, task quotas, model tiers, and a cap on retries. Cache hits can sharply cut the cost of repeated context, so system prompts and tool instructions should stay stable. Summarize history instead of replaying it in full. Use a lower-cost model for simple subtasks and a higher-capability model for critical decisions.
Cost also needs attribution. Record token use by task, tenant, tool, and model version, and set daily or weekly budgets with anomaly alerts. Long-horizon tasks should support checkpoint resume so a failure does not force a full rerun. High-risk actions such as writing files, running commands, or calling external services should have approval and rollback policies.
8. A rollout path and risk boundaries
Bring long-horizon agents online in stages. In the first stage, choose verifiable, low-side-effect work such as code fixes or report generation, and build an evaluation set plus trajectory logs. In the second stage, add multi-tool calls and checkpoints for long tasks, and complete the sandbox and permission model. Only in the third stage expand to multi-agent collaboration and always-on operation. Keep a human review point at every stage so unverified intermediate conclusions are not used directly for production decisions.
Risk boundaries matter just as much. A model can produce a conclusion that looks reasonable but is wrong. Tool output can be contaminated. A long context can amplify a false premise. Reproducible environments, process assertions, least privilege, audit logs, and rollback reduce that risk. Long-horizon agents move from demos to sustainable production systems only when model capability, the runtime, evaluation, and cost governance are designed together.
