Long-Horizon AI Agents in the Flagship Model Era: Engineering Leaps, Cost Control, and Security Balance
This article uses a recent flagship LLM release as a lens to examine the engineering realities of long-horizon AI agents. It works through three themes—the shift in post-training toward reinforcement learning with verifiable rewards (RLVR) and "environment engineering," the restructuring of inference systems to balance long context, throughput, and latency, and the redistribution of security responsibility once model weights are opened—and turns each into actionable practice. Readers will find concrete guidance on controlling agent costs (stable prefixes, layered context, budget circuit breakers), securing terminal and multi-agent deployments (sandboxing, least privilege, human approval), speeding up output, reading agent benchmarks correctly, and selecting models across capability, speed, cost, and controllability.
Introduction: One Flagship Release, Three Engineering Questions
Late in October, a Chinese large-model team released a new-generation flagship model. According to its public materials, it is the most capable trillion-parameter sparse (MoE) model the team has built to date. It supports a million-token context and puts particular emphasis on code generation, 3D content creation, financial research, and long-horizon agent (Agent) capabilities. The team also states that the model now approaches the strongest current closed-source models on code, agent, and knowledge benchmarks, and that full weights are planned to open in early November. A companion high-speed version lifts output speed by roughly 2–3x while keeping intelligence basically unchanged. The new model already covers the web, app, desktop, and coding product lines, and is delivered as a managed agent service—packaging the execution framework that keeps agents running over long periods as cloud infrastructure for developers and enterprises.
Community discussion has split into two camps: one worried about uneven capability and verbose answers, the other noticing that the high-speed version’s token quota “burns out in ten minutes.”
Setting aside the specific version and model name, this upgrade can be distilled into three engineering threads with general value for developers:
- A shift in post-training focus: from “making the model answer better” to “teaching the model to finish long tasks inside verifiable rewards”;
- Restructuring of the inference system: long context, high throughput, and low latency constrain one another, driving systematic optimizations such as prefix reuse, speculative decoding, and context engineering;
- A re-drawing of responsibility boundaries: once weights are public, the center of gravity for security and risk governance expands from the model side to the deployment and platform sides.
This article follows these three threads and offers engineering practices you can put to work directly.
1. First, Four Foundational Concepts
Before discussing capability diffusion and cost accounting, it helps to separate a few concepts that are often used interchangeably.
- Open weights ≠ open source: the former publishes the trained parameter files, usually without the full training data, data mixture, or training code; the latter generally also includes a reproducible training pipeline and code.
- Post-training: shaping model behavior on top of pre-training through supervised fine-tuning, preference alignment, and reinforcement learning. It is the key step from “general capability” to “domain productivity,” and it is where most of the effort in this release went.
- Context window ≠ effective memory: the window determines how many tokens a single request can hold at most, while effective memory depends on the model’s ability to retrieve and use long context. Beyond the model’s effective working range, key information may be ignored—the phenomenon commonly called “lost in the middle.”
- Agent ≠ single-turn Q&A: an Agent is a system of “model + tools + execution environment + control logic.” The execution framework (often called a Harness in the industry) handles tool orchestration, context maintenance, retries and recovery, permissions, and auditing, and determines whether an Agent can keep working 24/7.
Everything that follows assumes the Agent form, because long-horizon tasks are exactly where security, cost, and evaluation problems surface together.
2. Post-Training Paradigm: From Preference Alignment to Verifiable Rewards
2.1 Why RL becomes the center of post-training
Traditional post-training relies mostly on human-labeled preference data, aligning output style through methods such as reinforcement learning from human feedback (RLHF), and is limited by labeling scale and subjective judgment. When a task’s goal can be verified programmatically—whether code passes tests, whether a retrieval result answers the question, whether a ticket field passes validation—you can build reinforcement learning with verifiable rewards (RLVR). The verifier emits an objective reward signal directly, so training scale is no longer bounded by the throughput of human labeling but by how many verifiable tasks you can construct.
2.2 Post-training is becoming “environment engineering”
Under this paradigm, the subject of post-training is no longer only data labeling and loss-function design, but the executable environment itself. A mature training environment needs at least four kinds of components:
- Task generators: abstract task templates from real needs, and stratify them by difficulty and distribution;
- Verifiers: run validation in an isolated environment and emit stable, reproducible reward signals;
- Execution infrastructure: containerized sandboxes that support large-scale parallel sampling and evaluation;
- Scheduling and health checks: queuing, rate limiting, and failure retries, plus weeding out corrupted images, stale tests, and non-reproducible tasks.
Only when the environment is “stable, decidable, and reproducible” can reinforcement learning converge reliably. Spreading scaled-up post-training compute across hundreds of downstream domains is essentially building hundreds or thousands of such environments in parallel.
2.3 RL difficulties for long-horizon tasks and how to handle them
A long-horizon trajectory can run dozens of turns, and RL faces three difficulties:
- Sparse rewards: success appears only at the task’s endpoint;
- Credit assignment: it is hard to tell which step produced the gain;
- Long trajectories: heavy ineffective exploration and repeated calls waste compute and amplify cost in both training and inference.
Common responses include: splitting by sub-goals and setting process rewards; using curriculum learning to move from short tasks to long ones; replaying and filtering trajectories to keep high-value samples; using reward shaping to suppress redundant calls; and compressing trajectories at the execution-framework layer. A rule of thumb from practice: the quality of reward design often determines the final result more than the choice of algorithm.
3. The Truth About Cost: Why the Quota “Burns Out in Ten Minutes”
3.1 The basic structure of token billing
Mainstream inference services typically meter cost by token and distinguish two kinds of input:
- Cache-miss input: the full-price baseline, fully participating in computation;
- Cache-hit input: reuses the computed result of an existing prefix, at a much lower price—often a fraction of the former.
There are also two billing points that are easy to overlook:
- Multimodal input: images, audio, and video are first converted to tokens by a vision or speech encoder, so a multimodal long-horizon Agent’s input cost can far exceed that of text alone;
- Thinking tokens: a reasoning model generates large spans of internal reasoning before giving an answer, and this is usually billed as output tokens.
Caching generally matches on the “longest common prefix,” most implementations cap how long a cache entry stays valid, and they distinguish inference-side caching from context caching. This is a detail where implementations differ significantly, so the official documentation should be the reference.
3.2 The cost-amplification effect of long-horizon Agents
A single long-horizon task often involves dozens of model calls, each sending the “system prompt + tool definitions + task goal + interaction history + tool returns” into the model as a whole. Suppose a single-turn request has input size $I$ and output size $O$, input unit price $p{in}$ and output unit price $p{out}$; the total cost of one task is approximately:
Cost ≈ N × [ I × p_in + O × p_out + C × p_out ]
where $N$ is the number of calls and $C$ is the number of thinking tokens. The output unit price is usually clearly higher than the input unit price, because autoregressive decoding generates tokens one at a time with low parallelism, making per-token compute cost higher, and memory bandwidth often becomes the bottleneck. When output is priced several times higher than input, verbose answers and reasoning become the biggest cost amplifier. The longer the context, the more every turn pays again for the entire history, so total cost grows roughly quadratically with task length. The “quota exhausted fast” phenomenon mentioned earlier stems precisely from this.
3.3 Seven practices you can put to work
- Stable prefix: put the system prompt, tool definitions, and long-term memory first and keep them byte-for-byte identical. Do not insert volatile fields such as timestamps or random IDs, to maximize cache-hit rate;
- Layered context: divide context into system, task, retrieval, interaction, and output layers; send only what the current task truly needs into the window, summarize history, and externalize details to a knowledge base for retrieval on demand;
- Slim tool returns: trim irrelevant fields, paginate large results, truncate over-long logs, and avoid stuffing raw artifacts back into context whole;
- Cap thinking length: set a thinking budget for reasoning models, and use a lower tier or turn thinking off for simple tasks;
- Model-tier routing: route requests to models of different sizes by task difficulty—for example, let a small model handle intent classification, field extraction, and routing decisions, and escalate complex reasoning to the flagship model;
- Budget circuit breaker: set token and cost caps per task, per session, and per tenant; degrade, queue, or require human confirmation as thresholds approach;
- Observability and attribution: record input, output, and cache-hit tokens by session, user, and tool to pinpoint “who is burning the money.”
The following sample code illustrates the ideas of budget control and a stable prefix (general pseudocode only):
import hashlibimport timeclass BudgetExceeded(Exception):passclass TokenBudget:"""Metered separately for input / output; thinking tokens are billed as output"""def __init__(self, max_input, max_output):self.limits = {"input": max_input, "output": max_output}self.used = {"input": 0, "output": 0, "cache_hit": 0}def charge(self, usage):self.used["input"] += usage["prompt_tokens"]self.used["cache_hit"] += usage.get("cached_tokens", 0)# Thinking tokens are already included in completion_tokens; do not double-countself.used["output"] += usage["completion_tokens"]for k in ("input", "output"):if self.used[k] > self.limits[k]:raise BudgetExceeded(f"{k} budget exceeded: {self.used[k]} > {self.limits[k]}")def snapshot(self):return {**self.used, "cache_hit_rate":round(self.used["cache_hit"] / max(self.used["input"], 1), 3)}def build_prompt(system_block: str, tool_schemas: list, history: list):"""Stable prefix first: keep system prompt and tool definitions byte-for-byte identical to hit the prefix cache"""prefix = json_dumps({"system": system_block, "tools": tool_schemas},sort_keys=True, separators=(",", ":"))digest = hashlib.sha256(prefix.encode()).hexdigest()[:12]# Volatile content (conversation history, tool returns) goes after the prefixreturn {"cache_marker": digest, "prefix": prefix, "tail": history}def compact_history(history: list, keep_turns: int = 8):"""Keep the most recent N turns verbatim; summarize earlier turns to avoid unbounded history growth"""if len(history) <= keep_turns:return historyhead, tail = history[:-keep_turns], history[-keep_turns:]summary = {"role": "system", "content": f"[History summary] Compressed {len(head)} turns of interaction"}return [summary] + tail
4. Security Tradeoffs: Governing Capability Diffusion Under Open Weights
4.1 How the security structure of open weights differs
Open weights mean the model files can be downloaded by anyone, privately deployed, and freely modified. This brings three structural changes:
- No recall: once released, you cannot withdraw a capability or patch a flaw through server-side updates the way you can with a closed API;
- Alignment can be removed: safety alignment trained on human preferences lives in the weights and can be substantially weakened through continued fine-tuning;
- Hard to observe misuse: private deployments do not pass through the publisher’s service, making actual usage hard to learn.
So it is important to recognize: model-level safety protection under open weights is a “soft constraint that can be bypassed”; the real line of defense lies in system design and governance mechanisms.
4.2 A governance framework worth borrowing
Drawing on the approach of the NIST AI Risk Management Framework (AI RMF: Generative AI Profile), risk can be divided into “risks of the model itself” and “risks of system use.” Take code generation—the most criticized capability of open-weight models—as an example:
- generating code with known vulnerabilities;
- the model, in turn, suggesting that safety checks be disabled;
- helping build malicious programs.
These risks cannot be eliminated by the model alone and can only be intercepted at the application layer. A common layered approach in the industry is as follows:
| Layer | Core question | Typical measures | Characteristics under open weights |
|---|---|---|---|
| Model | Will the model itself emit harmful content | Safety fine-tuning, refusal policies, value alignment | Can be removed by continued fine-tuning; serves only as a baseline |
| System | The environment in which the model is invoked | Sandbox isolation, least privilege, output validation, auditing | Depends entirely on the deployer; responsibility shifts forward |
| Governance | Who may obtain and use the model, under what conditions | Licenses, tiered release, red-teaming, model cards | Publisher and deployer share responsibility |
4.3 Tiered release and risk management
In practice, a gradual path of “managed first, open later” is common: expose capabilities in a controlled way through an API first, then open the weights after monitoring misuse patterns and completing red-team evaluation. A common quantitative reference in the industry is the European AI Act’s threshold for general-purpose AI models: when cumulative training compute reaches 10^25 FLOPs, it triggers additional obligations such as systemic risk assessment, adversarial testing, and incident reporting. Publishers should also provide model cards and system cards describing capability boundaries, known risks, and recommended deployment methods.
4.4 Special risks in terminal scenarios
When an Agent executes commands in a terminal environment, the risks differ sharply from those of traditional applications:
- Prompt injection: untrusted command output, web content, or file content may carry malicious instructions that hijack the Agent’s behavior;
- Privilege abuse: an Agent may read keys, modify production configuration, or initiate outbound connections;
- Supply-chain risk: installing dependencies of unknown origin, or introducing backdoors in scripts.
For an Agent, model safety is only one link; sandbox isolation and permission control are the real security boundary.
4.5 Risks amplified by multi-agent collaboration
Multi-agent collaboration makes role separation possible—for example, a planner, an executor, and a reviewer each doing their part—but it also amplifies risk. An executor injected with malicious instructions may contaminate the entire collaboration chain’s output; a reviewer that shares context with the reviewed party is also easily “persuaded.”
Three principles are therefore recommended: trust no content passed by any agent unless it has been validated; authorize each agent independently and forbid access beyond its scope; require human approval for critical operations.
5. Restructuring the Inference System: The Tradeoffs Behind Long Context and High-Speed Output
5.1 Why long context is “expensive”
Standard attention’s compute grows quadratically with context length, while KV-cache memory grows linearly with length. When the window reaches the million-token scale, time to first token (TTFT) is dominated mainly by the prefill phase, and memory pressure comes mainly from the KV cache. Common industry optimizations include:
- Sparse or sliding-window attention: attend only to local and key tokens;
- Grouped-query attention (GQA): multiple query heads share one set of key-value heads, compressing the KV cache;
- Paged KV cache: borrowing the paging idea from OS virtual memory to reduce memory fragmentation and improve cache reuse;
- Prefill/decode disaggregation: deploy the compute-intensive prefill and the memory-access-intensive decode to different instances and optimize each separately.
5.2 Main techniques for speeding up output
From the generation process, output speed depends on the time per token in the decode phase, so speedups concentrate on “reducing the number of serial decoding steps” and “improving per-step efficiency”:
- Speculative decoding: a lightweight draft model or the model’s own shallow modules guess several tokens in a row, then the target model verifies them in parallel in one pass; accepted tokens land directly, reducing decoding steps;
- Dynamic batching: merge multiple requests into the same batch to improve GPU utilization;
- Quantization and operator optimization: reduce compute and memory-access overhead while keeping accuracy under control;
- Scheduling optimization: order requests by length and priority so short requests finish first.
A high-speed version usually combines the above techniques without changing the model weights to optimize throughput and latency, so its intelligence is basically the same as the standard version, with the difference mainly in speed. The “faster” experience users perceive generally has two parts: thinking speed (tokens generated per unit time) and tool-execution speed (the time each tool call takes to return). The latter depends on the execution framework’s parallelism and the infrastructure, and this is one of the core values of a managed agent service.
5.3 Context engineering in practice
Supporting a million tokens does not mean that “stuffing everything in” is the optimal solution. For a long-horizon Agent, a more effective approach is layered context with retrieval on demand.
An abstracted practice case: an enterprise knowledge-base assistant initially placed each multi-tens-of-thousands-of-words product document into context whole, so a single request’s input exceeded 40,000 tokens, the cache-hit rate was under 20%, and TTFT exceeded 5 seconds. After introducing retrieval-based context management, the system first used a lightweight classifier to judge the question type, then retrieved the 5 most relevant passages (each no more than 800 tokens) and kept only summaries of the most recent 6 turns of conversation. After the change, single-request input dropped to about 6,000 tokens, the cache-hit rate rose above 70%, and answer accuracy stayed basically on par.
The sample code is as follows:
class LayeredContext:"""Layered context: system layer + retrieval layer + interaction layer + output-constraint layer"""SYSTEM = {"role": "system","content": "You are an enterprise knowledge assistant. Answer only from the given material and cite source numbers. ""When the material is insufficient, say so explicitly; do not speculate.",}def __init__(self, retriever, max_turns=6):self.retriever = retriever # retrieval layer: vector store / keyword indexself.max_turns = max_turnsdef build(self, query, history):snippets = self.retriever.search(query, top_k=5, max_chars=800)context_block = "\n".join(f"[{i + 1}] {s}" for i, s in enumerate(snippets))return [self.SYSTEM,{"role": "user", "content":f"Reference material:\n{context_block}\n\nQuestion: {query}\n"f"Requirement: answer in no more than 300 words and cite the source numbers used."},*history[-self.max_turns:],]
6. Reading Benchmarks: Scores and the “Uneven Capability” Phenomenon
6.1 How to read terminal-agent benchmarks
Terminal-agent benchmarks usually assess a model’s overall ability to complete complex tasks in a real, resource-constrained terminal environment, covering system operations, dependency management, code changes, and test verification, with an independent verification script for each task. Such benchmarks reflect “end-to-end task completion” well and show a model’s real productivity better than static Q&A. Three points to note when interpreting them:
- Close scores don’t mean identical capabilities: task-type distributions differ across the same benchmark, and a single aggregate score can mask weaknesses in specific capability dimensions;
- Scores depend heavily on the execution framework: tool-set design, retry strategy, and prompts all significantly affect results, so cross-framework score comparisons have limited meaning;
- Self-evaluation can’t replace real scenarios: your own task sets need continuous maintenance to prevent benchmark “contamination” (evaluation data leaking into training data) from inflating estimates.
6.2 “Uneven capability” and verbosity: problems not to avoid
Community attention to “uneven capability” and “verbose answers” has a real basis. Reinforcement learning depends on verifiable rewards, and goals like code execution and task completion are easiest to build reliable verifiers for; capabilities that are hard to judge automatically—writing, aesthetics, commonsense reasoning—are optimized less directly. This is the source of “uneven capability”: the direction of post-training optimization is highly correlated with the verifiability of the reward signal.
Verbose answers also have a mechanism. Under the guidance of process rewards, a model easily forms a “write more, cover more, hit more scoring points” strategy and tends to display its thinking process and intermediate results. For conversation-centric use cases, this does raise cost and slow the experience.
The remedy is not complex: state answer-length and format requirements explicitly in the system prompt; constrain fields through structured output; and, when necessary, design “conciseness” itself as an evaluable reward item.
7. Engineering Practices for Deployment
7.1 Agent execution layer: sandbox, recovery, and auditing
A managed agent service turns the “execution framework” into cloud infrastructure—a key step for long-horizon tasks to move from demo to production. A production-grade Agent execution layer should include at least the following capabilities:
- Sandboxed execution: run code and commands in containers or micro-VMs, with limits on CPU, memory, execution duration, and network egress;
- State persistence: write session state to object storage or a database to support resume-from-checkpoint;
- Audit logs: record each tool call, its parameters, returns, and the basis for decisions, traceable to a specific session;
- Observability: build monitoring and alerting around metrics such as tool-call volume, task success rate, average latency, and token consumption.
In the cloud, these capabilities are usually carried by combinations of common cloud products—container platforms, object storage, message queues, logging services, and monitoring/alerting—for example, container, storage, and logging cloud services such as those offered by Baidu AI Cloud, which enterprises can assemble as needed without building from scratch.
A minimal sketch of a sandbox executor:
import subprocessimport uuiddef run_in_sandbox(command, workdir, network="none", timeout=60,memory_limit="1g", cpu_limit="1.0"):"""Sketch: run Agent commands inside a container sandbox- run as a non-root user; privilege escalation prohibited- no network by default; open only specified domains on demand- dual constraints of resource limits and timeout- full audit logging"""run_id = uuid.uuid4().hexargv = ["container-exec-tool", # replace with the actual container runtime in use"run", "--rm","--user", "1000:1000","--network", network,"--memory", memory_limit,"--cpus", cpu_limit,"--workdir", workdir,"--label", f"audit_id={run_id}","agent-sandbox:latest","bash", "-lc", command,]audit_log(run_id, command, network) # audit log persisted separatelytry:result = subprocess.run(argv, capture_output=True, text=True,timeout=timeout)return result.returncode, result.stdout[-8192:], result.stderr[-2048:]except subprocess.TimeoutExpired:return -1, "", f"Task timed out ({timeout}s); terminated"
7.2 Cost and quotas: treat budget as a first-class citizen
Treat “budget” as a system constraint as important as “functionality,” and implement it at three levels:
- Request level: set a
max_tokenscap and turn off unnecessary chains of thought; - Session level: track cumulative consumption, and degrade to a smaller model or require human confirmation past a threshold;
- Tenant level: establish quotas and alerts, and give teams explainable usage reports.
7.3 Model selection: a four-dimension assessment of capability, speed, cost, and controllability
Enterprise selection should not look at a single benchmark score but assess four dimensions together:
| Dimension | Assessment points | Validation method |
|---|---|---|
| Capability | Task success rate, domain-knowledge accuracy, long-context utilization | Self-built task sets + real business sampling |
| Speed | Time to first token, output speed, concurrency capacity | Load-test P50/P95 latency and throughput |
| Cost | Token consumption per task, cache-hit rate, quota burn rate | End-to-end billing instrumentation |
| Controllability | Whether weights are open, private-deployment feasibility, audit and compliance | Security review + data-flow mapping |
For data-sensitive scenarios needing deep customization, the private deployment of open-weight models stands out; for scenarios pursuing fast iteration and low operational cost, a managed API may be more suitable. A hybrid architecture is common in real projects: core inference runs on private deployment, with elastic overflow spilling to managed services.
7.4 Security baseline: a six-item must-do checklist
- Sandbox isolation: all code and commands an Agent executes run in an isolated environment;
- Least privilege: authorize on demand, minimizing the access scope of tools and resources;
- Content filtering: detect prompt injection in external input, and redact sensitive information from model output;
- Human approval: require human confirmation for high-risk operations (such as production changes or money-related actions);
- Rate limiting: prevent resource and cost waste from runaway Agent loops;
- Auditability: make all decisions and operations replayable and accountable.
7.5 Observability and governance: make Agents “explainable and accountable”
The failure of a long-horizon task is often not “the model answered wrong” but “the execution chain broke somewhere.” So you need end-to-end tracing that covers the whole chain:
- record each call’s input summary, output summary, latency, and token count;
- instrument tool calls structurally, tracking failure and retry rates;
- assign each session a trace ID that connects model calls, tool execution, and resource consumption;
- establish anomaly-detection rules, such as a sudden spike in per-task token consumption, tool-call loops, or consecutive timeouts.
These capabilities can likewise be carried by common cloud products—logging services, monitoring/alerting, and distributed tracing—but the key is to design observability into the Agent framework from the start rather than patch it in afterward.
8. Conclusion: The Boundary of Capability Is Set by Systems Engineering
From this flagship upgrade we can read a clear industry trend: the main battlefield of large-model competition is shifting from “the quality of a single answer” to “the completion rate of long-horizon tasks,” and supporting this shift are the restructuring of the post-training paradigm, the restructuring of the inference system, and the rebalancing of security governance.
For developers, real competitiveness lies not in which model you use, but in whether you can build a reliable execution framework, fine-grained cost control, and rigorous security boundaries around the model. For organizations, embracing open weights means taking on more of the security-responsibility burden yourself: you need to evaluate the deployment environment carefully, establish audit mechanisms, and set risk red lines.
Model capability is the ceiling; systems engineering determines the floor. Whoever turns “capability” into “controllable productivity” will go further in this long-horizon Agent race.
