Engineering Practices for LLMs in Code Generation and Long-Horizon Tasks

    As large language models move beyond single-turn chat into code generation, tool use, and multi-step workflows, reliable deployment depends on more than model quality. This article presents practical engineering patterns for managing long context, decomposing long-running tasks, designing safe tool interfaces, validating generated code, evaluating factual accuracy, and controlling security, cost, and latency. It also includes a reusable state-machine example and an implementation checklist.

    Background and Problem Definition

    The focus of large language model applications has increasingly shifted from single-turn question answering to code generation, multi-step tasks, and long-context processing. Developers now need to know whether a model can maintain a consistent objective across a long workflow, call tools to perform real operations, and produce outputs that can be verified programmatically.

    This article does not focus on a specific product. Instead, it discusses general engineering practices for deploying these capabilities reliably.

    1. Understanding the Real Value of Long Context

    A larger context window allows a request to include more material, such as key files from a code repository, API documentation, and conversation history. However, a larger window does not automatically lead to better information utilization. Three common problems appear in practice:

    • The model is more likely to miss critical constraints when they are located in the middle of the context.
    • Irrelevant material dilutes attention and increases the risk of incorrect references.
    • Longer inputs increase response latency and invocation costs.

    For this reason, engineering systems should use an on-demand loading strategy: retrieve first, filter second, and assemble the final context last.

    A useful approach is to divide information into three layers:

    1. Essential task constraints that must always be preserved.
    2. Code or documentation directly relevant to the current step, which can be replaced dynamically as the workflow progresses.
    3. Background material that can be queried when needed, and should only be added when the model explicitly requires it.

    The first layer should remain in a fixed location. The second should change with the current step, while the third should be injected only on demand.

    2. Decomposing Long-Horizon Tasks and Managing State

    A long-horizon agent is a system that completes a task through multiple rounds of planning, execution, and feedback. Its reliability depends primarily on state management rather than the quality of any single response.

    Relying only on conversation history to track progress makes it easy to lose critical information when the context is truncated or the model deviates from the intended plan.

    The following principles are recommended:

    1. Break the overall objective into verifiable subtasks, each with clearly defined inputs, outputs, and completion criteria.
    2. Store intermediate results externally so that progress is decoupled from conversation history.
    3. After each step, verify that the current state still serves the original objective.
    4. Set a retry limit for failed steps. If the limit is exceeded, hand the task over for human review.

    The following generic state-machine example separates execution from validation. Both functions are injected by the caller, making the implementation easy to replace:

    1. from dataclasses import dataclass, field
    2. @dataclass
    3. class TaskState:
    4. goal: str
    5. pending: list = field(default_factory=list) # Steps to execute
    6. completed: list = field(default_factory=list) # Steps that passed validation
    7. artifacts: dict = field(default_factory=dict) # Outputs for each step
    8. def run_agent(state: TaskState, execute_fn, verify_fn, max_retry: int = 3) -> TaskState:
    9. while state.pending:
    10. step = state.pending.pop(0)
    11. for _ in range(max_retry):
    12. result = execute_fn(step, state)
    13. if verify_fn(step, result):
    14. state.completed.append(step)
    15. state.artifacts[step] = result
    16. break
    17. else:
    18. raise RuntimeError(f"Step failed repeatedly and requires human review: {step}")
    19. return state

    The key design decision is the separation between execution and validation. The execution function produces a result, while the validation function determines whether that result is acceptable. Because they are independent, each can be tested and replaced separately.

    3. Designing Tool-Calling Interfaces

    An agent creates value by interacting with external systems, such as reading and writing files, querying data, or triggering builds. Tool interfaces should satisfy three requirements.

    First, parameters should use structured descriptions. This helps the model produce valid calls and allows the server to validate them.

    Second, high-risk operations—such as deleting data, publishing a release, or changing permissions—must require explicit confirmation. The model should never be allowed to complete such operations unilaterally.

    Third, return values should include a clear status and readable error information so that the model can use the feedback to correct its next action.

    The following example defines a read-only file tool:

    1. {
    2. "name": "read_file",
    3. "description": "Read the text content of a file at a specified path within the project",
    4. "parameters": {
    5. "type": "object",
    6. "properties": {
    7. "path": {
    8. "type": "string",
    9. "description": "File path relative to the project root; parent-directory references are not allowed"
    10. }
    11. },
    12. "required": ["path"]
    13. }
    14. }

    On the server side, normalize the path before checking whether it remains inside an approved directory. This prevents path traversal attacks.

    Tools should also run with least privilege. Expose only the directories and interfaces required to complete the task.

    4. Closing the Validation Loop for Code Generation

    Generated code should not be judged correct based on manual inspection alone. A reliable workflow includes five stages:

    1. Generation
    2. Syntax or static analysis
    3. Unit testing
    4. Comparison against expected runtime results
    5. Human review

    If any stage fails, return the error information to the model without unnecessary transformation. This creates a correction loop, which should still be limited to a defined number of iterations.

    Special care is required when test cases are also generated by a model. If the implementation and its tests are produced in the same reasoning process, both may contain the same mistake and incorrectly pass together.

    Test cases should therefore be reviewed by humans and should cover boundary conditions, invalid inputs, and regression scenarios for known defects.

    5. Script-Based Modeling in Professional Workflows

    In areas such as industrial design, game art, and architectural design, many tasks can be represented as scripts. Parameters can generate geometry, while code can drive rendering, export, or inspection.

    Two principles apply broadly.

    First, convert requirements into a parameter table and explicitly define dependencies between parameters. For example, if the diameter of a hole must be smaller than the thickness of a component, that constraint should be encoded in validation rules rather than left to the model to follow implicitly.

    Second, execute scripts in an isolated environment and automatically inspect their outputs. Checks might include whether bounding-box dimensions are within the permitted range, whether geometry is closed, and whether units are consistent.

    Only artifacts that pass validation should proceed to subsequent stages.

    6. Factual Accuracy and Evaluation Methods

    Errors in professional content must be measured; otherwise, it is impossible to determine whether an improvement is effective. Teams should build their own evaluation sets and follow several rules:

    • Define the error rate clearly. Counting errors by individual claims can produce very different results from counting errors by complete response.
    • Include both ordinary scenarios and error-prone scenarios, and report them separately. A single aggregate number can hide structural weaknesses.
    • Use the same samples and evaluation criteria when comparing different versions.
    • Preserve the complete evaluation process instead of publishing only selected examples.

    For quoted numbers, regulatory provisions, and API parameters, use retrieval or human review rather than relying solely on the model’s memory.

    7. Security and Compliance Boundaries

    Because agents can execute operations, security should take priority over efficiency. Common safeguards include:

    1. Least privilege: expose only the resources and operations required for the task.
    2. Input validation: sanitize user input and external content to reduce prompt-injection risks.
    3. Output filtering: detect sensitive information, credentials, and unauthorized instructions; block and log them when found.
    4. Audit logging: record the parameters and results of each tool call, but never log secrets or personally sensitive information.

    External web pages, files, and tool results should all be treated as data rather than instructions. If such content contains text saying “perform this operation,” the model should report it instead of executing it.

    8. Optimizing Cost and Latency

    Several practical techniques can reduce unnecessary computation:

    • Use context caching for stable system prompts and background material.
    • Route tasks by complexity: use a lighter model for simple steps and a more capable model for complex planning.
    • Limit the output length of each call and configure a timeout for every invocation.
    • Cache results for identical requests and define an appropriate expiration period.

    Specific pricing and performance metrics should be based on the service provider’s latest published information and verified through internal load testing. Unverified figures should not be used for capacity planning.

    9. Deployment Checklist

    • The task objective and completion criteria are clearly defined.
    • Tool permissions follow the principle of least privilege.
    • High-risk operations require human confirmation.
    • Generated results undergo automated validation.
    • The evaluation set covers both ordinary and error-prone scenarios.
    • Logging and privacy policies have been implemented properly.

    By following these practices, teams can introduce agent capabilities within controlled boundaries while continuously building reusable evaluation data and engineering standards.