Evaluating LLM Code Generation and Agent Collaboration: A Practical Guide

    This article offers a practical framework for evaluating large language models (LLMs) in real-world software engineering, focusing on code generation and AI agent autonomy. It addresses five core questions: managing long-context inputs, defining stop conditions for self-correction loops, calculating true task costs, establishing evaluation criteria for agents, and implementing safety fallbacks. Each section includes actionable checklists and acceptance criteria, designed to help engineering teams move beyond benchmark scores and make informed decisions.

    Using LLMs to write code and letting AI agents automatically modify projects has become routine for many teams. When selecting a model, benchmark scores alone are insufficient to determine if it will perform well in a real engineering environment. This guide addresses five key questions: how to use long text inputs, when to stop self-iteration, how to calculate costs, what to test in an agent, and how to handle errors. Specific acceptance criteria are provided for each section.

    1. Code Generation with Long Context Inputs: Step-by-Step Validation

    Modern models generally support extensive context windows, allowing you to input requirement documents, API specifications, and sample data simultaneously. However, a long input does not guarantee a production-ready output in a single pass. In practice, when asked to generate an entire full-stack application at once, models often focus on the frontend pages and interactions, while simplifying or omitting backend APIs, database schemas, and persistence logic.

    A three-round approach is recommended:

    1. Round One: Focus solely on a frontend prototype. This output must include a list of pages, interaction states, and the sample data fields used.
    2. Round Two: Based on the Round One output, add backend APIs. Clearly define the request format, response format, and error codes for each endpoint.
    3. Round Three: Require the model to write integration tests for the APIs. The results of these tests serve as the primary acceptance criterion.

    Define prerequisites and failure boundaries clearly. The length of the input document, the frontend framework version, and the requirement for directly runnable code will all influence the outcome. If the Round One output fails to start, do not proceed to Round Two; fix the prototype first. If the APIs generated in Round Two do not align with the fields used by the Round One pages, update the field contract within the prompt and regenerate.

    The acceptance check focuses on two things only: whether each round’s output can be launched, and whether the tests for that round pass. The appearance of completeness is not a sufficient criterion.

    2. Self-Correction Loops: Using Stop Conditions to Prevent Wasted Effort

    Models with self-correction capabilities typically follow a workflow: receive an instruction, generate code, run tests, capture errors, modify code, and run tests again. This loop reduces the number of manual interventions but risks spinning endlessly, where the same error recurs, consuming tokens without progress.

    When evaluating this capability, track four metrics:

    • The number of rounds taken from start to when all tests pass.
    • The number of human interventions required per task.
    • Whether the task completes within a pre-defined maximum number of rounds.
    • The frequency with which the same error signature occurs consecutively.

    It is recommended to set a fixed maximum round limit (e.g., 10). The process should stop when the same error signature appears 3 consecutive times and be escalated for manual review. The logic is as follows:

    1. def should_stop(error_signatures: list[str], max_repeat: int = 3) -> bool:
    2. if len(error_signatures) < max_repeat:
    3. return False
    4. recent = error_signatures[-max_repeat:]
    5. return len(set(recent)) == 1

    For the error signature, it’s best to use the “exception type combined with the error file and line number” rather than the full log. Timestamps and temporary paths change on each run, which can make the same error appear different.

    Also, check if the model is taking shortcuts. If the model claims to have fixed an issue, verify this against the test results. Examine the code diff to confirm the model hasn’t deleted a failing test, loosened an assertion, or skipped a test case.

    3. Cost Calculation: Measure Cost per Successful Task

    A high benchmark score doesn’t necessarily mean a low cost per task. A more reliable metric is the cost per successful task:

    Cost per Successful Task = (Average Cost per Task) / (Task Success Rate)

    For example, if Model A scores 10% higher on a certain benchmark but its cost per task is twice that of Model B, and their success rates are 60% and 85% respectively (with Model B’s cost normalized to 1), then Model A’s cost per successful task is approximately 2 / 0.6 ≈ 3.33, while Model B’s is approximately 1 / 0.85 ≈ 1.18. In this scenario, Model B is more cost-effective.

    Calculate the single-task cost using the following formula and be sure to include retry attempts:

    Single-task Cost = (Average Input Tokens × Input Price) + (Average Output Tokens × Output Price)

    The table below provides a hypothetical cost example; replace the prices with your platform’s actual rates:

    Item Hypothetical Value
    Daily Task Count 200
    Avg Input Tokens 8000
    Avg Output Tokens 2000
    Input Price (CNY/M tokens) 2
    Output Price (CNY/M tokens) 8
    Avg Retry Count 1.3

    Daily Cost = 200 × 1.3 × (8000 × 2 + 2000 × 8) / 1,000,000 = 8.32 CNY.

    When calculating, specify the measurement basis: whether it includes cache hits, accounts for failed retries, and includes tokens used for tool calls. Also, record the daily allowed number of API calls or token limit, and the behavior when this limit is exceeded (e.g., queuing, degradation, or an immediate error). This quota behavior directly impacts the reliability of an agent running continuously.

    4. Agent Evaluation Checklist: Test Categories and Acceptance Criteria

    4.1 Stability and Concurrency

    • Method: Run N identical tasks concurrently (start with N=20), each with a timeout.
    • Metrics: Success rate, timeout rate, P95 response time, and the number of context loss events (task states that forget earlier constraints).
    • Passing Criteria (Example): Success rate no lower than 95%, timeout rate no higher than 2%, and zero context loss events. Adjust these thresholds according to your business’s tolerance.

    4.2 Complex Instruction Following

    • Method: Prepare 20 tasks with multiple constraints, such as “only modify the specified function in the specified file; do not add any third-party dependencies; keep the public function signature unchanged.” After each task, use a script to check the diff.
    • Passing Criteria: At least 90% of tasks must have zero constraint violations. Constraints related to dependency changes must have a 100% pass rate, as reverting dependency changes after a merge is costly.

    4.3 Environment Perception and Exception Handling

    The test framework below checks the agent’s behavior in both the absence and presence of a configuration file.

    1. import contextlib
    2. import io
    3. import json
    4. import os
    5. import sys
    6. import tempfile
    7. from typing import Any, Protocol
    8. DEFAULT_DB = {"host": "127.0.0.1", "port": 5432, "database": "app", "user": "app"}
    9. INSTRUCTION = (
    10. "1. Read config.json in the current working directory. "
    11. "2. If the file does not exist, print a warning to stderr starting with WARNING and use the default configuration. "
    12. "3. Return the parsed database connection parameters."
    13. )
    14. class AgentExecutor(Protocol):
    15. """Adapter protocol: the run method returns a dict including
    16. actions: list[str] - action identifiers, including "missing_file_handled" when the file is absent.
    17. db_config: dict - database connection parameters.
    18. """
    19. def run(self, instruction: str, workdir: str) -> dict[str, Any]: ...
    20. def _run_capturing_stderr(executor: AgentExecutor, workdir: str) -> tuple[dict[str, Any], str]:
    21. buf = io.StringIO()
    22. with contextlib.redirect_stderr(buf):
    23. result = executor.run(INSTRUCTION, workdir)
    24. return result, buf.getvalue()
    25. def _report(case: str, checks: dict[str, bool]) -> bool:
    26. for name, ok in checks.items():
    27. print(f"[{'PASS' if ok else 'FAIL'}] {case} / {name}")
    28. return all(checks.values())
    29. def test_missing_config(executor: AgentExecutor) -> bool:
    30. with tempfile.TemporaryDirectory() as workdir:
    31. try:
    32. result, stderr_text = _run_capturing_stderr(executor, workdir)
    33. except Exception as exc:
    34. print(f"[FAIL] Unhandled exception when config was missing: {exc}")
    35. return False
    36. checks = {
    37. "stderr contains WARNING": "WARNING" in stderr_text,
    38. "records missing_file_handled": "missing_file_handled" in result.get("actions", []),
    39. "returns default DB config": result.get("db_config") == DEFAULT_DB,
    40. }
    41. return _report("missing config", checks)
    42. def test_existing_config(executor: AgentExecutor) -> bool:
    43. expected_db = {"host": "10.0.0.5", "port": 3306, "database": "orders", "user": "svc"}
    44. with tempfile.TemporaryDirectory() as workdir:
    45. with open(os.path.join(workdir, "config.json"), "w", encoding="utf-8") as f:
    46. json.dump({"db": expected_db}, f)
    47. try:
    48. result, stderr_text = _run_capturing_stderr(executor, workdir)
    49. except Exception as exc:
    50. print(f"[FAIL] Unhandled exception when config was present: {exc}")
    51. return False
    52. checks = {
    53. "stderr has no WARNING": "WARNING" not in stderr_text,
    54. "does not record missing_file_handled": "missing_file_handled" not in result.get("actions", []),
    55. "returns DB config from file": result.get("db_config") == expected_db,
    56. }
    57. return _report("existing config", checks)
    58. class ReferenceExecutor:
    59. """Only for validating the test framework, not representative of any real model or agent."""
    60. def run(self, instruction: str, workdir: str) -> dict[str, Any]:
    61. path = os.path.join(workdir, "config.json")
    62. actions: list[str] = []
    63. if os.path.exists(path):
    64. with open(path, encoding="utf-8") as f:
    65. db = json.load(f)["db"]
    66. else:
    67. print("WARNING: config.json not found; using default configuration", file=sys.stderr)
    68. actions.append("missing_file_handled")
    69. db = dict(DEFAULT_DB)
    70. return {"actions": actions, "db_config": db}
    71. if __name__ == "__main__":
    72. executor = ReferenceExecutor()
    73. results = [test_missing_config(executor), test_existing_config(executor)]
    74. sys.exit(0 if all(results) else 1)

    To run, save the file as env_perception_test.py and execute python env_perception_test.py. The exit code is 0 when all checks output PASS. The provided ReferenceExecutor validates the test framework and does not represent the behavior of any real model. When integrating a real agent, write an adapter that satisfies the AgentExecutor protocol. If the agent outputs warnings through logging, ensure its handler points to sys.stderr, otherwise redirect_stderr will not capture the logs.

    Acceptance Criteria: When the config is missing, stderr must contain WARNING, actions must include missing_file_handled, and the default database parameters must be returned without unhandled exceptions. When the config exists, the agent must read the parameters from the file and not output a warning.

    5. Safety Boundaries: Sandboxing, Version Control, and Rollback

    The risks of an agent modifying files and executing commands stem from three areas: accidental file deletion, incorrect configuration changes, and misuse of production credentials. Establish the following boundaries before deployment:

    • Run the agent in a separate branch or sandbox directory, never directly on the main branch.
    • Commit current changes before each run to ensure you can revert to a known state.
    • For rollbacks, use git revert or switch to a previous commit. Do not use git reset --hard or force-push on shared branches.
    • The agent should only use test environment databases and keys, never production ones. Inject secrets via environment variables, not in code or logs.
    • High-risk operations like file deletion, deployment, and changing permissions must require manual confirmation before execution.
    • Review the diff after each run, paying close attention to deleted tests, loosened assertions, and newly added dependencies.

    Final Deployment Checklist

    1. Break down long-context tasks into frontend, backend, and test phases. Each phase must be executable and pass its tests.
    2. Set a maximum round limit and a repeated-error stop condition for self-correction loops.
    3. Calculate costs based on cost per successful task, and specify the measurement basis and quota behavior.
    4. Have quantified thresholds for the three evaluation categories: stability, instruction following, and environment perception.
    5. Run the agent in a sandbox or a dedicated branch, commit before execution, log all rollbacks, and require human confirmation for high-risk operations.