Practical Guide to Evaluating Long-Horizon LLM Agents and Code Generation

    As large language models shift from single-turn Q&A to executing multi-step tasks, evaluation criteria must evolve from conversational fluency to task completion, controllability, and verifiability. This guide explores engineering practices for long-context capabilities, long-horizon agent design, and methodologies for evaluating code generation, professional modeling, and financial workflows. It also covers factual accuracy testing, security governance, and cost-effective model selection to help teams build robust LLM evaluation frameworks.

    I. Background: From Answering Questions to Completing Tasks

    The way large language models (LLMs) are utilized is changing. Early scenarios focused primarily on single-turn Q&A, where users inputted questions and the model generated text responses. Evaluation criteria mainly revolved around language fluency and knowledge coverage. Once models are integrated into code repositories, command-line environments, file systems, and business systems, they must make dozens or even hundreds of sequential decisions. Each step’s output directly impacts subsequent results. Consequently, the evaluation focus shifts from “how well the question is answered” to “whether the task can be completed, whether the process is controllable, and whether the result is verifiable.”

    Understanding this shift is the starting point for building an evaluation system. Teams must first define the types of target tasks and then select the corresponding metrics.

    II. Engineering Implications of Long-Context Capabilities

    The context window refers to the maximum input length a model can process in a single inference pass, typically measured in tokens. With windows expanding to the million-token level, many materials that previously required segmentation can now be inputted in full. Examples include complete code repository indexes, hundreds of pages of technical documentation, long-term meeting transcripts, and multiple financial statements.

    However, a larger window does not equate to better comprehension. In practice, three points require attention:

    1. Positional effects of information: Models are typically more sensitive to the beginning and end of long texts, while details in the middle paragraphs are easily overlooked. Key constraints should be repeated in the prompt or placed in prominent positions.
    2. Cost and latency: The longer the input, the higher the inference time and cost. Relevant fragments should be prioritized and filtered, loading the full context only when necessary.
    3. Trade-off between retrieval and full input: For well-structured materials, retrieval-augmented generation (RAG) is usually more economical; for tasks requiring cross-paragraph reasoning, full input is more reliable.

    A schematic approach is as follows:

    1. Input material -> Split by file or chapter -> Retrieve relevant fragments
    2. -> Assemble context (constraints + task + relevant fragments)
    3. -> Model inference -> Result validation

    III. Designing Long-Horizon Agent Tasks

    Long-horizon agents refer to systems capable of autonomous planning, tool invocation, result observation, and continuous iteration. When designing such systems, the following aspects are recommended:

    1. Task decomposition: Break the overall goal into verifiable sub-tasks, each with clear inputs, outputs, and completion criteria.
    2. State management: Write completed steps, key variables, and intermediate artifacts to external storage rather than relying solely on conversation history. In long sessions, history records continuously expand; external state ensures the task is recoverable and auditable.
    3. Tool boundaries: Define permission scopes for each tool, such as read-only directories, restricted command whitelists, and limited network access. The principle of least privilege applies equally to agents.
    4. Failure recovery: Set timeouts, retry limits, and rollback mechanisms for each step. If consecutive failures reach a threshold, execution should halt and request human intervention.

    Schematic code (pseudocode):

    1. def run_agent(goal, max_steps=50):
    2. state = load_state(goal)
    3. for step in range(max_steps):
    4. plan = model.plan(goal, state)
    5. if plan.is_done:
    6. return save_result(state)
    7. result = execute_with_policy(plan.action) # Constrained by permission policies
    8. state = update_state(state, plan, result)
    9. if state.consecutive_errors >= 3:
    10. return request_human_review(state)
    11. return request_human_review(state)

    This structure separates model decision-making from execution permissions. The execution layer handles validation and rate limiting, facilitating auditing and troubleshooting.

    IV. Evaluating Code and Terminal Tasks

    When evaluating code generation capabilities, merely counting lines of generated code or syntax correctness rates is of limited value. A more effective approach is to construct executable test scenarios:

    • Functional correctness: Given requirements and test cases, track the pass rate.
    • Environmental constraints: Require task completion within a restricted terminal environment (e.g., only specific commands allowed, limited disk space and runtime) to assess the model’s adherence to constraints.
    • Modification quality: Compare the scope of changes, checking whether unrelated changes were introduced or existing tests were broken.
    • Multiple sampling: Run the same task multiple times and report the success rate interval rather than a single result. The generation process involves randomness, and single-run metrics can be misleading.

    It is recommended to maintain a fixed test set for each category of task and update it regularly to prevent evaluation data from being incorporated into training materials, which would inflate results.

    V. Professional Modeling and Script Generation Scenarios

    In fields such as 3D modeling and engineering drafting, models can write scripts to drive modeling software to generate parametric models. The key to such tasks is verifiability, which requires answering three questions: Does the generated geometry meet dimensional constraints? Can it be exported to a standard format? Does the structure change as expected when parameters are modified?

    In practice, a closed-loop approach of “generate script, execute, render or measure, and compare against reference values” can be adopted. For parametric models, additional testing of boundary parameters (e.g., minimum size, zero values, and maximum values) is necessary to check the robustness of exception handling.

    VI. Implementation Points for Financial and Reporting Workflows

    Financial modeling, investment analysis, and industry research reports involve extensive data referencing and logical derivation. Models can handle data sorting, formula construction, and initial drafting, but conclusions must undergo human review.

    It is recommended to establish the following checklist:

    • Can all numerical values be traced back to their original sources?
    • Can calculation formulas be recomputed in an independent environment to yield consistent results?
    • Are assumptions explicitly listed and modifiable?
    • Are risk warnings and uncertainty statements complete?

    VII. Testing Factual Accuracy and Reducing Error Rates

    Factual errors are a primary risk in LLM deployment. Evaluation should distinguish between two types of metrics. The first is the single-fact error rate: the proportion of individual facts in a statement judged to be incorrect, measuring fine-grained reliability. The second is the response-level error rate: the proportion of responses containing at least one error, reflecting the frequency of issues users actually encounter. These two reflect different problems and should be reported separately.

    Specially designed hard test sets are used to expose weak points, and their error rates are typically higher than those in daily use. When reporting, the construction method of the test set should be explained to avoid generalizing extreme scenario data into overall performance.

    Common methods to reduce error rates include providing searchable authoritative materials as a basis, requiring the model to annotate citation sources, implementing secondary checks for critical numerical values, and distinguishing between “confirmed” and “inferred” content in the output.

    VIII. Security and Data Governance

    More capable models require clearer boundaries of use. Organizations should focus on the following areas during deployment:

    1. Data compliance: Review training and usage data, clarifying what data must not enter the model’s context.
    2. Output filtering: Filter and audit outputs in high-risk domains, such as content involving system intrusion or bypassing security controls.
    3. Operation logging: Record tool invocation logs to ensure every automated execution is traceable.
    4. Credential management: Inject sensitive credentials via key management services rather than hardcoding them into prompts or code.

    Security capabilities also need to be quantified. Internal test sets can be used to track the model’s rejection rate and false rejection rate for sensitive requests. Both metrics must be monitored simultaneously, as over-rejection reduces practical utility.

    IX. Cost and Model Selection

    Model selection should comprehensively consider capability, latency, and price. Common practices include:

    • Choosing the most capable models for high-value, low-frequency complex tasks.
    • Selecting more cost-effective models for batch, low-complexity tasks.
    • Evaluating whether the premium for high-speed versions is justified for latency-sensitive interactive scenarios.

    It is advisable to perform cost-benefit calculations on candidate models using the same set of tasks, computing the average cost and success rate per unit task, and allocating resources accordingly.

    X. Implementation Checklist

    1. Define task types and select matching evaluation metrics.
    2. Construct fixed test sets covering normal, boundary, and exception scenarios.
    3. Configure permissions, state storage, and human intervention mechanisms for agents.
    4. Fact-check outputs and recalculate critical numerical values.
    5. Record cost, latency, and success rates, and conduct regular reviews.
    6. Link evaluation results to business goals as a basis for iteration.

    The ultimate value of LLM capabilities lies in task delivery. Connecting evaluation, engineering constraints, and business acceptance is the only way to ensure that technical investments yield stable returns.