Million-Token Context and Long-Horizon Agents: How LLMs Move from Answering Questions to Completing Tasks
Competition among large language models is shifting from single-turn question answering to end-to-end task delivery, and two technical signals define that shift: context windows growing from tens of thousands to a million tokens, and the rise of long-horizon agents. This article explains how the two relate, how to tell stated context length from effective context, how long-horizon tasks are actually evaluated, and what all of it costs in memory, latency, and money. It covers KV cache math and optimization techniques, context and memory management patterns for agents, tool-driven workflows for code, 3D, and document work, hallucination suppression, the capability cost of safety filtering, caching-based pricing structures, and a reference enterprise architecture with an evaluation path from PoC to production.
In recent years, competition in large language model capability has moved from “single-turn question answering” toward “long-task delivery.” Two developments stand out as markers of that shift. Context windows have expanded from the tens-of-thousands-of-tokens range into the million-token range. And the “long-horizon agent” has become a shared focus for vendors and researchers alike.
The two are not isolated technical points. Context determines how much information a model can take in at a single pass; agents determine how long a model can keep working without interruption. The former is the physical foundation of the latter, and the latter is the vehicle through which the former’s value is fully realized.
For developers and enterprises, the interesting question is not the headline number on the context window. It is whether:
- a long window reliably converts into effective information use;
- complex tasks stay correct across a long chain of steps;
- the cost of this capability in real business scenarios stays controllable.
This article is organized around four themes: how the capability works, how to evaluate it, how to engineer for it, and how to govern its cost.
One clarification up front: this article does not target any specific model. Capability descriptions cited here come from vendors’ publicly released materials and are used only as samples for observing industry trends. For actual figures, refer to the latest official information from each model provider.
1. Million-Token Context: Length, Effectiveness, and Cost
1.1 Stated length is not effective length
A stated context length only tells you how many tokens a model can accept at maximum. What actually determines business outcomes is the effective context: the model’s ability to accurately retrieve, connect, and apply key information inside a long input.
Academics typically use the Needle-in-a-Haystack test to probe long-context retrieval. A piece of key information is inserted at a specific position in a long text, and the model is then asked about it. In practice, retrieval ability is not uniform across positions. Many models exhibit the “Lost in the Middle” effect: information at the beginning and end of the context is used more reliably, while information in the middle is more easily overlooked.
Enterprises should also watch for a second kind of distortion: models that pass the simplest literal retrieval tests but fail on real long-document auditing or cross-file refactoring work. For that reason, context evaluation should cover at least three layers:
- Retrieval: can the model locate a single piece of key information precisely?
- Aggregation: can it draw conclusions from information scattered across multiple locations?
- Reasoning: can it perform multi-hop reasoning over cross-document information, and handle conflicts and priority ordering?
1.2 Key techniques on the training side
Mainstream industry practice falls into three categories:
- Position encoding extrapolation and scaling: for example, adjusting the base frequency or scaling factor of rotary position embeddings so the model retains positional discrimination over longer sequences;
- Continued training on long sequences: further pre-training or fine-tuning on long samples, so the model has genuinely “seen” long contexts rather than only supporting them in theory;
- Long-context instruction data: constructing samples for tasks such as long-document question answering and long-code editing, strengthening instruction-following ability when the input is long.
According to the vendor’s public introduction, the latest flagship model from a Chinese model developer has a parameter count of roughly 3 trillion and a context window of 1 million tokens. The vendor identifies code and long-horizon agents as the primary areas of upgrade, and states that the model reaches or approaches the level of the strongest currently available closed-source models on code, agent, and knowledge benchmarks. In one evaluation of real-world terminal-constrained tasks, for instance, the model scored about 65.7%, above 58.2% for one closed-source model and within 0.7 percentage points of 66.4% for another. This indicates that Chinese models now have the capability to compete on long-task dimensions with internationally leading models.
1.3 The engineering cost of long context
The cost of long context concentrates in two areas: GPU memory and latency.
In autoregressive generation, the key/value vectors for every token must be cached so that subsequent tokens can reuse them during attention computation. This is the KV Cache. Its memory footprint can be roughly estimated as:
KV cache memory ≈ 2 × sequence length × layers × KV heads × head dim × bytes per value
With 60 layers, 8 KV heads, a head dimension of 128, and FP16 precision, each token needs roughly 240 KB of KV cache. At a context length of 1 million tokens, the KV Cache alone approaches 240 GB — before counting model weights, activations, and framework overhead.
Common optimization techniques include:
- Grouped-query attention (GQA) / multi-query attention (MQA), which reduce the number of KV heads;
- KV Cache quantization, which lowers the precision of each cached entry;
- Paged memory management, which reduces fragmentation and duplicate allocation;
- Prefix cache reuse, which lets multiple requests share the same KV prefix;
- Sparse attention, linear attention, or hybrid architectures, which lower the compute required for long sequences.
Together, these techniques determine whether a million-token context can actually be afforded in practice.
2. Long-Horizon Agents: From Answering to Doing
2.1 Where long-horizon agents are hard
A long-horizon agent is a system that autonomously executes multi-step, cross-tool tasks over an extended period with minimal human intervention. The difficulty is not in any single reasoning step. It is that errors accumulate along the chain. The main challenges are four:
- Planning and decomposition: breaking a vague goal into verifiable subtasks and handling the dependencies between them;
- Tool use: function calls, command-line execution, script execution — parameter errors get amplified at each subsequent step;
- State and memory management: context is finite, so the system must distinguish information required for the current task from information that can be written out and retrieved on demand;
- Error recovery and termination: recognizing failure, retrying or rolling back, and stopping promptly once the task is genuinely complete.
2.2 Trustworthy evaluation of long-horizon capability
An agent’s capability cannot be judged from what the model reports about itself. The industry commonly uses controlled environments with automatically checkable outcomes, such as terminal-constrained task evaluations built on real terminals:
- Network access is restricted and the toolset is fixed, forcing the model to complete the operation through its own reasoning;
- Pass rate and step completion serve as objective metrics;
- pass@k (the proportion of k independent attempts in which at least one succeeds) measures stability.
Combining publicly available data, three observations can be drawn:
- Leading models cluster around roughly 60% on real terminal-constrained tasks, with gaps between them often only a few percentage points; “matches or exceeds the strongest closed-source model” has become a common framing in leading-model release messaging;
- Cross-generational gains often show up in long-horizon consistency: one vendor states its new model scored about 61.2% on an internal long-horizon code evaluation, versus about 55.95% for the previous generation;
- A single successful run is not the same as reliable delivery. Long-horizon tasks must be measured with repeated sampling and layered metrics together.
2.3 Context management for long-horizon tasks
An agent is fundamentally a long-context consumer. The observation from each step, the command output, and every intermediate artifact enters the context. The longer the task, the faster the context grows. Three common management strategies:
- Compaction and summarization: produce a structured summary of historical steps, retaining only the goal, completed items, remaining items, and key constraints;
- Externalized memory: write code snippets, documents, and logs to external storage, keeping only an index and paths in context, retrieving content when needed;
- Subtask isolation: delegate independently completable work to sub-agents, and merge only conclusions and artifacts back into the main agent.
A simplified long-horizon agent loop follows. It highlights the context budget and the timing of compaction:
def run_long_horizon_agent(goal, tools, max_steps=50, context_budget=800_000):"""Long-horizon agent framework constrained by a context budget (pseudocode)"""state = {"goal": goal, "todo": [goal], "done": [], "notes": ""}history = [] # stores (action, observation) pairs for each stepfor step in range(max_steps):prompt = assemble_prompt(goal, state, tools, history) # build the current promptaction = model.generate(prompt) # model emits the next actionif action.type == "finish":return state # done: return artifacts and execution recordresult = execute(action, tools) # run in a sandbox, keep the full loghistory.append((action, result))state["notes"] += summarize(result) # distill key conclusions into notes# when the context exceeds budget, compact history instead of truncating itif estimate_tokens(prompt) > context_budget:history = compact_history(history, keep_last_n=3)state["todo"] = replan(state) # replan remaining work based on notesraise RuntimeError("Max steps reached without completion; escalate to human review")
In practice, agent applications commonly adopt a separated-memory architecture to cope with long-horizon tasks:
- Short-term memory: the full message list of the current session;
- Working memory: the tool results required by the current subtask;
- Long-term memory: post-session summaries, user preferences, and historical conclusions, stored externally and retrieved on demand.
With clear division of labor among the three, long chains of work can be supported within a finite context.
3. Multimodal Tool Use and Vertical Workflows
Much of a long-horizon agent’s value depends on how many external tools it can actually operate.
3.1 Game engine scripting
Mainstream game engines such as Unity, Unreal Engine, and Godot all expose scripting interfaces that can be used to generate scenes in bulk, set object properties, and export assets. A model can write and run these scripts to complete repetitive work that engineers would otherwise do by hand — for example, bulk-assembling levels, enforcing consistent naming conventions, or automatically generating light probes.
3.2 Parametric 3D modeling
3D modeling software such as Blender and CAD tools such as AutoCAD support scripting interfaces including Python. With scripts, parametric modeling becomes possible: adjusting parameters to drive changes in model structure. According to the vendor’s public introduction, the Chinese model described above scored about 92.7% on parametric 3D modeling with tools, compared with 96.2% for one closed-source model and 95.9% for another. This suggests that the combination of “the model generates the script, the tool executes and validates it” is an important path toward making 3D generation practically deployable.
3.3 Office documents and financial workflows
According to the vendor’s public introduction, on the external office-document question-answering benchmark OfficeQA Pro v2 the model scored about 64.4, described by the vendor as the best result at the time. In the financial domain, the model can deliver end-to-end workflows including financial modeling, investment analysis, and industry research reports.
These scenarios share common characteristics:
- Input is heterogeneous material spanning multiple formats and sources;
- Output must be traceable and reviewable;
- A single generation cannot guarantee correctness, so multiple rounds of iteration and human verification are required.
For this reason, packaging “model capability” into a pipeline of document parsing → information extraction → computation and modeling → result validation → final draft is more reliable than pursuing single-pass generation quality alone.
4. Factuality and Hallucination Suppression
Failures in long-horizon tasks are often not caused by insufficient reasoning ability. They are caused by factual errors being amplified. A single wrong API parameter or a misremembered metric definition can produce cascading deviations in later steps.
The fact types where errors occur most readily include:
- low-frequency entities and proper names of people and organizations;
- exact numbers, units, and measurement definitions;
- time-sensitive dynamic information;
- easily confused near-synonymous concepts;
- details requiring multi-hop association.
4.1 Internal stress tests on error-prone facts
One vendor disclosed results from its internal stress test, Kimi Hallu Bench Hard, in its official release:
- the error rate for individual factual statements fell from 23.4% in the previous generation to 8.3%;
- the proportion of responses containing at least one factual error was only about 42.4% of the previous generation’s figure;
- the vendor also emphasized that the test deliberately focuses on error-prone cases, and that the error rate does not represent the overall level of everyday usage.
Two takeaways follow from this data:
- Targeted optimization of error-prone scenarios is more effective than broadly increasing “knowledge volume”;
- Metrics must be interpreted in light of sample composition. A high error rate on an error-prone set does not mean a product is unusable — but neither should it be concealed.
4.2 Layered suppression strategies
Hallucination suppression requires coordination across training and engineering:
- Training layer: introduce factuality data and verifiable rewards, for example requiring answers to be consistent with retrieved evidence and numeric values to be checkable by tools;
- Inference layer: use retrieval-augmented generation (RAG) to inject external knowledge into the context and require cited sources in the output; hand computational portions to code execution or calculator tools;
- Output layer: explicitly attach confidence to uncertain content, and allow the model to abstain or ask clarifying questions.
5. The Trade-off Between Safety Filtering and Capability
Knowledge in areas such as network offense and defense and security vulnerabilities is inherently dual-use: it can serve defense, hardening, and incident response, and it can also be misused for attacks. Mainstream model providers typically identify, filter, or down-weight high-risk data during pre-training and post-training.
According to the vendor’s public introduction, the Chinese model described above had network offense-and-defense-related data identified and removed during both the mid-training and reinforcement learning stages, in order to reduce the risk of misuse.
The capability cost of this approach deserves attention. On the vendor’s internal code security benchmark xdev-bench-hard, the reported figures are:
- about 90.5% pass@3 for the unfiltered version;
- about 81.0% for the final released version, a difference of roughly 9.5 percentage points.
This data makes the point that safety governance is not zero-cost. Enterprises need an explicit decision between capability ceiling and compliance floor:
- In high-compliance scenarios (finance, government, healthcare), prefer model versions with stricter filtering and more complete auditing;
- Teams that need security research capability should operate under isolation, least privilege, and full auditing, with human review in the loop;
- Filtering policies themselves should be part of the evaluation system, with regular regression testing to prevent policy drift.
6. Context Caching, Pricing Models, and Cost Governance
6.1 A four-part pricing structure
Long contexts and long-horizon tasks inherently mean high token consumption. Using one vendor’s published pricing structure as an example, mainstream model services typically have four price categories:
- Base input: the prompt sent with each request;
- Base output: the content generated by the model;
- Cache hit: the portion of input served from a prefix cache, priced well below base input;
- Cache write: the portion of input first written to the cache, priced according to the cache’s lifetime (for example 5 minutes or 1 hour).
| Line item | Standard (illustrative) | High-speed (illustrative) | Notes |
|---|---|---|---|
| Input | 13.00 | 26.00 | Input tokens that miss the cache |
| Output | 68.00 | 136.00 | Generated tokens, usually the highest unit price |
| Cache hit | 1.30 | 1.30 | Roughly 1/10 of the input price |
| Cache write (5 min) | 13.00 | 26.00 | Same as input; suited to short-term reuse |
| Cache write (1 hour) | 26.00 | 52.00 | Roughly 2× the input price; suited to long-cycle reuse |
Note: units are CNY per million tokens, and the figures above are structural illustrations only. Actual prices, cache lifetimes, and cache-hit rounding rules should be taken from each service provider’s latest announcements.
In addition, many providers offer a high-speed tier whose input and output prices are roughly 2× the standard tier, typically in exchange for higher throughput and lower latency. Some vendors also lower prices across generations. In other words, per-token cost is itself on a continuing downward trend.
6.2 Four cost optimization principles
- Structured prompts: place stable content such as system instructions, tool definitions, and domain knowledge at the front of the prompt, and request-specific user input at the end, maximizing cache hit rates;
- Retrieve on demand: replace full injection with retrieval — chunk long documents and retrieve relevant portions instead of filling the window at once;
- Tiered routing: send simple tasks to lightweight models and complex long-horizon tasks to flagship models;
- Make usage measurable: track token consumption by business dimension to identify high-cost call chains.
7. Enterprise Architecture and Evaluation Systems
7.1 A reference layered architecture
- Access layer: a unified API gateway handling authentication, rate limiting, quotas, and auditing;
- Model service layer: wraps calls to different models and supports multi-model routing, retries, and fallback;
- Knowledge and retrieval layer: document parsing plus hybrid recall across vector and keyword retrieval;
- Agent execution layer: runs tools and scripts inside isolated containers with limits on network, filesystem, and resource quotas;
- Data layer: object storage for source documents and artifacts, a message queue to decouple long tasks, and a relational database for structured results;
- Observability layer: a logging service collects call chains and tool execution records, with monitoring and alerting covering error rates, latency, and token consumption.
7.2 Scenario-specific recommendations
- Intelligent coding: use the code repository as the knowledge source and terminal-constrained automated tests as the check, focusing on multi-file changes and test pass rates;
- 3D and industrial software automation: center on script generation, emphasizing parametric behavior, repeatability, and version management;
- Finance and office documents: build on a parse → extract → compute → review pipeline, with key numbers traceable to their original sources;
- Customer support and knowledge Q&A: prioritize context caching to reduce multi-turn conversation costs, and add a factuality validation step.
7.3 Four gates from PoC to production
- Scenario selection: prioritize tasks with long chains, automatic verifiability, and controllable failure cost;
- Offline evaluation: build an enterprise-specific evaluation set covering retrieval, aggregation, reasoning, and tool use, and use pass@k to measure stability;
- Gradual rollout: release to a small traffic share, compare against a human baseline, and monitor hallucination rate and human-takeover rate;
- Continuous improvement: feed production failure samples back into the evaluation set and prompts, closing the loop.
8. Conclusion
Million-token context and long-horizon agents mark a transition in large models from answering questions to completing tasks. For enterprises, three capabilities need to be built:
- Evaluation capability: distinguishing stated length from effective length, and single-run success from reliable delivery;
- Engineering capability: orchestrating long chains of work under constraints of context budget, tool sandboxes, and cost;
- Governance capability: balancing factuality, security, and measurability.
The technology will keep evolving, but the principle of measuring model value by verifiable task completion will not change. Building an evaluation system and an engineering foundation around your own business is the key to converting large model capability into productivity.
