A Practical Guide to Tiered Evaluation of LLM Code Generation Capabilities

    This article presents a practical, tiered framework for evaluating how well large language models generate code, addressing the gap between high benchmark scores and real engineering usability. It explains how to prepare a reproducible evaluation environment by fixing runtime variables, prompts, sampling parameters, and scoring scripts. Three progressive tiers are covered: basic correctness and constraint adherence, agentic self-correction, and long-context engineering understanding plus interface aesthetics. The article includes scoring tables, code examples, common pitfalls, and advice on archiving results and integrating the workflow into CI, enabling data-driven model selection.

    1. Background: Why a High Benchmark Score Does Not Mean a Model Can Write Code

    In AI-assisted programming, a persistent gap exists: model scores on general benchmarks keep climbing, yet when the generated code is actually delivered into a project, the front-end pages are often logically fragile and visually crude, with color schemes and layouts stuck in template styles from a decade ago. This shows that benchmark scores and engineering usability are not linearly related, and that the evaluation dimensions themselves have gaps.

    To close these gaps, “code generation capability” needs to be broken down into several observable, scoreable dimensions and validated in tiers of increasing difficulty. This article proposes three tiers: a basic correctness tier, an agentic iteration tier, and a complex engineering and aesthetics tier. The three tiers build on one another and can be used both to compare different models horizontally and to track changes from version to version of the same model vertically.

    It should be emphasized that this article does not recommend or compare any specific product. All methods are based on common industry evaluation practices, and model calls in the examples are expressed with neutral placeholders that can be replaced with any compatible interface.

    2. Preparing the Evaluation Environment for Reproducibility

    The biggest enemy of evaluation is randomness. Four categories of variables need to be fixed before starting.

    The first is the runtime environment. Use a unified containerized base image, language runtime version, and package manager version to avoid “it works on my machine” interference.

    The second is the prompts. Within the same tier, all models must use exactly the same prompts and the same context materials. It is forbidden to “help the model by tweaking a sentence and retrying” midway.

    The third is sampling parameters. Fix the temperature, maximum output length, and timeout. If a model supports thinking-budget-type parameters, those must also be fixed; otherwise results are not comparable.

    The fourth is the scoring script. Objective judgments such as “does it run” are handed to scripts, while subjective judgments such as “is it aesthetically pleasing” are handed to blind review by multiple people.

    A sample call skeleton is shown below, where both endpoint and model are placeholders:

    1. import os, json, subprocess
    2. from openai import OpenAI # Only to illustrate the interface shape
    3. client = OpenAI(api_key=os.environ["API_KEY"],
    4. base_url=os.environ["ENDPOINT"])
    5. def generate(prompt: str, files: dict) -> str:
    6. ctx = "\n".join(f"### {k}\n{v}" for k, v in files.items())
    7. resp = client.chat.completions.create(
    8. model=os.environ["MODEL"],
    9. temperature=0.2,
    10. messages=[{"role": "user", "content": prompt + "\n" + ctx}],
    11. )
    12. return resp.choices[0].message.content
    13. def run_checks(code: str, workdir: str) -> dict:
    14. path = os.path.join(workdir, "app.py")
    15. open(path, "w").write(code)
    16. lint = subprocess.run(["python", "-m", "py_compile", path],
    17. capture_output=True)
    18. return {"compiles": lint.returncode == 0,
    19. "stderr": lint.stderr.decode()[:500]}

    3. Tier 1: Basic Correctness and Constraint Adherence

    This tier examines the most fundamental but critical ability: given clear constraints, can the model write it correctly in one pass.

    The key to test design is “automatically judgeable.” For example, require the implementation of a function with caching, a sort meeting a specific complexity, or a form parser that strictly validates input, and provide a list of prohibited dependencies. Scoring looks at only three things: whether it compiles, the unit test pass rate, and whether constraints are violated.

    Constraint adherence is the most easily overlooked source of lost points. After a prompt states “do not introduce third-party dependencies,” many models still casually import a convenience library; after stating “implement using only the standard library,” external calls still appear. In real projects, such problems directly cause dependency conflicts and compliance risks, so they should incur hard deductions.

    Suggested scoring table:

    Metric Weight Judgment Method
    Compiles on first attempt 25% Script
    Unit test pass rate 35% Script
    Zero constraint violations 25% Static scanning
    Code readability 15% Manual review

    4. Tier 2: Agentic Self-Correction Ability

    The second tier is the watershed. Agentic programming means the model does not just output a piece of code but has a closed loop of “execute—observe—correct”: it runs the code itself after writing, reads error messages when it encounters errors, and iteratively fixes them, rather than throwing incomplete content directly at the user.

    The evaluation method is to deliberately create reproducible failures. Provide initial code with a hidden defect, or introduce an input that will inevitably trigger an exception, and observe the quality of the model’s behavior after it receives the error stack. Key metrics include: whether the number of repair rounds converges within a reasonable range, whether it merely masks the surface of the error (for example, by directly swallowing the exception), and whether the fix introduces new regressions.

    A practical automated loop is as follows:

    1. def agentic_loop(prompt, files, max_turns=5):
    2. history, code = [], ""
    3. for i in range(max_turns):
    4. code = generate(prompt, {**files, "History": "\n".join(history)})
    5. result = run_checks(code, "/tmp/work")
    6. if result["compiles"]:
    7. return code, i + 1, result
    8. history.append(f"Round {i+1} compilation failed: {result['stderr']}")
    9. return code, max_turns, {"compiles": False}

    When scoring, focus on three points: the median number of convergence rounds, whether oscillation such as “repeatedly changing the same line” occurs, and whether the final artifact passes all tests. Excellent performance converges within two or three rounds with localized changes; poor performance exhausts the rounds without passing, or involves massive changes with the logic rewritten.

    5. Tier 3: Long-Context Engineering Understanding and Interface Aesthetics

    The third tier is close to real delivery and contains two sub-dimensions.

    Long-context understanding examines whether the model can produce consistent code under the constraints of an entire project’s materials (interface agreements, data models, descriptions of existing components). The test method is to provide thousands of lines of context and embed several “global constraints” within it, such as a unified time format, a unified error code specification, and a specified state management convention, then check whether the generated result follows them. Common failure modes are locally reasonable but globally inconsistent, and forgetting information in the middle of the context.

    Interface aesthetics requires breaking subjective feelings into evaluable sub-items, with blind review by three or more people and averaging the results: whether the visual hierarchy is clear, whether spacing and grids are consistent, whether color use is restrained and contrast meets readability requirements, whether interaction feedback is complete (loading, empty state, error state), whether responsive breakpoints are reasonable, and Chinese typography details (line height, font weight, and mixed punctuation and numbers).

    A practice that improves the reliability of this tier’s evaluation is to provide the same design constraint specification, so that all models answer under the same “aesthetic contract,” thereby turning “personal preference” into “degree of constraint fulfillment.”

    6. Archiving Results and Engineering Implementation

    The value of evaluation lies in traceability. It is recommended to solidify each round’s results into structured records containing the model identifier, parameter configuration, three-tier scores, failure samples, and artifact snapshots, making regression comparison between versions easy.

    1. {"run_id": "2024-eval-013", "params": {"temperature": 0.2},
    2. "scores": {"basic": 0.86, "agentic": 0.72, "engineering": 0.68},
    3. "failures": ["Inconsistent global error codes", "Missing empty state"]}

    In real projects, the above process can be integrated into continuous integration: code generation artifacts automatically enter the build and test stages, objective metrics are judged by the pipeline, and subjective aesthetics are backed up by sampled manual review. Combined with a unified logging service and monitoring alerts, the long-term trends of generation success rate and rework rate can be continuously observed.

    7. Common Pitfalls and Recommendations

    First, only looking at the one-shot success rate while ignoring convergence cost. A model that only fixes things after multiple rounds may have a higher total cost on high-complexity tasks.

    Second, attributing aesthetic problems to the model. If the constraint specification is missing, any model will degrade into template-like output; complete the design contract first before discussing aesthetics.

    Third, feeding context without structure. Organizing it in layers of “global constraints—interface agreements—task description—reference materials” is far more effective than piling up raw text.

    Fourth, ignoring security and compliance. Generated code needs to go through dependency whitelist scanning and sensitive information checks to avoid introducing uncontrollable external calls.

    By advancing the evaluation across the three tiers, a team can obtain a complete picture that covers correctness, iteration ability, and delivery quality, turning model selection from subjective impression into data-driven decision-making. To implement this on Baidu AI Cloud, you can directly use the container platform to host the evaluation pipeline, use object storage to archive artifacts, and use the logging service and monitoring alerts to track long-term metrics.