Engineering Large Language Models: Long-Horizon Agents and Code Generation

    As large language models (LLMs) transition into production environments, the post-training phase becomes critical for optimizing downstream tasks like code generation and agentic workflows. This article explores the key engineering practices for deploying long-horizon agents and code generation models. It covers managing long-context memory bottlenecks (KV Cache), building secure sandbox infrastructures, evaluating agent performance, verifying generated code, and measuring inference acceleration. A practical deployment checklist is provided to guide engineering teams.

    1. Why the Post-Training Phase is Critical

    While pre-training provides the foundation of general capabilities, post-training determines a model’s performance on downstream tasks such as code generation and AI agents. As computational investment in reinforcement learning (RL) training increases, teams must simultaneously address three core challenges: memory consumption for long sequences, execution safety of model-generated code, and the quality of environment feedback. This article explores these three issues and concludes with a practical checklist for deployment.

    2. Long-Context Memory Bottlenecks and KV Cache Management

    As context length increases, the memory footprint of the KV Cache grows linearly with the sequence length. The estimation formula for a single sequence is:

    2 × number of layers × number of KV heads × dimension per head × sequence length × bytes per element

    Consider a hypothetical configuration: 80 layers, 8 KV heads, a head dimension of 128, FP16 storage, and a sequence length of 1 million tokens. The KV Cache for a single sequence would require approximately 328 GB. This figure illustrates that long-context scenarios must rely on compression or eviction strategies; simply adding more GPUs is not a scalable solution.

    There are three common approaches:

    1. Quantize KV Cache: Compress the cache from FP16 to INT8 or INT4. This yields significant memory savings, but the accuracy loss depends on the model and task. Teams must monitor both perplexity and downstream task scores.
    2. Sliding Window or Hierarchical Retention: Retain only the cache for recent tokens or critical layers. This is suitable for tasks with strong local dependencies but carries higher risks for tasks requiring cross-segment retrieval.
    3. Importance-based Token Eviction: Remove low-contribution entries based on attention scores. You must ensure that deleted content is not referenced in subsequent steps.

    Failure boundaries must also be documented. When the context length exceeds the range seen during training, the extrapolation of positional encodings may degrade quality. Therefore, evaluation must be conducted specifically at the target length, rather than relying solely on results within the training length.

    In RL training, sampling (rollout) for long sequences often bottlenecks overall throughput. A common mitigation strategy is to bucket tasks by length and allow short and long tasks to complete asynchronously, preventing short samples from waiting idly for long ones.

    3. Sandbox Infrastructure: Isolation, Quotas, and Cleanup

    Sandbox environments execute model-generated code and should be treated as handling untrusted input. At a minimum, the following requirements must be met:

    • Isolation: Use containers combined with user-space kernels or lightweight virtual machines to reduce the system call surface. Disable access to the host filesystem and internal network addresses.
    • Network: Disable outbound network access by default. If external service access is required, only explicitly whitelisted domains should be allowed.
    • Resource Quotas: Set limits on CPU, memory, disk, and execution time. Force-terminate processes upon timeout and log the termination reason.
    • State Cleanup: Destroy the filesystem after each task. Residual files can contaminate subsequent samples and distort training data.
    • Credential Management: Do not place long-term secrets inside the sandbox. Use only short-term, least-privilege temporary tokens.

    The scheduling system can dynamically allocate sandbox instances based on concurrency. An environment quality inspection service is responsible for filtering invalid feedback. Common filtering rules include: samples where the same input yields inconsistent results across multiple runs, samples that timed out due to infrastructure failures, and samples with faulty test cases. These samples should be removed from the training data and tracked separately. Excessive filtering will bias the training set toward simple tasks, so filtering thresholds must be reviewed regularly.

    Below is pseudocode illustrating the execution and retry logic. It cannot be run directly and requires replacement with an actual sandbox client.

    1. # Pseudocode, cannot be run directly, for illustration only
    2. # Dependencies: model client, sandbox service, predefined test suite
    3. def run_with_verification(task, max_attempts=3, timeout_s=600):
    4. for attempt in range(max_attempts):
    5. result = sandbox.run(task.code, tests=task.tests, timeout=timeout_s)
    6. if result.status == "passed":
    7. return result
    8. if result.error_type == "infra": # Infrastructure errors do not count as model failures
    9. continue
    10. task = model.revise(task, result.report)
    11. raise RuntimeError("Exceeded maximum retry attempts, manual review required")

    4. Evaluation Methods for Long-Horizon Agents

    Evaluating long-horizon agents requires clearly defining the task set, available tools, success criteria, and budget limits. Scores lacking this context cannot be meaningfully compared.

    Take SWE-bench as an example. It uses real issues from open-source projects and leverages the repository’s own tests as the judgment criteria. This design allows results to be independently verified, but it also means evaluation results depend on specific repository versions, dependency environments, and timeout settings.

    It is recommended to record at least the following metrics:

    • Task Completion Rate: The proportion of tasks that pass the tests.
    • Average Tool Call Count: Reflects execution efficiency.
    • Tool Call Error Rate: Differentiates between parameter errors and changes in tool response formats.
    • Per-Task Cost: Includes token count and execution time.

    Due to inherent randomness, single-run results are unstable. It is recommended to run multiple repetitions with different random seeds and report the mean and variance.

    Common failure modes include: parsing failures caused by changes in tool response formats; the model forgetting early constraints during later stages of multi-step execution; and repeatedly executing the same failed command.

    Troubleshooting should follow this sequence:

    1. Fix the environment image and random seeds to confirm the issue is reproducible.
    2. Step-by-step inspect the inputs and outputs of every tool call in the complete trace.
    3. Classify the failure as an inference error, tool error, environment error, or budget overrun.
    4. Modify only one variable at a time before re-running.

    5. Code Generation: Verify Before You Trust

    Generating full-stack projects directly from requirements is an attractive prospect, but generated code should not be trusted until it has passed verification. Verification typically includes the following four aspects:

    • Dependency Declaration: Lock dependency versions to avoid inconsistent behavior across different machines.
    • Input/Output Contracts: Define interface request and response formats using schemas, and generate tests based on them.
    • Error Handling: Check for the presence of timeouts, retry limits, and exception branches.
    • Test Assertions: Inspect status codes and return fields for critical interfaces, rather than merely checking if the program can start.

    The evaluation of visual output requires separate handling. Just because UI code runs does not mean the page meets the design intent. Screenshot comparison or human review should be used; you cannot rely solely on lines of code or structural correctness.

    When calling third-party design-to-code tools or rendering services, verify the terms of service, whether data leaves your internal network, and whether user privacy is compromised.

    6. Inference Acceleration: Measure Instead of Assuming

    The basic idea of speculative decoding is that a small model first proposes multiple tokens, and a large model verifies them in parallel, accepting the correct portions. The speedup depends on the acceptance rate, the overhead of the small model, the batch size, and the input/output length.

    Under the ideal assumption of an acceptance rate of α and k proposed tokens per round, the average number of tokens accepted per verification round is approximately (1 − α^(k+1)) / (1 − α). As the acceptance rate drops, the benefits diminish rapidly.

    Therefore, vendor claims of “2x to 3x speedup” only hold true under specific conditions. Before deployment, you should re-measure using your own workloads, recording Time to First Token (TTFT), single-token latency, and throughput. Simultaneously, compare quality on your own evaluation set; do not compare speed in isolation.

    At the deployment level, container autoscaling can handle traffic spikes, but scaling takes time. During sudden traffic surges, set request queue limits and continuously track inference latency and tool call success rates via logging and monitoring.

    7. Deployment Checklist

    Before deployment, confirm the following three groups of questions:

    1. Post-Training Optimization: Has the long-context compression method been tested at the target length? Is the sandbox network disabled by default, resource-limited, and cleaned up after each task? Are filtering rules reviewed regularly?
    2. Agent Evaluation: Are the task set version, tool list, budget, and random seeds recorded? Have failures been categorized?
    3. Code Generation: Have generated results passed test assertions with locked dependencies? Is visual output verified via screenshots or human review? Is the data flow of third-party services compliant?

    The capability improvements of large-scale models have indeed shifted the boundaries of what is possible for long-horizon tasks and code generation. However, every benefit depends on specific conditions. Conclusions are only reliable if they can be reproduced in your own data and environment.