Engineering Practices for Long-Horizon LLM Agents and Code Generation

    This article explores the engineering practices for building long-horizon AI agents capable of handling complex tasks and code generation. It covers core challenges, recommended architectural layers, context management strategies, execution safety, validation, and cost optimization, providing a comprehensive guide for deploying reliable agent systems in production environments.

    1. From Single-Turn Q&A to Long-Horizon Tasks

    Early LLM applications primarily involved single-turn Q&A, where a user asks a question, the model generates a text response, and the interaction ends. As model reasoning and tool-calling capabilities have improved, business demands have shifted toward long-horizon tasks: developing a functional module based on a requirements document, troubleshooting faults in a restricted terminal, or generating a complete analytical report from a set of data. These tasks typically involve multiple steps, where the output of each step influences subsequent decisions, and the entire process may last tens of minutes or longer.

    Long-horizon tasks impose new requirements on engineering systems. The model must remember the goal and intermediate results, recover from failures, and operate within the external environment’s permission boundaries. Consequently, the focus shifts from “whether the model can answer” to “whether the system can reliably complete the task.”

    2. Core Challenges of Long-Horizon Agents

    In practice, the failure reasons for long-horizon agents can generally be categorized into four types.

    1. Context Bloat. Tool outputs, logs, and intermediate reasoning at each step consume the context window. As the context grows longer, the beginning and end information is more likely to be ignored, and inference costs increase.

    2. Unreliable Tool Calling. The model may generate calls with incorrect parameter formats or continue along an incorrect path when a tool returns an exception. Such issues require the tool layer to handle parameter validation and error normalization as a fallback, rather than relying entirely on the model to self-correct.

    3. Difficulty in State Recovery. If a task is interrupted without a persistent checkpoint, it can only be executed from scratch, wasting resources and potentially repeating operations with side effects.

    4. Lack of Result Validation. A model claiming “done” does not mean the task is truly complete. An independent verification step is necessary, such as running tests, comparing file hashes, or checking data constraints.

    To address these four issues, a more robust approach is to decouple the system into several independent layers: planning, execution, memory, and validation.

    A maintainable long-horizon agent typically includes the following components:

    • Planning Layer: Determines the next action based on the goal and current state, outputting a structured action description.
    • Tool Layer: Centrally manages callable capabilities, responsible for parameter validation, permission checks, timeout control, and result truncation.
    • Memory Layer: Saves task goals, key decisions, and intermediate artifacts, and compresses and summarizes historical results.
    • Validation Layer: Executes independent checks before the task declares completion, deciding whether to pass, retry, or escalate to a human.
    • Checkpoint: Persists state after each step, supporting interruption recovery and backtracking.

    The following example demonstrates the basic structure of the main loop. The functions are illustrative; actual implementation should add details based on specific business needs.

    1. def run_agent(task, tools, max_steps=20):
    2. state = {"goal": task, "history": [], "artifacts": {}}
    3. for _ in range(max_steps):
    4. plan = model.plan(state) # Planning layer outputs structured actions
    5. if plan.type == "finish":
    6. return verify(state) # Validation layer independently judges the result
    7. result = tools.execute(plan.action, plan.args) # Tool layer executes and validates
    8. state["history"].append(summarize(result)) # Compress result and write to memory
    9. state = checkpoint(state) # Persist for breakpoint recovery
    10. raise TimeoutError("Exceeded maximum steps, manual intervention required")

    The key to this structure is that the model is only responsible for decision-making, all side effects are executed by the tool layer, and the state is recorded at every step. When issues arise, engineers can pinpoint the specific step rather than reading through the entire conversation.

    4. Context Management Strategies

    Context management is the most easily overlooked aspect of long-horizon tasks. Common strategies include the following.

    Tiered Retention. Task goals, constraints, and the current plan should always be retained in the context. Early tool outputs can be replaced with summaries, keeping only conclusions and key values.

    Result Truncation. Command-line outputs, logs, and API response bodies are often very long. The tool layer should set a limit and note the omitted length when truncating to prevent the model from assuming the information is complete.

    Retrieval Over Full Loading. For large codebases or document collections, use an index to locate relevant fragments first, then inject those fragments into the context, rather than loading everything at once.

    Cache Reuse. System instructions and fixed materials within a task remain largely unchanged across multiple calls, making them suitable for context caching. When cache hits, the processing cost for repeated portions drops significantly. Actual benefits depend on the hit rate, which needs to be verified through log statistics.

    The following function demonstrates the truncation and annotation method for tool outputs:

    1. def truncate_output(text: str, limit: int = 4000) -> str:
    2. if len(text) <= limit:
    3. return text
    4. omitted = len(text) - limit
    5. return text[-limit:] + f"\n[Omitted {omitted} characters at the beginning]"

    Here, the end content is retained because error messages in command execution results are usually located at the end of the output. If the task nature differs, the retention position should be adjusted accordingly.

    5. Execution Safety in Code Generation and Restricted Terminals

    Allowing models to execute commands in a terminal is an effective way to improve efficiency, but it also brings obvious risks. The execution environment should follow the principle of least privilege. Common measures include:

    1. Command Whitelisting. Only explicitly listed commands are allowed; arbitrary shell concatenation is prohibited.
    2. Sandbox Directory. The working directory is restricted to an isolated space, prohibiting access to sensitive paths on the host machine.
    3. Timeout and Resource Limits. Each command has a timeout to prevent processes from hanging indefinitely.
    4. Network and Credential Isolation. The sandbox has no external network access by default. Secrets are injected via environment variables or a key management service, not written into code or logs.

    Here is an example code snippet. Note the use of an argument list to invoke the process, avoiding injection issues caused by shell interpretation:

    1. import shlex
    2. import subprocess
    3. ALLOWED_COMMANDS = {"ls", "cat", "pytest"}
    4. def run_command(cmd: str, timeout: int = 30) -> str:
    5. parts = shlex.split(cmd)
    6. if not parts or parts[0] not in ALLOWED_COMMANDS:
    7. raise PermissionError("Command not in whitelist")
    8. proc = subprocess.run(
    9. parts,
    10. capture_output=True,
    11. text=True,
    12. timeout=timeout,
    13. cwd="/workspace/sandbox",
    14. )
    15. return truncate_output(proc.stdout + proc.stderr)

    The whitelist must be set carefully based on the task scope. Even read-only commands can leak sensitive information, so production environments should further restrict readable paths.

    For code generation tasks, it is recommended to adopt a “generate, test, fix” closed loop. After the model generates code, a test suite determines whether it passes, and failure information is fed back to the model. The test cases themselves should be manually reviewed to prevent the model from modifying tests to “pass” the task.

    6. Structured Generation Tasks: A 3D Modeling Example

    In fields such as industrial design, architecture, and game art, a common practice is to let the model write parametric scripts, which are executed by computer-aided design or 3D software to generate models. The advantage of this approach is that results are reproducible, and modifying parameters allows for batch generation of variants.

    During implementation, three points require attention. First, parameters should be explicitly extracted and recorded from the requirements, such as dimensions, units, and materials. Second, after script generation, geometric validation should be performed to check bounding box dimensions, unit consistency, and topology closure. Third, key results should be rendered as images or cross-sections and submitted to a manual or visual validation step for confirmation.

    The validation step can be written as an independent function, separated from the generation process:

    1. def validate_model(bbox, spec, tol=0.01):
    2. errors = []
    3. for axis in ("x", "y", "z"):
    4. expected = spec[axis]
    5. actual = bbox[axis]
    6. if abs(actual - expected) / expected > tol:
    7. errors.append(f"Dimension deviation on {axis} axis exceeds tolerance")
    8. return errors

    7. Factual Accuracy and Evaluation Design

    The output of long-horizon tasks often contains a large number of statements, and a single factual error can invalidate the overall conclusion. Therefore, evaluation should focus on both the error rate of individual statements and the proportion of answers containing errors.

    It is worth noting that stress tests designed for error-prone scenarios typically have higher error rates than average daily usage. Therefore, test results should be interpreted as relative comparisons, not direct estimates of production performance. When constructing an evaluation set, it is recommended to cover the following types:

    • Questions requiring multi-hop reasoning;
    • Questions involving unit conversions or date calculations;
    • Information that may be outdated in the training data;
    • Questions that require abstention rather than guessing.

    The evaluation metrics are calculated as follows:

    1. def fact_metrics(results):
    2. total_statements = sum(r["statements"] for r in results)
    3. wrong_statements = sum(r["wrong_statements"] for r in results)
    4. answers_with_error = sum(1 for r in results if r["wrong_statements"] > 0)
    5. statement_error_rate = wrong_statements / total_statements
    6. answer_error_rate = answers_with_error / len(results)
    7. return statement_error_rate, answer_error_rate

    In business contexts, factual validation can also be achieved by cross-referencing external sources. For example, financial outputs should be reconciled with original accounts, and regulatory outputs should be compared item by item with authoritative texts. The model is responsible for generating drafts, while the final conclusions are supported by traceable data sources.

    8. Security and Compliance Boundaries

    Security design should run throughout the entire system, rather than being patched before launch. The following principles apply to most scenarios.

    Data Minimization. Only provide the model with the data necessary to complete the task; sensitive fields should be masked before entering the context.

    Training and Usage Data Filtering. For data involving high-risk areas such as cybersecurity, identification and removal should occur during the data preparation phase, and the filtering effect should be verified through evaluation. Changes in capabilities after filtering should be documented for subsequent trade-offs.

    Manual Confirmation for Sensitive Operations. Operations such as deleting data, sending messages, modifying permissions, and deploying to production should require manual confirmation and retain audit logs.

    Output Review. Set up rules or classifiers for generated content to intercept violations and obvious injection instructions. Content returned by tools should be treated as data and not executed as new instructions.

    9. Cost and Performance Optimization

    Long-horizon tasks involve many calls, making costs easy to lose control. Cost estimation can use a unified formula:

    Single task cost = Σ (Input tokens × Input price + Output tokens × Output price) ÷ 1,000,000

    The prices in this formula should be based on the service provider’s latest pricing table. On this basis, common optimization methods include:

    1. Model Tiered Routing. Assign simple classification, extraction, and format conversion tasks to smaller models, and invoke high-capability models only for complex planning tasks.
    2. Reduce Invalid Steps. Minimize exploratory calls through clearer plans and terminate early on failure.
    3. Improve Cache Hit Rate. Place stable system instructions and materials at the beginning of the context, and dynamic content at the end.
    4. Control Output Length. Require the model to return results in a structured format to avoid lengthy narratives.

    Before and after optimization, compare the cost per task and the task success rate; both are indispensable. If a cost reduction is accompanied by a significant drop in the success rate, the optimization is invalid.

    10. Pre-Deployment Checklist

    Before putting a long-horizon agent into production, it is recommended to confirm the following items one by one:

    • Are task goals, constraints, and acceptance criteria recorded in a structured format?
    • Does each tool have parameter validation, timeout, and output truncation?
    • Does the execution environment use a sandbox, whitelist, and least privilege?
    • Is there a checkpoint for each step, and can it recover after an interruption?
    • Have conclusions been independently validated rather than relying solely on the model’s self-reporting?
    • Do sensitive operations require manual confirmation and retain audit logs?
    • Does the evaluation set cover error-prone scenarios, and do metrics track both statement-level and answer-level errors?
    • Can costs be tracked per task, and is there a budget alert in place?

    The value of a long-horizon agent comes from reliably completing complex tasks, not from the impressiveness of a single response. Only by clearly designing planning, execution, memory, validation, and security boundaries can the system operate continuously and reliably in real-world business environments.