Engineering Practices for Million-Token Context Code Agents

    As LLM context windows scale to millions of tokens, code generation and long-horizon task automation are evolving from single-turn interactions into continuously running agent systems. However, a larger context does not automatically yield better results; without hierarchical context management, tool constraints, fact-checking, and security governance, long contexts can amplify noise, latency, and costs. This article explores the engineering practices for deploying million-token context code agents, focusing on architecture layering, execution loops, domain workflows, accuracy and security, and cost and performance governance.

    1. Capability Positioning: Long Context as a System Capability

    The value of a million-token context window lies in minimizing information loss across files and stages, allowing agents to retain plans, historical actions, tool results, and constraints over long-horizon tasks. From an engineering perspective, “long context” should be treated as a system capability rather than an excuse to stuff all historical data indiscriminately into the prompt. Typical capabilities include cross-file code understanding, long-horizon task planning, tool invocation, script generation and execution, structured result delivery, fact verification, and refusal to answer. For code and long-horizon agent scenarios, a combined architecture of “Model Decision + Tool Execution + State Machine + Validator” is recommended: the model handles planning and semantic judgment, tools handle deterministic execution, the state machine enforces process constraints, and the validator verifies the results.

    At the deployment level, long-context applications typically require object storage to host artifacts and audit archives, container platforms to run isolated sandboxes, and logging services and monitoring alerts to provide observability. On Baidu AI Cloud, these capabilities can be supported by general components such as object storage, container platforms, logging services, and monitoring alerts. The key is not to stack components, but to clarify the responsibility boundaries of each component: sandboxes only execute controlled actions, state storage only records auditable states, and logs only collect necessary fields to prevent sensitive data from spreading to unnecessary processes.

    2. Long Context Engineering: Layering, Compression, Retrieval, and Caching

    The first principle of million-token context is “layering.” It is recommended to divide the context into four layers: Task Constraint, Plan State, Evidence Material, and Tool Result. The Task Constraint layer stores goals, acceptance criteria, and prohibitions; the Plan State layer stores the current step, completed actions, and to-dos; the Evidence Material layer stores retrieved code snippets, documents, and data; the Tool Result layer stores the output of the most recent execution. Each layer should have a different retention policy: the constraint layer is persistent, the plan layer is rolling-updated, the evidence layer is trimmed by relevance, and the tool result layer retains only summaries and key fields.

    The second principle is “combining compression and retrieval.” For historical conversations and tool outputs, generate structured summaries first, then retain traceable references. For code and documents, use retrieval-augmented generation (RAG) to inject snippets on demand rather than concatenating the entire content. The third principle is “measurable caching.” Cache hits and cache writes should be tracked separately. Cache keys should include task identifiers, context versions, and tool result versions to avoid incorrect reuse. The following pseudocode illustrates the context assembly and compression process:

    1. function run_agent(task, toolset, budget):
    2. plan = plan_task(task)
    3. state = initialize(plan)
    4. while not completed(state):
    5. context = assemble_context(task, state, budget)
    6. action = model_decision(context, toolset_description)
    7. result = execute_tool(action)
    8. state = update_state(state, action, result)
    9. state = validate_and_compress(state)
    10. return summarize(state)

    This pseudocode emphasizes three points: the budget participates in context assembly, tool execution results must be written back to the state, and the state is validated and compressed after each round. In actual implementation, timeouts, retry limits, human handover, and failure rollbacks should also be included.

    3. Code and Long-Horizon Agents: The Plan-Execute-Verify Loop

    The core of a code agent is not “generating a large block of code in one pass,” but the loop of “Plan-Execute-Verify-Repair.” It is recommended to break down tasks into verifiable steps, defining the input, output, success criteria, and failure handling for each step. Tool invocations should use whitelists and parameter schema validation, prohibiting free-form command concatenation. Sandboxes should restrict network access, file systems, and resource quotas. Execution results should retain exit status, standard output summaries, and diff information. For long-horizon tasks, the state machine should record “current step, dependent steps, completed evidence, and blocking reasons” to prevent the model from getting lost in a long context.

    The verification phase should adopt multi-layer validation: syntax and static checks, unit tests, diff reviews, and critical path regressions. Model outputs should not directly enter the production branch but should go through a “Generate-Review-Merge” pipeline. For failure repairs, the model should be required to first provide a root cause hypothesis and a minimal repair plan before executing validation. In terms of observability, at a minimum, task identifiers, step duration, tool invocation count, failure types, human handover count, and cost consumption should be logged to locate bottlenecks in long-horizon tasks.

    4. Domain Workflows: Parametric Modeling and Financial Analysis

    In parametric 3D modeling scenarios, agents can write scripts to complete modeling, texturing, rendering, and batch exporting. The engineering focus is on “parameterization” and “reproducibility”: define dimensions, constraints, materials, and export formats as structured parameters, and scripts should only read parameters and execute deterministic operations. Perform parameter range validation before execution, and conduct geometric integrity checks and rendering sampling after execution. For complex models, it is recommended to separate “modeling scripts, validation scripts, and export scripts,” recording versions and artifacts separately to avoid overloading a single script with too many responsibilities.

    In financial analysis scenarios, agents can participate in financial modeling, investment analysis, and industry research report workflows. These tasks demand higher factual accuracy and traceability. A three-segment delivery of “Data Table - Calculation Logic - Conclusion Summary” is recommended: the data table retains sources and timestamps, the calculation logic is expressed in auditable formulas or scripts, and the conclusion summary must reference data rows and calculation steps. Set cross-validation and anomaly thresholds for key figures, explicitly mark missing data, and prohibit the model from fabricating data. The final delivery should retain a human review checkpoint, especially for externally published research reports and investment recommendations.

    5. Factual Accuracy and Security Governance: Verification, Refusal, and Red Teaming

    Long-context agents are prone to factual splicing errors among “seemingly relevant” materials. Governance should establish a fact-checking chain: require citations of evidence snippets for key statements; execute degraded answers or refusals for facts that cannot be cited; apply rule validation for numbers, dates, and entity relationships; and retain conflict explanations for multi-source conflicts rather than forcing a merge. Internal stress testing should deliberately cover error-prone scenarios, such as approximate entities, outdated data, negated statements, and multi-hop reasoning. It is important to separately track “single-fact error rate” and “proportion of answers containing errors” to avoid masking issues with a single metric.

    In terms of security, identify and remove high-risk data during training and alignment phases, and incorporate tool whitelists, least privilege, sandbox isolation, and output reviews during the inference phase. For capabilities related to network offense and defense, unauthorized testing and offensive use must be explicitly prohibited, and filtering effectiveness should be continuously verified through red teaming. The pass rate difference between the released version and the unfiltered version should serve as a security governance metric, but it should not be simplified into a single score for external communication. Security strategies must align with business scenarios: code execution sandboxes, data access control, audit logs, and human review are all indispensable.

    6. Cost and Performance Governance: Multi-dimensional Metering and Task Routing

    The cost of million-token context applications is typically determined by input, output, caching, and service tiers. It is recommended to establish a universal metering table independent of any single vendor’s metrics:

    Metric Dimension Description Governance Recommendation
    Input tokens Task constraints, evidence materials, historical state Layered trimming, on-demand retrieval of evidence
    Output tokens Plans, code, summaries, conclusions Limit redundant output, structured delivery
    Cache hits Reusing stable context and tool results Design versioned cache keys, verify consistency
    Cache writes Overhead of new context entering cache Batch writes, avoid high-frequency small writes
    Service tier Differences between standard and high-throughput instances Route by task urgency, downgrade non-critical tasks

    For performance governance, a “Task Router” is recommended: short tasks take a lightweight context and low-cost path, while long-horizon tasks take a full state machine and high-reliability path. Use queues for peak shaving on batch offline tasks, and set first-packet timeouts and progressive output for interactive tasks. Cost control is not simply about lowering prices, but about integrating budget, latency, and quality into a unified decision-making framework, allocating resources based on task value.

    7. Implementation Roadmap: Evaluation Sets, Grayscale Rollout, and Continuous Operations

    In the initial deployment phase, an evaluation set strongly correlated with business needs should be established, covering code correctness, tool invocation success rate, long-horizon task completion rate, factual accuracy, security refusal rate, and unit task cost. Rollouts should adopt a grayscale strategy: start with internal toolchains, then move to low-risk business scenarios, and gradually expand. Each change should retain a rollback point. During the operational phase, continuously monitor failure type distribution, human handover rate, cache hit rate, and cost fluctuations, and periodically review prompt templates, tool protocols, and validation rules. Only by transforming model capabilities into observable, auditable, and governable system capabilities can million-token context code agents deliver stable value in real-world business environments.