Million-Token Context LLMs: Engineering Practices and Cost Optimization
This article examines the engineering behind million-token context windows for large language models and explains why moving from a raw window size to usable context is the real challenge. It covers the gap between nominal window length and effective context, how parameter scale interacts with long context, and the core engineering constraints around attention computation and memory. It then treats prompt caching as the primary cost lever, walking through a five-item billing model with concrete cost examples and showing how cache invalidation happens when the token prefix changes. It also explains when paying for a high-speed tier is worthwhile and offers practical guidance for code and long-horizon agent tasks, factual accuracy and hallucination control, and safety trade-offs, closing with a pre-launch evaluation checklist.
1. Introduction: Context Length Has Become a New Competitive Dimension
In late October 2026, a major Chinese large-model vendor released its largest model to date, with a context window of 1 million tokens. In early November 2026, that model ranked first among Chinese models on the intelligence index of a well-known evaluation platform. The vendor also stated that the model has reached, or is close to, the level of the strongest closed-source models on coding and long-horizon agent tasks.
From a technical standpoint, this kind of progress shows that the focus of competition is shifting. The question used to be “can it answer a single turn accurately?” Now it is “can it read the full picture within an extremely long context, stay on course across many execution steps, and deliver reliably within a controllable cost budget?”
This article does not evaluate any specific product. Instead, it abstracts the technical elements worth borrowing from this kind of upgrade into general problems: the effectiveness and engineering constraints of long context, the cost mechanics of context caching, the selection logic for high-speed tiers, and the practical considerations for scenarios such as coding and long-horizon tasks, factual accuracy, and security.
2. From “Bigger Window” to “Usable Context”
2.1 Window Length Is Not Effective Context
One million tokens is roughly equivalent to thousands of document pages or a medium-sized code repository, but the actual benefit depends on three prerequisites:
- Recall: whether the model can accurately locate key information within a long context.
- Instruction following: whether instructions get diluted by long text.
- Consistency: whether early conclusions in multi-step reasoning are carried forward into later steps.
The common “needle-in-a-haystack” test already shows that most models recall information in the middle of the window noticeably worse than at the beginning and end. So from an engineering perspective, what matters more is the “effective context,” not the nominal upper limit.
2.2 How Parameter Scale and Long Context Work Together
Large parameter counts provide knowledge capacity, while long context provides the complete information a task requires. Only when the two are combined can they support complex, engineering-style tasks. At the same time, keep in mind:
- Scale is not everything. Some approaches use sparsification and mixture-of-experts structures so that a model does not have to activate all parameters to process a single token, which lowers the compute cost per token. When choosing a model, the guiding principle should be “task accuracy × cost per unit,” not parameter count alone.
- Capability gains are not uniform. The most noticeable change in this kind of upgrade is in coding and long-horizon tasks. The former depends on understanding program semantics; the latter tests the coherence of multi-step planning. Both rely heavily on whether contextual information is fully and correctly used.
- Third-party leaderboards need business context. For example, a terminal-restricted task evaluation measures the success rate of completing real tasks using only the command line, without the convenience of a network or graphical interface, which is very different from ordinary question answering. Such results can inform model selection, but business decisions should return to a self-built, scenario-based evaluation set.
3. Core Engineering Constraints of Long Context
3.1 Attention Computation and Memory Overhead
The compute cost of standard attention scales with the square of the sequence length. When the sequence grows from tens of thousands of tokens to the million-token scale, both the computation and memory usage in the prefill phase rise sharply.
Mainstream inference frameworks generally use optimizations such as paged KV-cache management and sparse or chunked attention to ease this problem. But as a caller, you still need to account for:
- The first ultra-long request has a noticeably longer wait time;
- With an ultra-long context, you should set an upper limit on output;
- For latency-sensitive paths, split requests or enable streaming output.
3.2 Adapting Prompt Engineering
In a long context, the model’s sensitivity to information is not uniform across positions. A more reliable approach is:
- State the task instructions, output format, and constraints once at the beginning and once at the end;
- Place long reference documents in the middle, labeled with sections or indices so the model can cite them;
- Use clear structured markers for key constraints so they are not buried in the body text.
3.3 Input and Output Are Strongly Asymmetric
Input prices are usually far lower than output prices. In mainstream pricing, the former is often a fraction, down to one-tenth, of the latter. There are two main reasons:
- The output phase is generally generated token by token through autoregression and cannot be fully parallelized like prefill, so it consumes more compute per unit;
- The output process occupies the request context until it finishes.
In addition, long-document scenarios often involve “long input, short output.” This means that the cost of a single request is determined mainly by the input, while the entire business bill depends on the output volume. The number of output tokens should be treated as a core control variable: it can be reduced with structured, concise output requirements, and a maximum output token count can be set to prevent generation from running out of control.
4. Context Caching: The Cost Lever of the Long-Context Era
4.1 How Cache Hits Reduce Latency
When vendors describe their intelligence index, they distinguish “whether caching is used,” which shows that context caching is already a foundational capability of inference services. The principle is: if the beginning of a new request matches the token sequence of an existing request, the inference service can directly reuse the previously computed key-value cache and skip recomputing those tokens, significantly reducing time to first token.
To be clear: caching only affects time to first token and does not speed up the generation of subsequent tokens. So for document analysis with “long input, short output,” the benefit of caching shows up mainly in wait time; for deep reasoning with “long input, long output,” the benefit shows up more on the bill.
4.2 Understanding the Four Layers of Billing Correctly
From the published price sheet, inference billing is split into basic tokens and context caching, with five pricing items in total:
| Billing item | Meaning | Relation to input price (standard) | Cost impact direction |
|---|---|---|---|
| Input | Input tokens that miss the cache | Baseline | Grows linearly with context length |
| Output | Tokens generated by the model | About 5× the input price | Main cost item |
| Cache hit | Input tokens that reuse an existing prefix | About 1/10 of the input price | More hits mean more savings |
| Cache write (~5 min) | Writing to a short-term cache | Same as the input price | Extra cost on first write |
| Cache write (~1 h) | Writing to a long-term cache | About 2× the input price | Premium for a longer reuse window |
Four points to keep in mind:
- The cache-hit price is far below the input price, making it the most important cost-reduction lever in long-context scenarios.
- Writing to cache is not free. A short-term write costs the same as input, and a long-term write costs about 2× the input price. If a piece of context will be used only once or twice, frequent cache writes actually increase cost.
- Cache writes are split into multiple time tiers to match different reuse cycles. For example, knowledge-base context may be queried repeatedly within tens of minutes, which suits a long-term cache; temporarily generated analysis material is fine with a short-term cache.
- Output and cache-hit prices do not change with the tier. The cache-hit price is the same for standard and high-speed tiers, both at 1/10 of the input price; the difference shows up only in input, output, and cache writes.
The standard pricing is: input ¥13, output ¥68, cache hit ¥1.3, short-term cache write ¥13, long-term cache write ¥26 (per million tokens). By this conversion, the cost of a cache hit is only 10% of the original input. Take a 100,000-character document (about 150,000 tokens) as an example:
- The cost of a full re-input each time is about ¥1.95;
- After writing to a short-term cache and repeating the question, each query costs only about ¥0.20;
- If 50 people ask about the same document in turn, the first writes the cache (¥1.95), and the remaining 49 are hits (about ¥9.56), for a total of about ¥11.5. Compared with ¥97.5 with no reuse at all, this saves about 88%.
4.3 The Cache Key Is the Token Prefix
A special point to note: context caching uses “model + token prefix” as the key. It compares from the first token position by position until the first difference appears; only the part before that difference can be a hit. So there are four engineering principles:
- Put stable content first and volatile content last. Static content such as system prompts, tool definitions, and output specifications goes first; volatile information such as timestamps, session IDs, and the current time should be placed later or removed from the prompt.
- Use only one tier per business flow. The standard and high-speed tiers are different model entries, so a different prefix means the cache cannot be reused. Mixing the two in task routing amounts to deliberately giving up cache benefits.
- Keep the prompt sequence stable. The ordering of the tool list, few-shot examples, and dynamically concatenated retrieval snippets should stay stable, to avoid the same content failing to hit because of a change in order.
- Choose a cache strategy by reuse cycle. Frequently reused, long-cycle context should preferentially be written to a long-term cache; low-frequency use can keep the default settings.
A typical counter-example: adding the current time at the beginning of the prompt, or regenerating the system prompt on every request. Even a one-character difference causes the entire context to be recomputed as a new prefix, and this waste is especially severe in long-context scenarios.
4.4 A Typical Cache-Invalidation Scenario
Suppose the full prompt of an intelligent coding tool looks like this:
[System prompt + tool definitions] → about 3,000 tokens (stable)[Repository code and dependency list] → about 120,000 tokens (semi-stable, changes with commits)[Current time: 2026-11-06 14:32:07] → about 20 tokens (changes every time)[User question] → different every time
Placing the timestamp in the third segment causes about 123,000 tokens to miss the cache. At standard pricing, this adds about ¥1.57 per request. Moving it after the user question lets the first two segments hit the cache reliably.
5. High-Speed Tier: Paying for Latency, and When It Is Worth It
This release also offers a high-speed version. The official description states that its price is about 2× the standard version, while the cache-hit price is the same as the standard version:
| Billing item | Standard | High-speed | Multiplier |
|---|---|---|---|
| Input | ¥13.00 / MTok | ¥26.00 / MTok | 2.0× |
| Output | ¥68.00 / MTok | ¥136.00 / MTok | 2.0× |
| Cache hit | ¥1.30 / MTok | ¥1.30 / MTok | 1.0× |
| Cache write (5 min) | ¥13.00 / MTok | ¥26.00 / MTok | 2.0× |
| Cache write (1 h) | ¥26.00 / MTok | ¥52.00 / MTok | 2.0× |
Whether it is worth using can be judged from three angles:
- Whether latency is central to the experience. Conversational applications, inline IDE completion, and agent loops are all constrained by time to first token. Take a long-horizon task requiring 12 tool calls as an example: if the standard version takes 1.5 seconds to first token per step and the high-speed version takes 0.6 seconds, you save about 11 seconds in waiting time alone. In such scenarios, the perceived improvement from paying 2× is worthwhile.
- The effect of output length. The cache-hit price does not change with the tier, and the high-speed premium is concentrated on input, output, and cache writes. Generation time depends mainly on output length; the longer the output, the more pronounced the acceleration benefit. So the high-speed tier is better suited to high-output scenarios such as deep analysis and long-form writing.
- Whether you can switch uniformly at the gateway layer. It is recommended to establish separate capacity and quotas for each tier and route uniformly through a business gateway, to avoid the configuration drift that comes from each application implementing its own logic.
A sensible default strategy is: the standard tier carries default traffic, and the high-speed tier is an option that can be enabled per scenario, for example only for online interaction and critical tasks, while batch preprocessing and offline evaluation continue to use the standard tier.
6. Practical Guidance for Typical Scenarios
6.1 Coding and Long-Horizon Tasks
The vendor states that these models can drive mainstream game engines and write scripts to operate 3D modeling and design software for parametric modeling. This shows that the model’s capability has extended from “generating code snippets” to “understanding a toolchain and completing tasks in a real environment.”
From a technical standpoint, this capability is made up of four parts:
- Tool knowledge: understanding of engine interfaces, scripting syntax, and command-line arguments;
- Context integration: judging requirements, existing code, the runtime environment, and error messages together in the same context;
- Execute-observe loop: run, read errors, correct, and retry;
- Long-horizon state management: keeping the goal from drifting across dozens or hundreds of steps.
The pseudocode below shows the typical structure of a long-horizon task loop:
"""Long-horizon task loop (pseudocode; interface names are illustrative only)"""# 1. Initialize once: system instructions + tool definitions form a stable prefix that improves cache hitsFROZEN_PREFIX = system_prompt() + json.dumps(tool_schemas, ensure_ascii=False)# 2. Total budget: step cap + context token cap + wall-clock cap, three layers of protectionMAX_STEPS, CONTEXT_BUDGET, WALL_CLOCK_LIMIT = 120, 900_000, 1800def run_long_horizon_task(goal: str, workspace: Sandbox):history = [] # Dynamic part: plans, observations, intermediate conclusionsused, deadline = 0, time.time() + WALL_CLOCK_LIMITwhile used < CONTEXT_BUDGET and time.time() < deadline:# 3. Stable prefix first, dynamic history after, to maximize the cache hit ratemessages = [FROZEN_PREFIX] + history + [format_goal(goal)]resp = chat(messages=messages, tools=tool_schemas, max_tokens=4096)used += resp.usage.prompt_tokens + resp.usage.completion_tokensif resp.is_final_answer():return resp.contentfor call in resp.tool_calls:# 4. All tool calls go through a sandbox: timeouts, resource limits, and logged tracesresult = workspace.execute(call, timeout=30)history.append(record(call, result)) # Keep only the summary + key error infoif result.failed:history.append(hint_from_error(result)) # Explicit feedback to guide self-correctionreturn escalate_or_fallback(goal, reason="budget_exhausted")
The accompanying engineering practices include:
- Externalize state: write plans, files already read, and commands already executed to external storage. Carry only a summary each round instead of the full history, which both controls context growth and makes recovery after interruption easier.
- Self-verification first: compilation, unit tests, rendering, or script execution are the most reliable signals and should take priority over “letting the model decide for itself whether it is done.”
- Fail fast: if the same error still is not resolved after several consecutive retries, switch approaches or escalate to human intervention.
- Hard budget constraints: set the step count, tokens, and wall-clock time as hard limits to prevent a long-horizon task from “drifting further and getting more expensive the longer it runs.”
When evaluating this kind of task, use the task completion rate under a given budget as the metric, rather than judging only whether the final answer text “looks right.”
6.2 Factual Accuracy and Hallucination Control
In internal stress tests, the vendor reduced the error rate of a single factual statement from about 23.4% in the previous generation to about 8.3%, a drop of more than 60%. At the same time, the vendor emphasized that the test deliberately focused on error-prone samples and that the error rate does not represent the overall level in everyday use.
For users, this has three implications:
- Look at how the metric is constructed. “Error rate per single statement” and “the share of answers containing at least one error” are metrics with different scopes. When comparing them, confirm that the test samples are consistent and the difficulty is comparable.
- Model capability cannot replace verification mechanisms. In high-risk scenarios such as financial modeling, industry research, and healthcare, you still need “retrieval augmentation + citation traceability + human review.” On the business side, you can record the source snippet corresponding to each conclusion to make it easy to locate and hold accountable.
- Make uncertainty explicit. Use prompts to require the model to distinguish between “explicitly supported by the document” and “inferred,” and add confidence or evidence fields in structured output.
6.3 Security and Capability Trade-offs
The vendor states that during the mid-training and reinforcement learning stages, it identified and removed data related to network offense and defense to reduce the risk of misuse. On its own security benchmark, the unfiltered version scored about 90.5% pass@3, while the final release scored about 81.0%.
This is a typical “security vs. capability” trade-off:
- Why filtering is needed. Offensive and defensive knowledge has dual use. Threat analysis for defenders requires this knowledge, but the same capability can also be used for attacks, so governance at the training-data level is a necessary precondition.
- What the cost is. Security hardening usually comes with some loss of capability. Metrics like pass@3 measure “whether at least one of several attempts succeeds,” reflecting the model’s capability ceiling rather than its average performance. After filtering, the ceiling drops somewhat, but the overall risk surface contracts significantly.
- How the business side can compensate. For defensive scenarios with genuine legitimate needs, you can provide a controlled toolchain and knowledge base within an enterprise intranet, supplement domain knowledge through retrieval augmentation, and combine this with access controls and audit trails, rather than simply opening up the model itself.
7. Pre-Launch Evaluation and Acceptance Checklist
- Build a scenario-based evaluation set: sample 100-300 cases from real business, covering typical input lengths, output lengths, and task types, with fixed prompts and sampling parameters to keep results reproducible.
- Design dedicated long-context tests: construct retrieval and reasoning tasks where “key information is buried in the middle of a 100,000-token document,” to verify recall and instruction following as the model approaches the window limit.
- Measure metrics separately: accuracy, time to first token, end-to-end latency, mean output tokens, cache hit rate, and cost per request. In long-context scenarios, pay special attention to the “effective hit rate,” meaning the share of tokens that actually save computation.
- Set up routing and fallback: use the standard tier as the default and switch to the high-speed tier per scenario; also keep backup models and degradation strategies so a single model does not become a single point of dependency.
- Ensure security and compliance: redact sensitive information before it enters the context, retain call logs and output traceability, and defend against prompt injection, especially malicious instructions coming from the documents being processed.
8. Conclusion
A million-token context and a large parameter scale bring more than just “the ability to read more.” What truly determines the effectiveness of a deployment is the engineering system built around the model:
- Use caching to turn repeated long context into a reusable asset;
- Use routing to find the balance point between cost and experience;
- Use an execute-observe loop to turn a single generation into reliable delivery;
- Use verification and validation mechanisms to cover factual risk;
- Use training-data governance to hold the security baseline.
For developers, it helps to ask three questions when choosing a model: How much effective context does this task need? Which prefixes can be reused? Which stages are worth paying for speed? Once these three points are clear, even the strongest model can be turned into real business value.
