Long Context and Long-Horizon AI Agents: Engineering Practices for Trillion-Parameter LLMs

    This article examines the engineering practices behind trillion-parameter large language models, focusing on two capability directions: long context and long-horizon agents. It explains why performance on long-context and long-horizon tasks has become central to LLM competition, then walks through practical techniques for effective context assembly (layering, compression, caching, and budgeting) and for building verifiable multi-step agent loops with sandboxing, structured outputs, and recovery controls. It also covers professional scenarios such as tool-driven modeling and financial research, hallucination classification and control, security and abuse mitigation, pricing and caching economics, and a practical checklist for evaluation, architecture, and model selection. Engineers will find concrete guidance and sample code for turning model capabilities into reliable, controllable, and cost-effective business value.

    1. Background: Two Directions of LLM Capability Growth

    Over the past two years, LLM capabilities have advanced along two main directions: “fitting more in,” meaning the number of tokens that can be processed in a single pass; and “going further,” meaning the ability to reason continuously and execute multi-step tasks. The former determines whether a model can digest an entire requirements document, a whole code repository, or a very long conversation history at once. The latter determines whether a model can independently complete complex tasks that span multiple turns and tools, without frequent human intervention.

    According to public reports, a model vendor released a trillion-parameter model on October 24, 2026, with officially stated support for a 1-million-token context. It subsequently ranked first among Chinese models on the intelligence index leaderboard of a third-party evaluation platform. The most useful aspect of this kind of release is not the specific ranking, but that it covers both long-context and long-horizon capabilities at the same time. Using the information disclosed for this class of models as a sample, this article distills a transferable technical methodology.

    2. Capability Baseline: Long Context, Code, and Long-Horizon Agents

    Long context mainly brings three benefits:

    • Simpler retrieval: Very large codebases, long documents, and multi-turn conversations can be fed directly as context, reducing the cost of designing and tuning retrieval pipelines;
    • Coherent reasoning chains: In multi-step tasks, intermediate results and constraints can be preserved in full, lowering the risk of “reasoning in one step and forgetting in the next”;
    • Carrying prompts and examples: Large numbers of tool definitions and reference examples can be placed in a single pass.

    Code and long-horizon agent capabilities are reflected in the model’s ability to execute multiple consecutive tool calls and complete, in a real environment, the full loop from understanding requirements, editing files, and running tests to fixing errors.

    According to data disclosed by the vendor (the table below is drawn from public material, has not been independently reproduced, and is provided only as a reference for capability magnitude):

    Capability Dimension Key Disclosed Points
    Terminal-restricted tasks In evaluations where operations can be performed only through tools and commands, a score of about 65.7, within 1 percentage point of the strongest closed-source model disclosed
    Long-horizon coding tasks A vendor-internal long-horizon coding benchmark score of 61.2, about 5 percentage points higher than the previous generation
    Parametric 3D modeling A tool-assisted modeling evaluation score of about 92.7, within about 3 percentage points of the two strongest closed-source models disclosed
    Office document and spreadsheet QA An external evaluation score of 64.4, described by the vendor as the current best result
    General evaluation leaderboard First among Chinese models on a third-party platform’s intelligence index leaderboard

    A common feature of these figures is that scores on long-horizon, structured-deliverable tasks tend to be closer to the current strongest closed-source models, indicating that “autonomous multi-step execution” has become the core battleground of large-parameter model competition.

    3. Long Context: From “Stuffing It In” to “Using It Well”

    Supporting a million-token context does not mean you can feed input without restraint. Engineering practice requires balancing three factors at once: effective utilization, latency, and cost.

    1. Effective context is shorter than the nominal length: Research (such as the “Lost in the Middle” phenomenon) shows that models often use information in the middle of the context less effectively than information at the beginning and end. Placing key constraints, output formats, and acceptance criteria at the end of the prompt, and ensuring the whole text is clearly structured, is the lowest-cost and fastest-to-implement optimization.

    2. Prefill latency and memory overhead rise sharply: The computational complexity of Transformer self-attention grows quadratically with sequence length, and the key-value cache (KV Cache) used during inference grows linearly with length. Million-token inputs often require several seconds or more of prefill time, which is unfriendly to real-time interactive scenarios.

    3. Long input does not mean negligible cost: Input tokens and output tokens are usually billed separately, and very large models have higher unit prices. Even if some platforms offer a clear discount for cache-hit input, uncached very long input can still become the main cost source.

    Based on this, the following practical recommendations can be given:

    • Assemble context in layers: Follow the order “system prompt (role, rules, output format) → long-term memory and domain knowledge → task background and history → current question,” so that the most critical instructions sit as close to the end as possible;
    • Compress rather than truncate: First produce a structured summary of very long material, retaining the file list, interface definitions, key code snippets, and error logs, while removing comments, whitespace, and duplicate content;
    • Combine long context with retrieval-augmented generation (RAG): Stable, repeatedly reused content such as system prompts, knowledge-base documents, and tool definitions is suitable for staying in context with caching enabled; massive, occasional material should be retrieved on demand and then injected;
    • Establish a context budget: For example, cap the total window at no more than 70% of the available limit, reserve room for model output and tool returns, and set a truncation length for individual tool results.

    The following sample code illustrates a “cache-first + budget-trimming” context assembly approach (it is pseudocode, and interface names should be confirmed against the relevant platform documentation):

    1. from dataclasses import dataclass
    2. @dataclass
    3. class ContextBudget:
    4. window: int = 1_000_000 # Context window supported by the model
    5. reserve: int = 16_000 # Reserved space for output
    6. ratio: float = 0.7 # Fraction of the window used for actual input
    7. @property
    8. def limit(self) -> int:
    9. return int(self.window * self.ratio) - self.reserve
    10. def assemble_context(system_prompt: str, knowledge: list[str],
    11. history: list[dict], question: str,
    12. budget: ContextBudget, tokenizer) -> list[dict]:
    13. """Assemble context with stable content first and volatile content later, trimming history"""
    14. pinned = [system_prompt, *knowledge] # Stable, cacheable content
    15. pinned_tokens = sum(tokenizer.count(t) for t in pinned)
    16. # Keep the most recent turns of history until the budget is exceeded
    17. kept, used = [], pinned_tokens + tokenizer.count(question)
    18. for msg in reversed(history):
    19. cost = tokenizer.count(msg["content"])
    20. if used + cost > budget.limit:
    21. break
    22. kept.append(msg)
    23. used += cost
    24. return [{"role": "system", "content": "\n\n".join(pinned)},
    25. *reversed(kept),
    26. {"role": "user", "content": question}]

    4. Code and Long-Horizon Agents: Turning Multi-Step Tasks into Verifiable Processes

    Terminal-restricted tasks refer to tasks that a model can complete only through tool calls, command execution, file reads and writes, and similar means, without directly “seeing” or modifying the target environment. Such evaluations closely resemble real development scenarios, such as automated operations, fault diagnosis, script writing, and refactoring. Their difficulty lies in error accumulation across steps: no matter how high the single-step success rate is, the overall success rate will drop markedly after dozens of consecutive steps.

    Long-horizon capability therefore becomes key to distinguishing a model’s practical value. A vendor-internal long-horizon coding benchmark score rose from 55.95 in the previous generation to 61.2, indicating that the focus of improvement has shifted from single-turn question answering to continuous execution. The following six points deserve attention in engineering practice:

    1. Sandboxing and least privilege: Execute code and commands in isolated containers; restrict network access, writable directories, and system calls; grant permissions dynamically as the task requires, avoiding giving the model access beyond the task scope.
    2. Structured results: Agree on a unified JSON structure for tool returns (status code, standard output, error message, structured data) to reduce the model’s misreading of natural-language logs.
    3. Context compression and trajectory summarization: When the trajectory exceeds the budget, compress completed steps into “goal—action—result” summaries while fully preserving the raw information of the most recent few steps.
    4. Failure recovery and timeout control: Set a maximum number of steps, per-step timeouts, and failure-retry strategies; escalate repeatedly failing tasks to human handling in a timely manner.
    5. Observability and replayability: Record the input, output, and token consumption of each step, to facilitate problem localization, regression evaluation, and cost accounting.
    6. Clear termination conditions: Use passing acceptance tests or meeting explicit completion conditions as the task-end criterion, avoiding the model “confidently wrapping up early.”

    The following sample code illustrates an agent loop with step and budget control:

    1. import json
    2. MAX_STEPS = 50
    3. MAX_TOOL_RESULT_CHARS = 8000
    4. def truncate(text: str, limit: int = MAX_TOOL_RESULT_CHARS) -> str:
    5. """Truncate overly long tool returns to avoid momentarily filling the context"""
    6. if len(text) <= limit:
    7. return text
    8. return text[:limit] + f"\n...[truncated, original {len(text)} chars]"
    9. def run_agent(llm_client, sandbox, task: str, max_steps: int = MAX_STEPS) -> dict:
    10. """Drive the model to complete a multi-step task in the sandbox, returning the trace and status"""
    11. messages = [{"role": "user", "content": task}]
    12. for step in range(1, max_steps + 1):
    13. reply = llm_client.chat(messages=messages, tools=sandbox.tool_specs)
    14. # The model no longer requests tool calls, so the task is considered finished
    15. if not reply.tool_calls:
    16. return {"status": "done", "steps": step, "result": reply.text}
    17. messages.append(reply.message)
    18. for call in reply.tool_calls:
    19. try:
    20. result = sandbox.execute(call.name, call.arguments, timeout=120)
    21. except Exception as exc:
    22. # Feed exception information back to the model so it can adjust its strategy
    23. result = {"ok": False, "error": str(exc)}
    24. messages.append({
    25. "role": "tool",
    26. "name": call.name,
    27. "content": truncate(json.dumps(result, ensure_ascii=False)),
    28. })
    29. return {"status": "max_steps_reached", "steps": max_steps, "result": None}

    5. Professional Scenarios: Tool Scripts and Financial Modeling

    Beyond general coding ability, long-context models are increasingly valuable in operating specialized software and delivering industry-specific results.

    1. Scripting specialized software: A model can call the scene and resource interfaces of mainstream game engines, and can also drive 3D modeling, rendering, and computer-aided design software through scripts to complete parametric modeling. For example, generating a mechanical part with dimension parameters via a script; changing the parameters automatically rebuilds the model. Evaluations of such tasks usually need to be done with tools, and disclosed data show that the relevant scores are within about 3 percentage points of the strongest closed-source models.

    2. Financial modeling and research reports: Financial models, investment analysis, and industry research are typical “long-document input + structured output” tasks with very high demands on computational accuracy and data traceability. Long context lets the model read financial reports, announcements, and historical research reports at the same time; long-horizon capability supports the full chain of “data extraction — assumption setting — model construction — sensitivity analysis — conclusion writing.”

    Three points need attention when putting such scenarios into practice:

    • Externalize numerical computation: Formulas and numerical results are computed by programs or modeling tools; the model is responsible for structural design and logical connection;
    • Traceable citations: Each key data point is annotated with its source section or file location, for easy review;
    • Human final review: For research conclusions intended for external release, retain compliance review and human sign-off steps.

    6. Factuality: Classifying and Controlling Hallucinations

    Factual accuracy is a prerequisite for large models to enter production and financial scenarios. Hallucinations can be divided into three types:

    • Factual hallucination: Stating information that does not match objective facts;
    • Faithfulness hallucination: Output that deviates from the given material, such as misinterpreting a document or omitting key terms;
    • Citation hallucination: Citing non-existent literature, data, or sources.

    A vendor’s internal stress test showed that the error rate for individual factual statements in its new model dropped from 23.4% in the previous generation to 8.3%, and the proportion of answers containing at least one factual error dropped to about 42.4% of the previous generation. The vendor also emphasized that the test deliberately focused on error-prone cases, and that the error rate does not represent the overall level of everyday use. This point is significant for engineering practice:

    • Stress tests measure the “worst case” and should not be equated directly with production error rates;
    • Actual performance should be judged by evaluation sets close to the business, and metrics should be tracked continuously after version updates.

    Common control measures include:

    • Retrieval-augmented generation: Using a traceable knowledge base as the source of facts;
    • Structured output constraints: Validating field types, value ranges, and required fields;
    • Citation checking: Verifying the consistency of each citation against the original text;
    • Self-checking and cross-validation: Performing a second check or multi-model comparison on key conclusions;
    • Confidence prompting: Requiring the model to explicitly flag uncertain information in the prompt, rather than forcing an answer.

    7. Security and Abuse Risks: Data Filtering and Capability Trade-offs

    While improving capabilities, large-parameter models also bring abuse risks, with cyber attack and defense being a typical area. According to the vendor, the model identified and removed data related to cyber attack and defense during both the mid-training and reinforcement learning stages. On the vendor’s internal hard-code evaluation, the unfiltered version solved 90.5% of problems at pass@3, while the final release version scored 81.0%. This shows that safety governance is not “cost-free”: filtering data affects performance on certain high-risk tasks to some extent, but the benefit of reducing abuse risk is equally significant.

    pass@3 means allowing 3 independent samples and counting a problem as solved if 1 passes; it is a common metric for measuring code-generation ability. Beyond training-stage governance, the enterprise side should also build defense in depth:

    • Input side: Prompt-injection detection, sensitive-data identification, and redaction;
    • Output side: High-risk content blocking and human review;
    • Permission side: Least-privilege access, operation auditing, and record-keeping;
    • Data side: Distinguishing data tiers that can be uploaded, need redaction, or must not be uploaded, and following compliance requirements such as data residency.

    8. Cost and Pricing: Three Keys to Understanding the Price List

    According to public material, the new model’s price has been lowered compared with the previous generation; the standard version’s cache-write (5 minutes) unit price is on par with the base input price, cache write (1 hour) is about twice the base input price, and the cache-hit price stays low; the high-speed version’s input and output prices are about twice those of the standard version, with the cache-hit price on par with the standard version. This structure conveys three signals:

    1. Output is “more expensive” than input: Output tokens are generated autoregressively token by token, usually billed at several times the input price. Compressing redundant output and agreeing on concise formats often reduce costs more significantly than reducing input.
    2. Caching is a key lever for long-context scenarios: The cache-hit price is usually only about one-tenth of the input price, while cache writes incur an additional fee. Stable content such as system prompts, tool definitions, and knowledge bases is suitable for long-term caching; one-off long documents, if repeatedly written to cache, may instead increase costs because of more writes than reads.
    3. The high-speed version is a trade-off between latency and cost: The high-speed version is better suited to latency-sensitive scenarios such as online customer service and real-time interactive coding; tasks such as batch data processing and offline report generation are better handled with the standard version.

    Common optimization strategies include:

    • Placing stable prefixes first so more content hits the cache;
    • Summarizing long documents before injection;
    • Merging batch requests for combined submission;
    • Building a cost dashboard to track token consumption and cost by business line;
    • Adopting tiered model routing, where simple tasks are handled by lighter models and complex tasks are escalated to the large-parameter model.

    The following sample code estimates monthly cost (prices are illustrative; actual prices follow the pricing of the platform you use):

    1. # Prices are illustrative (per 1M tokens); actual prices follow the platform you use
    2. PRICE = {
    3. "standard": {"in": 13.0, "out": 68.0, "cache_hit": 1.3},
    4. "highspeed": {"in": 26.0, "out": 136.0, "cache_hit": 1.3},
    5. }
    6. def estimate_monthly_cost(daily_requests: int, in_tokens: int, out_tokens: int,
    7. cache_hit_ratio: float, tier: str = "standard") -> dict:
    8. p = PRICE[tier]
    9. hit = in_tokens * cache_hit_ratio
    10. miss = in_tokens - hit
    11. # Unit: cost per 1M tokens; daily requests * tokens per request / 1e6 * 30 days
    12. daily_in = (miss * p["in"] + hit * p["cache_hit"]) / 1e6
    13. daily_out = out_tokens * p["out"] / 1e6
    14. daily = (daily_in + daily_out) * daily_requests
    15. return {"daily_cost": round(daily, 2), "monthly_cost": round(daily * 30, 2)}
    16. if __name__ == "__main__":
    17. # Example: 100,000 requests per day, average 8,000 input tokens, 70% cache hit
    18. print(estimate_monthly_cost(100_000, 8_000, 1_000, cache_hit_ratio=0.7))
    19. # The same load using the high-speed version
    20. print(estimate_monthly_cost(100_000, 8_000, 1_000, 0.7, tier="highspeed"))

    9. Implementation Checklist: Evaluation, Architecture, and Selection

    To turn LLM capabilities into real business value, you need to advance together on three levels: evaluation, architecture, and selection.

    Evaluation level

    • Build your own evaluation set, covering real business tasks, edge cases, and adversarial samples;
    • For long-horizon tasks, use end-to-end task completion rate, average number of steps, and number of human interventions as core metrics, rather than only looking at single-step accuracy;
    • Distinguish pass@1 from pass@k, and clarify the business’s stability requirements;
    • Track the error rate for factual tasks separately, and annotate whether retrieval is allowed;
    • Run regression evaluation after version updates to confirm that capability gains have not come at the cost of safety or stability.

    Architecture level

    • Enable caching and layered assembly for long-context scenarios, and strictly control the context budget;
    • For agent tasks, adopt a “plan—execute—verify—feedback” loop, and set a maximum number of steps and a failure-exit strategy;
    • Follow the least-privilege principle for tool and data access;
    • Build a monitoring and alerting system covering token usage, cost, latency, error rate, and human-takeover rate; on Baidu AI Cloud, you can leverage cloud products such as log services and monitoring alerts to achieve full-chain observability;
    • Integrate model APIs as services, using a gateway to handle routing, rate limiting, auditing, and fallback in a unified way.

    Selection level

    You can refer to the table below to compare candidate models across multiple dimensions:

    Dimension Key Question Validation Method
    Effective context Is recall of information in the middle of long documents reliable? Long-document QA and multi-hop retrieval tests
    Long-horizon execution What is the end-to-end completion rate for multi-step tasks? Sandboxed rehearsal with real tasks
    Factual accuracy Is the error rate controllable in error-prone scenarios? Business fact-checking evaluation set
    Security Can sensitive and high-risk content be effectively blocked? Adversarial testing and red-team exercises
    Cost What is the actual unit price after cache hits? Estimate the monthly bill using real traffic
    Latency Can it meet the response requirements of interactive scenarios? First-token latency and throughput stress tests

    Overall, the value of large-parameter models lies not in a single leaderboard ranking, but in whether they can complete end-to-end tasks in real business pipelines stably, controllably, and economically. Building engineering capabilities around long context, long-horizon agents, factuality, and safety governance, and establishing mechanisms for continuous evaluation and cost monitoring, is the key path to turning model capabilities into productivity.