LLM Selection for Coding: How to Build a Coding Plan
Model versions change every few weeks, so teams that pick a coding LLM from leaderboard rankings and gut feeling get inconsistent results on completion, refactoring, and bug fixing. This article presents the Coding Plan, a practical methodology that covers capability, latency, cost, and compliance. It walks through task grading, building a private evaluation set from your own codebase, weighted scoring, cost estimation and portfolio routing, context and tool-call design, and monitoring with regression testing. You'll find task-grading tables, a task-card JSON schema, and Python code for evaluation, scoring, cost estimation, and routing.
Model versions change every few weeks. Flagship models keep getting upgraded, low-latency fast variants ship alongside them, and some new models first appear in public beta under anonymous names. In this fast-moving environment, many teams still choose models by looking at leaderboards and going with impressions. As a result, performance on real tasks such as completion, refactoring, and bug fixing tends to be hit or miss.
This article organizes these problems into a practical methodology: the Coding Plan. It is a usage plan for coding scenarios that covers capability, latency, cost, and compliance. Its core ideas are: define requirements by task, drive decisions with data, control cost with a portfolio, and ensure stability with regression testing.
I. Breaking Down the Problem: Why Model Selection Is Hard for Coding
1. Scenarios Are Highly Heterogeneous
Developer needs for coding tools fall into at least five categories: line-level code completion, single-function or script generation, cross-file bug fixing and refactoring, multi-step tasks that depend on tools (such as automatically fixing CI failures), and auxiliary work like code review, test writing, and API documentation generation. These tasks emphasize different capability dimensions:
| Task Type | Core Requirement | Tolerable Latency |
|---|---|---|
| Line-level completion | Low time-to-first-token, syntactic accuracy, consistent style | Hundreds of milliseconds |
| Function/script generation | Correct logic, complete edge-case handling | Seconds |
| Cross-file refactoring / bug fixing | Repository understanding, long context, reasoning depth | Tens of seconds to minutes |
| Tool-orchestration tasks | Planning, tool selection, error recovery | Depends on the task, usually longer |
| Code review and test writing | Understanding conventions, readability, coverage | Seconds to tens of seconds |
Using a single model for all scenarios usually means sacrificing either experience or budget.
2. Fast Iteration and Dynamically Changing Capabilities
Leading vendors typically iterate on their models on a weekly or even daily basis. Flagship versions keep improving complex reasoning and multi-step task capability; fast variants for low-latency scenarios ship at the same time, balancing response speed and cost; and some new models first appear on public platforms under anonymous codenames for blind comparison, collecting feedback before an official release. This means any selection conclusion has a shelf life, so a Coding Plan must include re-evaluation and rollback mechanisms.
3. Leaderboards Don’t Equal Engineering Performance
Public leaderboards (coding ability benchmarks, software engineering task benchmarks, user-voted arenas, and so on) offer broad coverage and strong comparability, but they have three limitations:
- Training data contamination: problems may already be in the training corpus, so a high score does not mean generalization ability.
- Task distribution bias: general algorithm problems differ greatly from legacy code in business repositories, internal frameworks, and specific coding conventions.
- Scenario disconnect: a high score on single-function generation does not mean the same reliability on tasks that require multiple tool calls and cross-file changes.
So leaderboards are good for narrowing down candidate scope, not for making the final decision.
4. Book Cost Isn’t Real Cost
Model pricing often lists only input and output unit prices, but the actual bill also depends on: the context length consumed by code completion, the number of tool-call rounds in multi-step tasks, the number of retries after failures, and the prefix-cache hit rate.
II. The Core Framework of a Coding Plan
A complete Coding Plan can be viewed as a pipeline:
Task grading → candidate filtering → private evaluation → weighted decision → portfolio orchestration → deployment monitoring → regression iteration
Each of the six stages has clear inputs and outputs:
- Task grading: define quantifiable acceptance criteria for each task type based on complexity, latency requirements, and code sensitivity.
- Candidate filtering: narrow down candidate models based on public information to form a to-be-verified list, avoiding a large upfront evaluation investment.
- Private evaluation: build an evaluation set from the team’s real code and run standardized tests on each candidate model.
- Weighted decision: combine capability scores, latency, cost, and compliance requirements to compute a composite score, then determine the primary and backup models.
- Portfolio orchestration: encapsulate model calls uniformly at the application layer, route to different models by task characteristics, and design failure fallback.
- Deployment monitoring: collect quality, performance, and cost metrics, catch problems early, and feed them back into the evaluation set.
III. Step 1: Task Grading and Capability Dimensions
1. Grade Tasks and Define Acceptance Criteria
Start by breaking coding needs into 3–4 task levels, and define machine-verifiable acceptance conditions for each level:
| Level | Typical Task | Acceptance Method | Key Metrics |
|---|---|---|---|
| L1 | Line-level completion, snippet generation | Syntax check, compile pass | Completion acceptance rate, time-to-first-token |
| L2 | Single-function implementation, unit test writing | All automated tests pass | First-pass rate, average retries |
| L3 | Cross-file bug fixing, local refactoring | All tests pass with no regressions | Task completion rate, reasonableness of change scope |
| L4 | Multi-step engineering tasks (e.g., fixing build failures) | End-to-end success, human review | Tool-call accuracy, total time, total cost |
The point of grading is that different levels can use different models, different context strategies, and different budget caps, avoiding a one-size-fits-all approach.
2. Six Core Capability Dimensions
- Code correctness: not just “looks right” but passes compilation and tests. For L2 and above, use the automated test pass rate as the primary metric, supplemented by the ratio of consistent results across repeated generations (commonly measured with metrics such as Pass@k and Pass^k), plus acceptance rate in human review.
- Repository-level understanding: real changes often span multiple files, so the model needs to locate relevant modules, understand call relationships, and keep interfaces compatible after changes. Beyond context-window length, focus on effective-context utilization and on whether the model can accurately reference existing code.
- Multi-step planning and tool calling: models for complex tasks need to break problems into steps, read and write files, run commands, and view test output in a controlled environment, then adjust the plan based on results. Evaluation focuses on task completion rate, tool-selection accuracy, the number of times it gets stuck in loops, and the average number of steps.
- Latency and throughput: code completion is extremely sensitive to time-to-first-token, since slow generation directly interrupts the input rhythm; complex tasks care more about end-to-end time. Also assess throughput under concurrency and whether the model can maintain stable output speed.
- Cost controllability: beyond unit price, check whether long context supports prefix caching, how cached tokens are billed, and whether the vendor’s free or low-cost coding subscription plans offer reasonable rate limits and context caps.
- Security, compliance, and engineering integration: code is a core enterprise asset. Whether the model service supports “data not used for training,” whether it offers content filtering and audit logs, and whether it supports private deployment all directly affect the selection. For integration, look for APIs compatible with mainstream interface protocols, structured output capability, and easy integration into IDEs, CLIs, and CI pipelines.
IV. Step 2: Building a Private Evaluation Set
1. Data Sources
Public leaderboards can only serve as initial screening. What truly reflects team needs is a private evaluation set built from your own codebase, with sources including:
- Historical fix commits: from version-control history, pick bug fixes with clear problem descriptions, using the pre-fix code state as input and the post-fix test results as the pass criterion.
- Code review comments: turn refactoring suggestions, naming improvements, and performance-improvement requests from reviews into task descriptions.
- Internal tickets and production incidents: close to real pain points, but they need desensitization.
- Synthesized difficulty samples: deliberately design error-prone scenarios such as boundary conditions, concurrency, and exception handling to avoid an overly simple evaluation set.
2. Task Card Structure
Each evaluation task should be described as a structured file for automatic execution and version management:
{"id": "bugfix-0231","level": "L3","language": "Go","context_files": ["internal/billing/invoice.go", "internal/billing/invoice_test.go"],"instruction": "When the same customer concurrently creates two invoices within the same second, the numbers become duplicated. Please locate and fix the issue.","acceptance": {"command": "go test -race ./internal/billing/...","expected": "exit_code == 0 and no data race warnings"},"constraints": {"max_steps": 20,"max_cost_units": 5.0}}
3. Execution Flow
import jsonimport subprocessimport timeMODEL_REGISTRY = {"candidate-a": {"client": "adapter_a", "params": {"temperature": 0.0}},"candidate-b": {"client": "adapter_b", "params": {"temperature": 0.0}},}def evaluate(model_id: str, tasks: list[dict], repeats: int = 3) -> dict:model = MODEL_REGISTRY[model_id]results, latencies, costs = [], [], []for task in tasks:for _ in range(repeats):started = time.monotonic()submission, usage = model["client"].solve(task, **model["params"])latencies.append(time.monotonic() - started)costs.append(usage["cost_units"])passed = subprocess.run(task["acceptance"]["command"],shell=True, capture_output=True,cwd=submission["workspace"], timeout=300,).returncode == 0results.append({"task": task["id"], "level": task["level"],"passed": passed, "steps": submission["steps"],})return {"model": model_id,"pass_rate": sum(r["passed"] for r in results) / len(results),"p95_latency_s": sorted(latencies)[int(len(latencies) * 0.95) - 1],"avg_cost": sum(costs) / len(costs),"results": results,}
4. Implementation Notes
- Strict isolation: evaluation tasks and their reference answers must not appear in any model’s training data. Prefer code produced after a release, or internal code.
- Blind comparison: if using anonymous models, have reviewers score without knowing the source to reduce brand bias.
- Difficulty layering: keep both basic tasks (to expose weaknesses) and hard tasks (to separate candidates).
- Moderate scale: 30–50 tasks per level is enough for stable discrimination; keep adding over time.
- Version management: put the evaluation set under version control and evolve it alongside the code.
V. Step 3: Weighted Scoring and Decision
1. Scoring Model
First normalize each dimension to 0–1, then assign weights per task level. The table below shows example weights that you can adjust to your team’s situation:
| Dimension | Example Weight | Normalization |
|---|---|---|
| Task pass rate | 40% | Tasks passed / total tasks |
| Stability | 20% | Ratio of consistent results across repeats |
| Latency | 15% | Measured value / latency cap for that level |
| Cost | 15% | Lowest cost / this model’s cost |
| Compliance | 10% | Mapped to 0–1 after checking each item on the compliance checklist |
WEIGHTS = {"pass_rate": 0.40, "stability": 0.20,"latency": 0.15, "cost": 0.15, "compliance": 0.10}def normalize(values: dict[str, float], higher_is_better: dict[str, bool]) -> dict[str, float]:out = {}for name, value in values.items():lo, hi = min(value.values()), max(value.values())if hi == lo:out[name] = 1.0else:norm = (value - lo) / (hi - lo)out[name] = norm if higher_is_better[name] else 1.0 - normreturn outdef rank_candidates(candidates: list[dict]) -> list[dict]:"""Each item in candidates looks like:{"id": ..., "pass_rate": ..., "stability": ..., "latency_ms": ...,"cost": ..., "compliance": ...}"""raw = {k: {c["id"]: c[k] for c in candidates} for k in WEIGHTS}higher = {"pass_rate": True, "stability": True, "latency": False,"cost": False, "compliance": True}norm = normalize(raw, higher)for c in candidates:c["score"] = sum(WEIGHTS[k] * norm[k][c["id"]] for k in WEIGHTS)return sorted(candidates, key=lambda c: c["score"], reverse=True)
2. Interpreting Results
- Veto power: models that fail a compliance item do not proceed to comparison, no matter how high their composite score.
- Level fit: the top overall scorer is not necessarily best for every level. Completion scenarios should be won by a model with a higher latency weight; complex refactoring scenarios should be won by a model with a higher pass-rate weight.
- Pareto view: if model A beats model B on both quality and cost, B can be eliminated directly, without relying on the weighted total.
VI. Step 4: Cost Estimation and Portfolio Routing
1. Estimating Single-Call Cost
After getting the candidate list, estimate per-call cost with the formula below, then cross-check it against measured data:
def estimate_call_cost(n_files: int, avg_file_tokens: int,out_tokens: int, price_in: float, price_out: float,cache_hit_ratio: float = 0.0, cache_price_factor: float = 0.0,retries: int = 0, price_in_cache: float | None = None,retry_ratio: float = 1.0) -> float:"""All prices are converted to per-token unit prices; the default values below only demonstrate the calculation logic.cache_hit_ratio: ratio of input tokens that hit the prefix cachecache_price_factor: multiplier of the original price applied to tokens that hit the cacheretries: average number of retries per taskprice_in_cache: input unit price for cached tokens; if unspecified, calculated as the original price times the factorretry_ratio: token-volume multiple of a retry request relative to the first request"""input_tokens = n_files * avg_file_tokensp_cache = price_in_cache if price_in_cache is not None else price_in * cache_price_factorbilled_in = (1 - cache_hit_ratio) * price_in + cache_hit_ratio * p_cachecost = input_tokens * billed_in + out_tokens * price_outreturn cost * (1 + retries * retry_ratio)if __name__ == "__main__":# Example: 3 relevant files, ~1200 tokens each, 1500 output tokens,# input price 2.0, output price 8.0 (unit: currency per million tokens),# cache hit 60% billed at 10% of the original price, average 0.3 retriesunit = 1e-6base = estimate_call_cost(3, 1200, 1500, 2.0 * unit, 8.0 * unit)cached = estimate_call_cost(3, 1200, 1500, 2.0 * unit, 8.0 * unit,cache_hit_ratio=0.6, cache_price_factor=0.1, retries=0.3)print(f"no cache, no retries: {base:.6f} per call")print(f"with cache + retries: {cached:.6f} per call")
For high-frequency scenarios like code completion, also pay attention to: the context length carried by each completion request, the ratio of completions users accept, and the call rate and context caps allowed by subscription plans at different price points. These factors together determine the true unit cost.
2. Portfolio Routing Strategy
In most scenarios, “one model to rule them all” is not optimal. A common approach is to combine models by task level:
- L1 completion: route to the lowest-latency fast or lightweight model, focusing on time-to-first-token and throughput.
- L2 function generation: route to a mid-tier model with balanced cost-performance, with syntax checks and automated tests as post-validation.
- L3/L4 complex tasks: route to the most capable flagship or reasoning model, with a more generous time and cost budget.
- Failure fallback: automatically switch to a backup model when the primary times out, gets rate-limited, or fails repeatedly.
class LLMError(Exception):passROUTING_RULES = [{"match": lambda t: t.level == "L1", "model": "fast-model"},{"match": lambda t: t.level in ("L2", "L3"), "model": "balanced-model"},{"match": lambda t: t.level == "L4", "model": "flagship-model"},]FALLBACK_CHAIN = ["balanced-model", "fast-model"]class ChatClient:def __init__(self, registry):self.registry = registrydef chat(self, model_id, messages, **kwargs):client = self.registry.get(model_id)if client is None:raise LLMError(f"unknown model: {model_id}")return client.chat(messages, **kwargs)def route(client: ChatClient, task) -> str:model = next((r["model"] for r in ROUTING_RULES if r["match"](task)), "balanced-model")for candidate in [model, *FALLBACK_CHAIN]:if candidate == model or candidate not in ROUTING_RULES and False:pass# Try the primary model and then each model in the fallback chain, in orderfor candidate in [model, *FALLBACK_CHAIN]:try:return client.chat(candidate, task.messages, **task.params)except LLMError:continueraise RuntimeError("all candidate models failed to respond")
Note: ChatClient is a thin wrapper over the model-call interface. Teams can implement a single client that is compatible with mainstream interface protocols, keeping model names and parameters in a config file so as not to couple a specific vendor into business code.
VII. Step 5: Context and Tool-Call Design
Model capability is only the upper bound; context and tool design determine the lower bound. Regardless of which model you use, these points belong in a Coding Plan:
- Precise retrieval, not bulk stuffing: use retrieval to put only relevant files, type definitions, and call chains into the context, improving hit quality while reducing token consumption.
- Structured prompts: clearly specify the task background, input/output format, constraints, and acceptance method to reduce the model’s guesswork.
- Sandboxed execution: generated code should run in a container or isolated environment with limited network and filesystem permissions, preventing accidental modifications or execution of risky commands.
- Test-driven validation: make compilation, static checks, and unit tests an automated validation loop; do not rely on the model’s “claim that it’s done.”
- Failure-feedback retries: feed error messages and failure reasons back to the model so it can fix based on feedback instead of regenerating from scratch.
def run_task(engine, task, max_rounds: int = 3):for round_idx in range(max_rounds):feedback = task.context if round_idx == 0 else task.last_errorpatch = engine.solve(task, feedback=feedback)result = task.validate(patch) # compile + static check + testsif result.passed:return {"success": True, "rounds": round_idx + 1, "patch": patch}task.last_error = result.summary # compressed error summary to avoid context bloatreturn {"success": False, "rounds": max_rounds, "patch": None}
VIII. Step 6: Deployment Monitoring and Continuous Iteration
A Coding Plan is not a one-time document but a continuously running loop:
- Quality metrics: completion acceptance rate, test pass rate, human rework rate.
- Performance metrics: time-to-first-token, end-to-end time (watch both P50 and P95).
- Cost metrics: cost per task, monthly total spend, cache hit rate.
- Regression mechanism: after each model upgrade, automatically rerun the private evaluation set and compare metrics against the previous version to prevent “regression after upgrade.”
When a new model version is released, just add it to the candidate list and run the evaluation flow to quickly decide whether the routing config needs adjusting.
IX. Common Pitfalls
- Looking only at leaderboard rankings: ignoring your own task distribution leads to a gap between measured and expected results.
- Blindly chasing ultra-long context: more tokens mean higher latency and cost, and irrelevant information also interferes with judgment.
- Ignoring long-context quality decay: a model’s ability to use information in the middle of a very long input is often noticeably weaker than at the beginning and end.
- Ignoring hidden costs: retries, tool-call rounds, and human review time should all count toward total cost.
- Lacking observability: unable to pinpoint whether the problem lies in the prompt, the context, or the model itself.
- Underestimating compliance risk: sending un-desensitized business code to external services can create data-leak risks.
X. Conclusion
The pace of model iteration won’t slow down. Rather than chasing the “strongest model right now,” build your own Coding Plan: use task grading to define requirements, private evaluation to quantify capability, portfolio routing to balance latency and cost, and monitoring with regression to ensure long-term stability.
Baidu AI Cloud has long emphasized bringing cloud and intelligence together, deeply integrating AI capabilities with cloud computing infrastructure. The same idea applies to coding scenarios: the model is only one part of the capability, and only by embedding it into a complete cloud engineering system—container platforms, object storage, logging services, monitoring and alerting—can it truly become measurable, governable productivity.
