Engineering Long-Horizon Agents on Million-Token Context Models
Evaluation of general models is shifting from parameter count and single-turn benchmarks to end-to-end task completion. This article covers million-token context constraints, cache-based cost models, recoverable agent loops, tool contracts, vertical workflows, hallucination control, and safety trade-offs for production long-horizon agents.
1. The starting point: evaluation is moving from scale to task completion
For the past two years, common metrics for general-purpose large models were parameter count and single-turn Q&A benchmark scores. In real engineering settings, users care less about how much a model “knows” and more about whether it can finish a complex task—dozens of steps, multiple tools, and repeated trial and error—without human intervention.
Recent public evaluations support this shift. On benchmarks of real terminal-constrained tasks (the model may operate the system only through limited interfaces such as a command line), leading models have reached the 60% range, compared with under 30% a year earlier. End-to-end evaluations of vertical workflows such as parametric modeling scripts, financial modeling, and industry research are also becoming important measures of productivity.
For developers this implies two things: selection criteria should move from leaderboard rank to pass rate on a target task set; engineering focus should move from prompt tuning to context management, tool orchestration, and state persistence.
2. Million-token context: capability and engineering constraints both scale up
2.1 Context length buys information completeness, not attention quality
The core value of a million-token context is avoiding truncation: a full repository, hundreds of pages of documents, and long session history can enter the model’s view at once, reducing information loss from traditional retrieve–assemble–retrieve pipelines.
Long context is not the same as effective use of long context. A widely observed issue is “lost in the middle”: recall is much higher for information at the start and end of the context than in the middle. Engineering still needs a layered strategy:
- Place critical constraints (API contracts, prohibitions, acceptance criteria) once at the beginning and once at the end of the system prompt.
- Organize large raw materials as structured summaries plus source anchors, not a flat dump.
- Deterministically preprocess ultra-long material (denoise, deduplicate, segment by semantics) before sending it to the model.
2.2 Context cost model: cache tiers are the main optimization lever
The real cost of long context is not the unit price of input tokens but repeated transmission. A common approach is tiered context-cache billing: cache hits often cost on the order of one-tenth of base input, while cache writes are priced by retention (for example 5-minute vs. 1-hour tiers), with the long-retention tier about twice the short one.
An approximate effective cost for a single request:
Cost = Lin_hit * C_hit + Lin_write * C_write+ Lin_miss * (L - C_hit - C_write) + Lout * C_outwhere L is total input length for this request, C_hit is prefix length that hit cache,and C_write is prefix length newly written to cache.
The engineering implication is direct: put stable content (system prompt, tool definitions, long-term knowledge, repo snapshots) first and keep the order fixed to maximize cache hits; put volatile content (current user input, live retrieval) last. Any change in prefix order invalidates the whole cache—the most common hidden cost in long-context apps.
# Stable long prefix + volatile suffix to maximize cache hitsdef build_request(system_block, repo_snapshot, tools, turn_input):stable_prefix = system_block + repo_snapshot + tools # fixed order; update by versionreturn {"messages": [{"role": "system", "content": stable_prefix},{"role": "user", "content": turn_input},],"cache_control": {"prefix_ttl_seconds": 3600},}
2.3 Context compression and external memory
Even with a million-token window, use a two-layer design: full history on object storage or a log service, and inside the window only the current subtask working set plus a rolling summary. That controls cost and makes sessions recoverable and auditable.
3. Long-horizon agents: from generating an answer to managing a process
3.1 Three typical failure modes on long-horizon tasks
- Goal drift: after many tool calls, the model leaves the original acceptance criteria.
- State loss: after context compression, intermediate artifacts and constraints are forgotten.
- Retry loops: the same failing command is run repeatedly, with no escalation or exit.
3.2 A recoverable main loop
A production agent loop needs an explicit state machine, structured memory, and budget limits:
# Illustrative agent main loop (pseudocode)state = {"goal": goal, "done": False, "step": 0, "artifacts": {}}while not state["done"] and state["step"] < MAX_STEPS:plan = model.plan(goal=state["goal"],artifacts=state["artifacts"],budget=remaining_budget())result = run_tool(plan.tool, plan.args) # all tool calls sandboxedstate["artifacts"][plan.tool] = result.digest()if result.is_error:state["errors"] = state.get("errors", []) + [result.stderr]if len(state["errors"]) > MAX_RETRY:escalate_to_human(state) # explicit escalation, not silent retrybreakstate["done"] = verify(state["goal"], state["artifacts"])state["step"] += 1
Three design points: verify must be deterministic (run tests, validate artifact schemas, compare numbers), not model self-scoring; errors must accumulate in structured form so the model can attribute them on the next step; hard step and budget caps are required to avoid cost runaway.
3.3 Capability requirements for terminal-constrained tasks
Terminal-constrained setups are useful because they strip specialized APIs and keep only a generic surface, which better reflects planning, error correction, and environment modeling. Engineering counterparts: run all tool calls in a sandboxed container platform, control filesystem and network egress, truncate command output and return structured summaries to the model.
4. Tool collaboration: scripted modeling and multi-engine scenarios
Newer models have improved at driving professional software by writing code: they can generate scripts and scene descriptions for mainstream game engines, and write parametric modeling scripts that drive 3D modeling and CAD tools. In public evaluations, leading models have reached the 90%+ range on tool-assisted parametric modeling benchmarks.
Implementation points:
- Contract first: define strict input/output schemas per professional tool; the model emits parameters, not free-form text.
- Idempotent generation: modeling scripts must be repeatable and deterministic for versioning and diffs.
- Visual feedback loop: feed render results or geometric checks (volume, bounding box, manifold topology) back to the model for generate–verify–fix.
- Failure degradation: on script failure, keep stderr and a minimal repro snippet rather than restarting from scratch.
5. Vertical workflows: engineering an end-to-end delivery
For financial modeling and industry research, end-to-end delivery typically includes data acquisition, definition alignment, model build, sensitivity analysis, report writing, and chart generation. To run this reliably:
- Definition dictionary: freeze metric definitions, units, and time granularity as checkable config so the model does not invent assumptions.
- Traceable numbers: every conclusion cell carries a source citation; any figure in the report can be traced to a source row.
- Separate compute from narrative: numbers come from deterministic code; the model organizes narrative and insight—no “model arithmetic.”
- Artifacts as interfaces: output structured files (tables, model files, report drafts) for downstream systems, not a chat blob.
6. Factual accuracy: hallucination control is a systems problem
Public internal stress tests report that, with targeted optimization, single-item factual error rates on deliberately hard cases can drop from above 20% to under 10%, and the share of answers containing errors to about 40% of the previous generation. These tests focus on hard samples and do not represent everyday error rates, but the methods generalize:
- Retrieval plus citation constraints: do not answer without sources; answers must include clickable/verifiable citations.
- Secondary checks on numbers and entities: rule-based checks on figures, dates, and proper names.
- Uncertainty: allow “insufficient evidence” and treat it as correct, rewarded behavior.
- Offline eval sets: maintain a business-specific hard-sample set in CI to catch regressions.
7. Safety alignment and data governance: a real capability–safety trade-off
One published approach is to identify and remove cyber offense/defense data during mid-training and RL to reduce abuse risk. The cost is measurable: on the same internal benchmark, an unfiltered version could solve about 90% of problems at pass@3, versus about 81% for the released version.
The implication for enterprises: safety is not free; trade-offs must be explicit. A workable frame is layered authorization—different capability tiers by scenario and identity—plus full operation audit, second confirmation for sensitive actions, and egress allowlists, replacing coarse “remove the data” with fine-grained runtime control.
8. Selection and optimization checklist
- Measure pass rate and human interventions on a private set of 20–50 real long-horizon tasks, not public leaderboards.
- Fix long-prefix order and monitor cache hit rate; hit rate is the primary cost metric for long-context apps.
- Distinguish standard vs. high-speed SKUs: high-speed is about twice the price of standard; use it only on latency-sensitive interactive paths; offline batch uses standard.
- Set triple budgets for agents (steps, tokens, spend) and wire monitoring/alerts.
- Make acceptance functions deterministic; model self-score is not a pass criterion.
- Put hallucination and safety regression sets into the release process.
9. Conclusion
Mature million-token context and long-horizon agent capability move large models from “tools that answer questions” to “executors that own a process.” The real engineering barriers are not parameter count but five details: context cost management, recoverable state, deterministic acceptance, tool contracts, and safety governance. Capabilities of Baidu AI Cloud on container platforms, object storage, logging, and monitoring/alerting can serve as a foundation for such long-horizon agent systems, helping teams take demo prototypes into production.
