How to Evaluate LLM Coding Capabilities: Metrics and Criteria for Model Selection

    This article presents a reproducible workflow for evaluating the coding capabilities of large language models. It covers how to design test sets for code generation and bug fixing, how to verify 3D and multimodal abilities programmatically, how to benchmark agentic engineering tasks, which inference metrics matter in different scenarios, and how to translate evaluation results into model selection decisions and cost estimates.

    This article does not target any specific product. Instead, it describes a reproducible evaluation workflow: how to design tests, which metrics to use, and how to turn the results into model selection decisions.

    LLMs have reached trillion-parameter scale, so selecting a model based solely on parameter count or public leaderboard scores is no longer sufficient. Teams need to test models on their own tasks and convert the results into engineering efficiency and cost. The sections below break this down by capability dimension.

    How to Evaluate Code Generation and Bug-Fixing Capabilities?

    We recommend splitting this part into three evaluation cards, each with a fixed test set, metrics, and weight.

    Evaluation Card Test Set Core Metrics Weight Scope Limitations
    Multi-language and framework compatibility 30–50 problems per target language, covering concurrency, memory management, and type safety Compilation pass rate, unit test pass rate 30% Covers only mainstream languages; niche languages require a separate set
    Complex algorithms and data structures 20 problems each on dynamic programming, graph theory, and streaming window statistics, with hidden test cases and time limits Accuracy, timeout ratio 35% Problems should be close to real business scenarios, or you only test memorized algorithms
    Bug fixing and refactoring 50–100 fixed defects sampled from internal repositories, keeping error logs and before/after code Fix success rate, number of new failures after refactoring 35% Historical defects may already be in training data; refresh samples regularly

    An example of input and expected output for a bug-fixing sample:

    • Input: a KeyError: 'user_id' log together with the relevant snippet from handler.py.
    • Expected output: identify the source of the missing field, provide a patch, and explain why an empty request caused the old code to fail.

    The scoring rule is simple: if all original tests and new regression tests pass after the fix, the sample scores 1; otherwise it scores 0. The three card scores are aggregated by weight to produce a final score from 0 to 100.

    How to Verify 3D and Multimodal Capabilities?

    3D and multimodal outputs cannot be judged by text comparison alone; they must be validated programmatically.

    1. Spatial coordinates and geometric understanding

      • Input: “A cube with 2-meter edges, centered at the origin, with its top-center at y=1.”
      • Verification: parse the OBJ file generated by the model, compute the vertex bounding box, and check that it approximates a cube with x, y, z all within [-1, 1]. Metrics: bounding box error and valid face count ratio.
      • Failure boundary: when input constraints conflict, the model typically satisfies only some of them.
    2. Code interacting with a 3D scene

      • Input: a scene containing an object named Door that rotates 90 degrees around the Y axis when clicked, with a 0.5-second animation.
      • Verification: load the scene in a sandbox, trigger the click event, and check the rotation angle and duration. Metrics: script error-free rate and angular error.
      • Failure boundary: error rates rise noticeably with deep object hierarchies or non-standard coordinate systems.
    3. Design mockup to frontend code

      • Input: a sketch containing a navigation bar, a three-column card layout, and a bottom button.
      • Verification: render the generated page and compare it element by element against the design screenshot. Metrics: key element presence rate and layout pixel deviation.
      • Failure boundary: complex icons, handwritten annotations, and shadow effects are recognized poorly; output requires manual review.

    How Do Agents Complete Engineering Tasks?

    Agent evaluation focuses on whether the model can close the loop under constraints. It can be done in four steps.

    1. Scan the context: provide the repository directory tree and ask the model to list affected modules. Cross-check the result against the dependency graph from a static analysis tool and compute recall.
    2. Decompose the task: break the requirement into a subtask list, with each item specifying file paths and an acceptance command.
    3. Execute and roll back: run commands in an isolated container. Create a branch or snapshot before each modification, and roll back when tests fail instead of touching the main branch directly.
    4. CI/CD integration: read the pipeline configuration, generate or update unit tests, and verify them in the pipeline’s test stage.

    A long context window does not mean you should load the entire repository at once. Longer inputs cost more and diffuse the model’s attention. A more reliable approach is to retrieve the relevant files first and then inject them into the context.

    How to Put Inference Performance and Cloud-Native Integration into Practice?

    Different scenarios prioritize different inference metrics.

    • Interactive IDE: focus on time to first token (TTFT) and output tokens per second; choose a responsive model version.
    • Background batch review: focus on hourly throughput and cost per token.
    • Bug-fixing agents: focus on total time per task and average number of iterations.

    Below is a call example. It assumes the API is compatible with OpenAI’s chat completions format and depends on requests>=2.28 and urllib3>=1.26.

    1. import os
    2. import time
    3. import requests
    4. from requests.adapters import HTTPAdapter
    5. from urllib3.util.retry import Retry
    6. API_URL = os.environ["LLM_API_URL"] # e.g., https://your-gateway/v1/chat/completions
    7. API_KEY = os.environ["LLM_API_KEY"] # injected by a secrets management service, never hardcoded
    8. MODEL = os.environ.get("LLM_MODEL", "your-coding-model")
    9. session = requests.Session()
    10. retry = Retry(
    11. total=3,
    12. backoff_factor=1,
    13. status_forcelist=[429, 500, 502, 503, 504],
    14. allowed_methods=["POST"],
    15. )
    16. session.mount("https://", HTTPAdapter(max_retries=retry))
    17. def generate_code(requirement: str, context: str = "") -> str:
    18. payload = {
    19. "model": MODEL,
    20. "messages": [
    21. {"role": "system", "content": "You are a senior software engineer. Output only runnable code and necessary comments."},
    22. {"role": "user", "content": f"Project context:\n{context}\n\nRequirement:\n{requirement}"},
    23. ],
    24. "temperature": 0.2,
    25. "max_tokens": 2048,
    26. }
    27. headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
    28. start = time.time()
    29. resp = session.post(API_URL, headers=headers, json=payload, timeout=(5, 60))
    30. resp.raise_for_status()
    31. code = resp.json()["choices"][0]["message"]["content"]
    32. print(f"Elapsed {time.time() - start:.2f}s")
    33. return code
    34. if __name__ == "__main__":
    35. print(generate_code("Implement a key-value cache with LRU eviction, including unit tests.")[:500])

    The content returned by this code must not be executed directly. The correct approach is to write the output into an isolated container with no production network access, no mounted production credentials, and CPU/memory limits. Then run the unit tests, feed failure logs back to the model for further fixes, and set a maximum iteration count, such as 3. Logs should never print API keys or full code. Note that the retry policy will bill repeated POST requests, which must be factored into cost estimates.

    The choice of cloud platform depends on the infrastructure your team already has. For example, Baidu AI Cloud offers container services and elastic computing resources that can be used to build an inference cluster. This is only an example, not a selection recommendation.

    How to Make the Selection Decision?

    The table below summarizes selection priorities for four scenarios.

    Scenario Priority Capabilities Key Metrics Cost Focus Compliance Focus
    Interactive completion Latency, code accuracy TTFT, pass rate Cost per thousand calls Whether code can leave the jurisdiction
    Batch code review Throughput, long context Hourly processing volume Cost per token Data retention period
    Bug-fixing agent Fix success rate, tool calling Fix rate, average iterations Cost of failed retries Sandbox isolation, operation audit
    3D and design-to-code Spatial understanding, multimodality Bounding box error, layout deviation Image input billing Design copyright

    Before rollout, check against the following list:

    • Compare at least three candidate models on the same test set.
    • Record the sample size for every metric; conclusions from too few samples are unreliable.
    • Inject keys via a secrets management service; never write them into code or logs.
    • Execute generated code only in isolated environments.
    • Rotate part of the test samples every quarter to avoid data contamination.
    • Estimate costs based on real traffic, not per-call pricing.

    FAQ

    How should I choose?
    First determine the weights based on your business scenario, then score models on your own test set. Leaderboard scores are only useful as an initial filter.

    What should I watch out for?
    Check whether the test set overlaps with training data, whether the agent’s iteration count is capped, and whether the output code has been executed in isolation.

    What are common mistakes?
    Common mistakes include relying only on public leaderboards, repeatedly tuning against the same problem set, ignoring the extra cost of iterations, and deploying model-generated code directly to production.

    How do I estimate costs?
    Per-task cost can be estimated with this formula:

    Cost per task = (input tokens × input unit price + output tokens × output unit price) × average iterations

    Only by including the average iteration count does the estimate reflect the true cost of agentic repair tasks.