Long-Horizon AI Agents and Million-Token Context: LLM Post-Training, Harness Design, and Infrastructure
The benchmark for large language models is shifting from answering a single question correctly to reliably completing real, multi-hour tasks across long agent sessions. This article breaks down the techniques and engineering practices behind that shift: verifiable-reward reinforcement-learning post-training, million-token context engineering, the agent runtime framework (Harness), training and inference infrastructure, and high-speed inference. It also covers practical patterns for coding, financial-research, and 3D-creation agents, plus guidance on cost, stability, and governance. Developers and technical decision-makers will find concrete takeaways for building and operating their own production LLM agents.
The boundaries of what large language models can do are being redrawn. The benchmark is no longer “can it answer a single question correctly” but “can it independently complete a real task that spans many rounds of interaction and runs for hours or even days.” Recently, a Chinese LLM team released a new-generation, trillion-parameter model that supports a million-token context and focuses on strengthening code generation, financial research, 3D content creation, and long-horizon agent capabilities. A high-speed inference version with comparable capabilities shipped alongside it. The team also plans to open the full model weights at a later date and to launch a hosted agent service for long-running tasks.
For developers and technical decision-makers, the signal is clear: post-training compute is shifting its focus from “single-turn dialogue performance” to “sustained agent environments.” This article walks through the key techniques and engineering practices across five areas — post-training methods, long-context engineering, the agent runtime framework (Harness), training and inference infrastructure, and high-speed inference — to help teams build their own LLM applications.
1. Why Long-Horizon Agents Are the Dividing Line
Over the past two years, gains in model capability have broadly moved through three stages:
- Pretraining scaling: larger parameter counts and more data, which mainly address breadth of knowledge;
- Instruction tuning and human-feedback alignment: making outputs better match human preferences and interaction habits;
- Post-training reinforcement learning and agent capabilities: letting the model iterate through trial and error on verifiable tasks such as coding, math, and tool use, and learn to plan multi-step actions.
Long-horizon agents are hard for three “asymmetry” reasons:
- Errors compound: a task with 95% per-step accuracy has only about a 0.95²⁰ ≈ 36% chance of completing 20 consecutive steps without a fatal error. Improvements in per-step capability only translate into long-task success when paired with effective error detection and recovery.
- Context balloons: interaction history, tool return values, and intermediate artifacts accumulate quickly. Contexts that reach hundreds of thousands or even over a million tokens are both the foundation of long tasks and a source of inference cost.
- Environment state is complex: real tasks involve stateful code repositories, file systems, databases, and external interfaces. The model must not only “think correctly” but also “act correctly” at the execution layer.
A long-horizon agent is therefore a systems-engineering problem. Model capability alone is not enough — post-training, long context, the runtime framework, and infrastructure must evolve together.
2. Post-Training: The Main Battlefield for Capability Leaps
Compared with continuing to pile on compute during pretraining, post-training offers three clear advantages:
- Objective alignment: post-training optimizes task success rate directly, rather than next-token prediction probability;
- Short iteration cycles: no need to train from scratch — data and policy updates can be validated quickly;
- Domain extensibility: adding tasks and rewards for a new domain directly targets improvements in that domain.
2.1 Verifiable Rewards: Turning Right and Wrong into Computable Signals
The most common post-training paradigm is reinforcement learning with verifiable rewards, where rewards come from deterministic judgment rather than human-preference scoring:
- Rules and test-driven: code tasks are judged by unit tests, compilation, and static checks; math and reasoning tasks are compared against reference answers; structured outputs are checked for format validity.
- Model review: subjective tasks such as writing, analysis, and planning can be scored by a reviewer model or by voting across multiple models.
- Environment feedback: tasks like function calls, terminal commands, and page operations use execution results, assertions, and state changes as signals.
Reward-function design directly determines training outcomes. Three practical lessons:
- Densify the signal: a binary 0/1 reward is extremely sample-inefficient. Break it into components such as compilation success, test pass rate, and completion of critical steps.
- Prevent reward hacking: a model may learn to “make tests pass” rather than “build the feature correctly” — for example, by hard-coding expected values or skipping key logic. Close off these shortcuts with hidden test cases, mutation testing, and code-quality constraints.
- Rejection-sampling fine-tuning: sample many trajectories with the current policy, filter out those that pass verification, then run supervised fine-tuning on them. This is a common, low-cost way to improve capability beyond reinforcement learning.
def evaluate(task):if not task.format_valid:return -0.5 # format penalty to suppress output degradationresult = run_tests(task.repo, task.patch, hidden=True)if not result.environment_ok:return 0.0 # environment anomaly does not count toward rewardscore = (0.5 * result.passed_ratio # test pass rate: dense signal+ 0.2 * float(result.compiled) # compilation passed+ 0.2 * result.critical_passed # hidden critical test cases+ 0.1 * result.quality_score # static checks and code quality)return score if score >= task.threshold else 0.0 # threshold filters low-quality trajectories
2.2 Joint Training from One Domain to Hundreds
Extending reinforcement learning from a few domains like code and math to hundreds of downstream domains is one of the most visible changes in the new generation of models. The difficulty is not “adding domains” but “not letting them hurt each other”:
- Balanced task distribution: data volume across domains can differ by orders of magnitude. Sampling naively lets high-volume domains dominate the gradient, so you need to balance with sampling weights or difficulty-based bucketing.
- Prevent catastrophic forgetting: foundational capabilities like general dialogue and instruction following must be continuously “rehearsed” during training — mix in a proportion of general data or use a replay mechanism.
- Capability routing and specialized policies: the optimal behavior differs greatly by domain. Code needs rigorous verification and debugging habits; financial research emphasizes traceable sources and numerical accuracy; 3D creation emphasizes understanding of space and parameters. Joint training can introduce domain identifiers or routing to keep policies from conflicting.
2.3 Training Stability and Engineering Details
- Cold start: doing supervised fine-tuning on high-quality trajectories before entering the reinforcement-learning stage can significantly shorten exploration time.
- Policy constraints: use a divergence penalty to limit how far the new policy drifts from the old one, and add entropy regularization to preserve exploration and avoid early training collapse.
- Reward normalization: standardize rewards within each task group to reduce gradient noise from differences in task difficulty.
- MoE load balancing: trillion-parameter models typically use a sparse mixture-of-experts (MoE) architecture where only a subset of experts is activated to cut compute. Training must constrain the expert-load distribution to prevent routing collapse and a few experts from being overloaded.
3. Million-Token Context: The Foundation of Long Tasks
Expanding the context window from tens of thousands to a million tokens is not simple capacity scaling.
3.1 Implementation Approaches
- Length extrapolation: models are usually pretrained on relatively short sequences and then extended to longer windows via position-encoding interpolation, adjusting the rotary position embedding (RoPE) base frequency, continued pretraining, and similar methods. A larger base frequency makes the angular difference between adjacent positions smoother, which helps extrapolation.
- Attention efficiency:
- Grouped-query attention (GQA) lets multiple query heads share a group of key/value heads, greatly compressing the KV cache;
- sparse attention and linear attention reduce the compute that grows with sequence length;
- paged KV-cache management reduces memory fragmentation and improves batch concurrency.
- Long-sequence continued pretraining: mixing in long samples at a fixed ratio during continued pretraining so the model actually “sees” long-range dependencies.
3.2 Long Context Is Not the Same as Using It Correctly
- Middle information gets overlooked: as context grows, key information in the middle is often ignored by the model. Put critical instructions and constraints at the end of the system prompt or in the most recent turns, and explicitly annotate section positions within long documents.
- Structure your prompts: with massive context, the main failure modes are conflicting instructions and diluted attention. Organize system instructions, tool specifications, background material, and the user request into separate zones, and keep the structure stable.
# System instructions (versioned, structurally stable)## Role and goal## Global constraints (safety boundaries, forbidden operations)## Tool usage rules (when to call, parameter validation, failure retry)## Output format rules# Tool list (JSON Schema declares names, parameters, return structures)# Background knowledge (put stable parts first for prefix caching)# Task context (changes per task)- Task goal and acceptance criteria- Summary of completed steps and key conclusions- Current workspace state# Latest user request (placed last, highest priority)
- KV-cache reuse: stable prefixes such as the system prompt and tool definitions can reuse their KV cache, avoiding recomputation on every turn. This both cuts latency significantly and underpins the cost tiering discussed below.
4. Harness: The Runtime Foundation of Long-Horizon Agents
If the model is the brain, the Harness (the agent runtime framework) is the body and nervous system. Around the model, it uses deterministic code to manage the loop, tools, state, and errors. A Harness must answer at least four questions: when the loop starts and ends, how errors are handled, how state is saved and restored, and how permissions are constrained.
4.1 Loop and Termination
An agent is essentially an “observe–think–act” loop, and the Harness must define clear termination conditions:
- Task completion: the model declares it is done, and a verifier checks the result;
- Failure termination: an unrecoverable error occurs, or the same ineffective operation repeats too many times;
- Budget exhaustion: a maximum step count, token budget, time limit, or cost cap is reached.
An agent without strict budget control easily falls into a “keep retrying, keep burning money” death loop.
4.2 Error Classification and Recovery
Tool-call failures are the norm in real environments, and the Harness should respond differently by error type:
- Retryable: timeouts, rate limiting, and network jitter — use exponential backoff and cap the retry count;
- Needs a different path: parameter errors, insufficient permissions, missing dependencies — return the full error to the model so it can adjust its plan;
- Fatal: terminate immediately and report, to avoid wasting resources.
Returning the raw error text to the model in structured form — rather than a generic “execution failed” — is a key detail for improving long-task success rates.
4.3 State Persistence and Resume
Tasks that run for hours or days must support “pause–resume.” A common approach is event sourcing: an event log records the input, output, and timestamp of every step, and a checkpoint is written after each stage completes. On failure recovery, the Harness rebuilds context from the most recent checkpoint instead of rerunning from scratch.
4.4 Sandbox Isolation and Least Privilege
Because agents can execute code, read and write files, and access the network, the runtime framework must enforce security boundaries:
- Container isolation: code runs in isolated containers, with the writable filesystem scope and network egress restricted;
- Permission tiers: reads, sandbox writes, and production writes are authorized separately, and high-risk operations require human confirmation;
- Resource quotas: cap CPU, memory, execution time, and concurrency so a single task cannot take down a node;
- Full audit: record the actor, parameters, and result of every tool call to meet traceability and compliance requirements.
4.5 Reference Implementation
def run_agent(task, budget):state = load_or_init(task.id) # resume from checkpointwhile not state.done and budget.remaining():if state.repeated_action_count >= 3:# repeated ineffective actions, force a strategy changestate.inject("Detected repeated operations. Please re-evaluate the current approach.")observation = build_observation(state) # structured observation, including raw error textaction = model.plan(observation, tools=registry, budget=budget)if action.type == "submit":verdict = verifier.check(task, state.artifacts)state.record("submit", verdict)state.done = verdict.passed # the verifier is the judge of terminationelse:try:result = sandbox.execute(action, timeout=30) # sandbox executionexcept RetryableError as e:result = retry_with_backoff(action, limit=3)except FatalError:state.record("fatal", str(e))raisestate.record(action, result) # append eventif state.step % 10 == 0:state.checkpoint() # periodic persistence, supports resumereturn state
4.6 Multi-Agent Collaboration
For complex engineering tasks, a single agent’s context is quickly filled by logs and intermediate artifacts. A more sensible approach is to split by role:
- Planning agent: decomposes the task and assigns subgoals;
- Execution agent: completes specific subtasks in an isolated context and returns only a summary of conclusions to the planning layer;
- Review agent: independently validates outputs as a second pair of eyes.
Agents communicate through a task message queue, and a scheduling layer manages dependencies and concurrency. Note that adding more agents amplifies the complexity of context synchronization and conflict merging — more is not always better.
5. Infrastructure: Supporting Large-Scale Joint Training and Inference
5.1 Reinforcement-Learning Training Framework
The biggest difference between reinforcement-learning training and supervised fine-tuning is that every iteration includes a “sample–reward–update” loop. This creates three engineering challenges:
- Sampling takes time: for long-context, multi-step agent tasks, a single trajectory can generate hundreds of thousands of tokens. Sampling often consumes most of the training time and becomes the throughput bottleneck.
- Sampling and training compete for resources: the sampling stage suits high-concurrency, low-latency inference deployments, while the training stage suits large-scale parallel compute — the two workloads have different hardware and parallelism needs.
- Policy and weight synchronization: sampling with old weights produces stale data, which hurts training stability.
The way to address this is to decouple inference from training:
- Deploy the sampling cluster independently, scale it elastically on demand, and cut redundant compute through cache reuse;
- Periodically synchronize weights between the training cluster and the sampling cluster;
- Use asynchronous sampling to raise overall throughput while keeping staleness under control.
At the same time, the sandbox execution cluster must handle massive concurrency of container instances, which requires high-concurrency capability across image distribution, dependency pre-installation, startup acceleration, network isolation, and resource recycling.
5.2 Training-Efficiency Optimization
Training a trillion-parameter model requires combined optimization across multiple dimensions of parallelism:
- Parallelism combinations: data parallelism, tensor parallelism, pipeline parallelism, expert parallelism, and more. Data parallelism is often paired with sharding (sharding optimizer states) to reduce per-GPU memory pressure.
- Compute–communication overlap: overlap gradient computation, communication, and parameter updates as much as possible to reduce communication waits.
- Mixed precision and checkpointing: mixed-precision training lowers memory and bandwidth overhead, while gradient checkpointing trades compute for memory.
- Elastic fault tolerance: at a scale of thousands of accelerators, hardware failures are the norm rather than the exception. Hot spares, fast failure detection, and automatic resume directly determine a cluster’s effective training time.
5.3 Environment-Quality Checks and Observability
The effectiveness of reinforcement learning depends heavily on environment quality. A flawed task or test case will continuously inject wrong signals into training. An environment-check platform needs to answer:
- Is the task reproducible, with dependency versions locked?
- Are the tests flaky — does the same input reliably return the same result?
- Is the task-difficulty distribution reasonable, without “dead zones” of tasks the model has fully mastered or cannot complete at all?
A supporting observability system is equally important and should at least cover:
- reward curves and pass rates per domain;
- sampling length and truncation rate;
- tool-call success rate and average number of steps;
- training throughput and cluster utilization.
The training side should also maintain an offline regression evaluation set and run scores on a fixed task set after each policy update, to prevent “gains here, losses there.”
5.4 Getting Elastic Capabilities in the Cloud
Not every team needs to build its own training and inference clusters. On cloud platforms such as Baidu AI Cloud, developers can combine elastic compute, container services, object storage, message queues, logging, and monitoring and alerting to fit their needs. In agent scenarios, object storage suits storing task artifacts and checkpoints, message queues decouple task distribution among multiple agents, and logging and monitoring trace the full execution chain of long tasks.
6. High-Speed Inference: Balancing Capability and Latency
The high-speed version shipping alongside the new model shows that inference speed is becoming a competitive dimension as important as model capability. For long-horizon agents, a single task can involve a hundred or more model calls, so single-step latency is amplified many times over — which makes high-speed inference especially valuable. Common techniques in the industry include:
- Speculative decoding: a lightweight draft model or small model guesses several tokens in a row, then the large model verifies them in parallel, accepting the matching prefix and resampling at the first point of divergence. It does not change the output distribution and suits structured outputs with strong regularities such as code and JSON.
- Operator and quantization optimization: operator fusion, low-precision inference, and sparsification reduce the per-token compute cost.
- Continuous batching and priority scheduling: dynamically batch different requests together, and give interactive requests higher priority in agent scenarios.
- Prefix caching: reuse the KV cache of the system prompt and tool definitions to reduce redundant compute.
- Cache-hit pricing: some model services bill cache-hit and cache-miss inputs separately, with cache hits typically priced well below misses.
This leads to a practical design principle: put stable content first and variable content last.
- Place stable content such as the system prompt, tool list, and domain knowledge base at the front, and keep the prefix verbatim-unchanged;
- Move volatile information such as timestamps and task IDs out of the prefix and into a variable section at the end;
- Update summaries by “appending a new summary” rather than “rewriting message history in place,” to avoid invalidating the cache.
7. Practices in Typical Scenarios
7.1 Intelligent Coding
Code is one of the most mature domains for reinforcement-learning post-training, because correctness can be verified objectively by tests. Long-horizon coding tasks often span dozens of files and last tens of minutes or more. A recommended workflow:
- Read before writing: have the agent first build a map of the repository structure and locate the relevant modules before making changes;
- Test-driven: run the existing tests first to ensure changes introduce no regressions;
- Small commits: commit a checkpoint as soon as each verifiable subgoal is complete;
- Failure retrospection: return test-failure information in structured form to drive the next round of fixes.
7.2 Financial Research
Financial-research tasks usually involve extensive data retrieval, report parsing, and cross-validation, with very high demands on accuracy and traceability. Key engineering points:
- Data-source tiering: distinguish authoritative disclosure documents, third-party data, and model inference, and annotate the source in the output;
- Numerical consistency checks: cross-compare the same metric across different sources and explicitly flag conflicts;
- Compliance statements: research conclusions should state their boundaries clearly and note that they do not constitute investment advice;
- Long-context summary chains: progressively compress historical material while preserving key numbers and conclusions, so details are not lost over a long chain.
7.3 3D Creation and Tool-Intensive Tasks
3D creation extends the agent’s capabilities from text to a professional toolchain. The model needs to understand scripting APIs for modeling, material and lighting parameters, and rendering output formats, and to pass intermediate artifacts (geometry models, textures, scene description files) between multiple tools. The characteristics of such tasks:
- Each operation is costly, so the model needs strong parameter understanding and planning ability;
- Feedback depends on render results, often requiring multiple “render–check–fix” iterations;
- Artifacts are large, so they are best passed through object storage rather than stuffed into the context.
8. Cost, Stability, and Governance
The cost structure of long-horizon agents is entirely different from ordinary dialogue:
- Costs accumulate: a single task may involve dozens of calls, with token consumption concentrated on the input side;
- Failed tasks also incur costs: you must set budget caps and stop-loss policies;
- Input and output are priced differently: the per-token price of input and output often differs by several times, so trimming prompts and constraining outputs directly affect the bill.
It is advisable to route models in tiers by task value: use the most capable, long-context model for high-value, high-difficulty tasks, and lightweight models or the high-speed version for high-volume simple tasks. At the same time, establish a closed loop of “offline evaluation → canary release → online monitoring → failure-sample feedback” so the model and the runtime framework keep iterating. For enterprise deployment, also define data-retention policies, tool-call auditing, and permission tiers, so that agent behavior stays manageable, controllable, and traceable.
Conclusion
From trillion parameters and million-token context to long-horizon agents, the center of gravity in the LLM race is shifting from “how strong is the model itself” to “how much work can the model reliably complete in a real environment.” Post-training reinforcement learning pushes capability from “able to talk” to “able to do”; long context provides the container that holds long tasks; the Harness packages the model into a recoverable, controllable execution body; and the training and inference infrastructure determines whether all of this can run at scale and at a reasonable cost. For developers, rather than waiting for a “stronger model,” it is better to start polishing your own Harness, verifiers, and evaluation systems now — these engineering assets are the true foundation for putting long-horizon agents into production.
