Million-Token LLMs: Engineering Reliable Agents and Controlling Costs
Building agents around million-token language models requires more than a large context window. This article examines layered context management, execution–verification–recovery loops, verifiable deliverables, factuality evaluation, tool security, and request-level cost controls. It also outlines a production architecture for turning long-context capabilities into reliable, auditable workflows.
Million-Token LLMs: Engineering Reliable Agents and Controlling Costs
As model context windows grow from tens of thousands to a million tokens and parameter counts reach very large scales, system design priorities change. The question is no longer simply whether a model can answer a request. It is whether the model can maintain state throughout a long-running task, call tools, verify results, and deliver usable artifacts at a controlled cost.
These requirements raise the bar for code generation, terminal-based tasks, professional workflows, factual reliability, and cost management. The following sections examine the engineering practices needed to make these capabilities useful in production.
1. A Large Context Window Is Not Effective Memory
The most immediate benefit of a million-token context window is that it reduces the need for frequent chunking, summarization, and external retrieval. A larger window, however, does not guarantee that a model will reliably use information buried in long inputs. Attention computation, GPU memory consumption, KV cache management, positional encoding extrapolation, and interference from irrelevant content all affect practical performance.
Treat context as a resource to schedule, not as an input buffer to fill without limits.
A layered context strategy helps separate information by purpose:
- Fixed layer: System rules, output constraints, tool protocols, and safety boundaries. Keep this layer as stable as possible to support cache reuse.
- State layer: Task objectives, completed steps, the current plan, important intermediate findings, and unresolved questions.
- Evidence layer: Retrieved passages, file contents, logs, tables, and reference sources. Rank, deduplicate, truncate, and label this material with its sources.
- Artifact layer: Code, configurations, reports, modeling scripts, and computed results. Validate these artifacts with appropriate checkers rather than relying only on natural-language descriptions.
A simplified context-building process might look like this:
function build_context(task, budget):reserve = estimate_output_budget(task)usable = budget - reservesegments = [system_rules, tool_schema, safety_policy]segments += compress_history(task.history, max_ratio=0.3)candidates = retrieve(task.goal, task.sources)candidates = deduplicate(candidates)candidates = rerank(candidates, relevance, freshness, authority)selected = pack_by_score(candidates, usable - size(segments))return assemble(segments, selected, citations=true)
The key principles are to retain high-priority rules, maintain rolling summaries of long histories, and inject evidence according to the current task stage. When the budget is insufficient, remove low-relevance, duplicate, or easily retrievable content first.
For workflows that require auditing, record why each piece of context was selected and where it came from. This makes failures easier to reproduce and investigate.
2. Long-Running Agents Need an Execution–Verification–Recovery Loop
Unlike ordinary question answering, long-running tasks may span dozens or hundreds of steps and produce external side effects. A typical workflow reads the environment, creates a plan, executes commands, observes results, adjusts its approach, and produces files.
Without verification and recovery, an agent may continue working from an incorrect state and eventually deliver something that looks complete but cannot be used.
A robust agent loop should include:
- Planning: Break the objective into verifiable steps and identify dependencies.
- Tool execution: Use controlled interfaces for reading, writing, querying, computing, and testing.
- Result reduction: Condense tool outputs into structured state while retaining error codes, exit statuses, and key evidence.
- Automated verification: Check results through tests, static analysis, constraint solving, format validation, and numerical cross-checks.
- Recovery: Roll back, retry, narrow the problem, or request human confirmation when a step fails.
- Termination: Stop when acceptance criteria are met, the budget is exhausted, a risk threshold is triggered, or an error cannot be recovered from.
For example:
plan = planner(goal, state)while not done and step < max_steps:action = choose_action(plan, state)check_policy(action)result = sandbox.execute(action, timeout=..., limits=...)state = reduce(state, result)if not verifier.ok(state):plan = recover(plan, result, state)if cost_guard.exceeded():break
Evaluate long-running agents across repeated tasks rather than treating a single successful run as proof of reliability. Track success rate, average step count, retry rate, cost per successful task, human takeover rate, rollback count, and security incidents.
For coding tasks, also review diffs, check dependencies, and test consistency with the target runtime environment. For file-generation tasks, verify paths, permissions, idempotency, and replayability.
3. Code and Professional Workflows Must Produce Verifiable Deliverables
Coding is an important test of long-context and agent capabilities because it has explicit syntax, observable runtime behavior, and test feedback. Errors quickly become visible and can compound across subsequent steps.
High-quality systems typically divide coding tasks into five stages: understanding constraints, generating a patch, running tests, repairing failures, and producing an explanation. Every modification should be traceable and reversible.
For tasks performed in a real terminal environment, environment initialization, command permissions, timeout management, output truncation, and retry behavior often matter more than prompt wording.
Professional workflows follow a similar pattern. The model must deliver verifiable, structured artifacts—not just prose.
In parametric 3D modeling, for example, the workflow needs to generate scripts, execute modeling operations, check geometric constraints, export intermediate results, and confirm that dimensions, topology, materials, or assembly relationships satisfy the requirements.
Financial workflows involve financial modeling, investment analysis, industry research, and report writing. They must preserve data timestamps, formula definitions, calculation steps, and source references.
Separate computation from narration: use deterministic programs to calculate numerical results, then let the model explain and summarize them. Every important number in a report should be traceable to a table, formula, or external source.
A general delivery pipeline consists of:
- Intent analysis: Define inputs, constraints, and acceptance criteria.
- Tool planning: Select retrieval, computation, modeling, and testing tools.
- Structured intermediate representation: Use JSON or tables to carry parameters, results, and errors.
- Executable deliverables: Produce code, scripts, reports, model files, or configurations.
- Automated acceptance checks: Run unit tests, format validation, numerical cross-checks, and citation verification.
- Human review: Route high-risk or high-value tasks to a review queue.
4. Factuality Evaluation Must Distinguish Claim-Level and Answer-Level Errors
Long-context models can confuse details such as dates, numbers, relationships between entities, source references, and qualifying conditions. A single overall error rate does not capture these differences.
Evaluation should measure several dimensions:
- The error rate of individual factual claims.
- The proportion of answers containing at least one factual error.
- Citation precision.
- Whether refusals are appropriate.
- How well expressed confidence aligns with correctness.
Internal stress tests often deliberately emphasize difficult, error-prone cases. Their results should not be interpreted directly as everyday usage error rates. Production evaluation should reflect real traffic distributions and use risk-weighted samples.
Reducing hallucinations requires a combination of methods:
- Retrieval augmentation: Require retrieval for time-sensitive or fact-dense questions and retain the sources.
- Tool-based verification: Prefer deterministic tools for calculations, queries, and code execution.
- Evidence requirements: Tie important conclusions to supporting evidence. When evidence is missing, lower confidence or explicitly state the uncertainty.
- Self-checking and cross-validation: Use multiple checking paths and compare consistency for high-risk answers.
- Refusal policies: Allow the system to explain its limitations and request more information when evidence is insufficient or the request exceeds its capabilities.
Evaluation datasets should cover factual question answering, long-document summarization, table reasoning, code repair, multistep calculations, and conflicts across documents. Weight errors by severity.
In production, collect user feedback, conduct human spot checks, and classify root causes to support ongoing regression testing.
5. Design Safety Controls Alongside Tool Permissions
Once a model can execute commands, read and write files, or access business systems, output filtering alone is not an adequate security boundary.
A more robust approach uses defense in depth:
- Training: Identify high-risk data and downweight or remove it.
- Inference: Apply policy checks to inputs and outputs.
- Execution: Enforce least privilege, sandbox isolation, network egress controls, command allowlists, or approval requirements.
- Audit: Record the complete tool-call chain and changes to artifacts.
For coding and terminal agents in particular, assume that the model may generate dangerous operations. Divide tools into three permission levels: read-only operations, reversible writes, and irreversible writes. Irreversible actions should require additional confirmation or human approval.
Security evaluation should measure both the interception rate for risky requests and the false-refusal rate for legitimate requests. Overly restrictive controls can undermine usability.
Before release, conduct adversarial testing, tests for bypassing permission boundaries, prompt-injection testing, and rollback drills. Establish an incident response process as well.
6. Manage Costs with Request-Level Budgets
Million-token contexts can substantially increase both cost and latency. Billing commonly distinguishes input tokens, output tokens, cache reads, and cache writes. Higher-speed service tiers also tend to cost more.
Set budgets at the request level and manage caching, model routing, output limits, and context compression together.
A simplified cost estimate is:
cost = input_tokens * price_in+ output_tokens * price_out+ cache_hits * price_hit+ cache_writes * price_write
Useful controls include:
- Stable-prefix caching: Place fixed rules, tool protocols, and shared documents in a stable prefix to improve cache reuse.
- Tiered routing: Use lower-cost configurations for simple tasks and escalate for complex ones. Reserve higher-speed tiers for latency-sensitive interactions.
- Context compression: Apply rolling summaries, deduplicate evidence, and inject information by task stage rather than filling the entire window at once.
- Output control: Set maximum output lengths, require structured formats where appropriate, and define early stopping conditions.
- Observability: Record token usage, cache utilization, latency, success rate, and cost per successful task for each request.
A budget guard can estimate costs before execution and downgrade the request when necessary:
if projected_cost > request_budget:shrink_context(retain=high_priority)lower_max_output()route_to_lower_cost_tier()if still_over_budget:request_human_approval_or_abort()
7. A Reference Architecture for Production
A production-ready system typically includes the following components:
- Unified gateway: Handles authentication, rate limiting, and routing.
- Context manager: Manages retrieval, compression, and caching.
- Tool runner: Provides sandboxed execution and permission enforcement.
- Evaluation service: Supports offline regression tests and production spot checks.
- Logging and monitoring services: Provide tracing, alerts, and cost analysis.
- Object storage: Stores deliverables and audit records.
Use a gradual release process that includes offline evaluation, a limited rollout, shadow traffic, comparison of business metrics, and full deployment. Retain the ability to roll back with a single action.
Ultimately, the value of million-token contexts and long-running agents lies not in parameter counts or window sizes, but in the ability to turn complex tasks into executable, verifiable, and auditable workflows. Context engineering, tool contracts, result validation, security isolation, and cost controls must work together before model capabilities can become reliable production capacity.
