Model Selection and Coding Plans for AI-Assisted Programming

    This article explains how teams can move from ad hoc LLM choices to a repeatable coding plan. It covers task classification, model evaluation across correctness, project understanding, context handling, latency and throughput, and cost; a reusable benchmark framework; phased rollout; fallback and monitoring; security and compliance requirements; and common pitfalls to avoid.

    1. Why a Systematic Coding Plan Is Needed

    More and more teams are integrating large language models into editors, code review, and test generation. Model selection, however, is often based on intuition: a model performs well in one demo and is rolled out everywhere, or it fails once and is rejected entirely. The costs of this approach are not always obvious. They include the learning cost of frequent switching, rework caused by unstable output, and emergency procurement after quota overruns.

    A coding plan means clarifying the following before writing code: how tasks will be split, which model combinations will be used, what acceptance criteria will apply, what the budget ceiling is, and how to fall back when a model fails. It turns “which model should we use” from a one-time decision into an engineering decision that can be reviewed and iterated.

    2. Define Tasks First, Then Compare Models

    The first step in model selection is task classification. Different development activities place very different demands on model capabilities:

    • Code completion: emphasizes low latency; context mainly comes from code near the cursor.
    • Function-level generation: requires understanding function signatures, comments, and call patterns, with high requirements for syntactic correctness.
    • Cross-file refactoring: depends on understanding project structure and requires longer context and stable multi-step reasoning.
    • Defect localization and repair: requires reading logs, understanding reproduction steps, and providing a verifiable patch.
    • Test generation and code review: focuses on covering boundary conditions and identifying potential risks.

    For each task type, teams should write a one-sentence description, input form, expected output, and acceptance method. If a task type cannot be described with clear acceptance criteria, there is no way to judge which model is more suitable for it.

    3. Five Evaluation Dimensions

    1. Correctness

    Correctness is the most fundamental metric. Check whether generated code passes compilation or interpreter checks, whether it passes existing unit tests, and whether it introduces new boundary errors. The gap between “looks right” and “runs and produces correct results” is often large, so evaluation should be based on execution results.

    2. Engineering Understanding

    Real projects rarely contain isolated functions. A model needs to recognize directory conventions, dependency versions, naming styles, and existing abstraction layers. One effective approach is to ask the model to complete a small requirement in a real repository, then observe whether it reuses existing utility functions or reimplements them. The former indicates that the model understands the project; the latter creates duplicate code and maintenance burden.

    3. Context Management

    Context window size is only one parameter. More important is whether the model can accurately use information located in the middle of a long context. A simple test can be designed: place constraints at the beginning and end of a long file, ask the model to modify code in the middle according to those constraints, and then count how many constraints were missed.

    4. Response Speed and Throughput

    Interactive scenarios are sensitive to first-token latency, while batch processing scenarios care more about total throughput. The two should be measured separately. When measuring, record the network environment, concurrency level, and input length; otherwise, data collected at different times and under different conditions cannot be compared.

    5. Cost and Quota

    Cost includes the charge per call, additional consumption caused by retries, and human review time. A model with a low unit price but frequent revisions may not have a lower total cost. It is recommended to use “average cost per accepted task” as a unified measure so that different models can be compared under the same standard.

    4. Build a Reusable Evaluation Benchmark

    Without evaluation, model selection is guesswork. The following script provides an evaluation framework that is independent of any specific service. It reads a set of cases, sends each prompt to a candidate model to generate code, runs tests in a temporary directory, and finally summarizes the pass rate and latency.

    1. import subprocess
    2. import tempfile
    3. import time
    4. from pathlib import Path
    5. def call_model(model_name: str, prompt: str) -> str:
    6. """Unified model invocation interface. The concrete implementation depends on the service the team uses and is left blank here."""
    7. raise NotImplementedError
    8. def run_tests(code: str, test_code: str, timeout: int = 10) -> bool:
    9. """Run generated code and tests in a temporary directory; return True if all pass."""
    10. with tempfile.TemporaryDirectory() as tmp:
    11. Path(tmp, "solution.py").write_text(code, encoding="utf-8")
    12. Path(tmp, "test_solution.py").write_text(test_code, encoding="utf-8")
    13. try:
    14. result = subprocess.run(
    15. ["python", "-m", "unittest", "discover", "-s", tmp],
    16. cwd=tmp,
    17. capture_output=True,
    18. timeout=timeout,
    19. )
    20. return result.returncode == 0
    21. except subprocess.TimeoutExpired:
    22. return False
    23. def evaluate(model_name: str, cases: list[dict]) -> dict:
    24. """Each case contains prompt and tests fields; return pass rate and median latency."""
    25. passed, latencies = 0, []
    26. for case in cases:
    27. start = time.perf_counter()
    28. code = call_model(model_name, case["prompt"])
    29. latencies.append(time.perf_counter() - start)
    30. if run_tests(code, case["tests"]):
    31. passed += 1
    32. latencies.sort()
    33. return {
    34. "model": model_name,
    35. "pass_rate": passed / len(cases),
    36. "p50_latency_s": latencies[len(latencies) // 2],
    37. }

    When using this framework, keep several points in mind:

    • Generated code itself should not be trusted. Run it in a container or sandbox isolated from the production network, and restrict file system and process permissions. The temporary directory above can isolate files only; it cannot isolate malicious behavior.
    • The same model may produce inconsistent output for the same prompt. Run the evaluation repeatedly and use statistical values rather than relying on a single result.
    • Use enough cases. When there are too few samples for each task type, differences in pass rates may simply be random fluctuation.
    • Cases should come from the team’s real historical requirements, not generic problems found online. Real cases better reflect the team’s code style and business constraints.

    5. Phased Rollout Process

    The first phase is a small-scale pilot. Select two or three candidate models, run evaluations on low-risk tasks, and observe the distribution of pass rates, revision counts, and latency.

    The second phase is a canary rollout. Make models that pass evaluation available to part of the team or a single code repository, and record the adoption rate, meaning the proportion of generated results that developers accept directly.

    The third phase is continuous monitoring. Record fallback counts, online defect counts, and cost per task, and re-evaluate once a quarter because model version updates can change behavior.

    The fourth phase is establishing a fallback mechanism. When the primary model is unavailable or its quality drops significantly, the system should automatically switch to a backup model while retaining a manual switch that allows the team to temporarily disable automatic generation.

    6. Security and Compliance Requirements

    • Prompts must not contain keys, customer data, or undisclosed internal interfaces. Redact sensitive information before calls and mask sensitive fields in logs.
    • Model-generated code must undergo human review and static analysis before it can be merged into the main branch.
    • Data retention policies must be consistent with the service provider’s terms and written into the team’s development guidelines.
    • Evaluation sandboxes should be strictly isolated from production environments to prevent generated code from accessing internal resources or external networks.

    7. Common Pitfalls

    1. Replacing systematic evaluation with a single demo. Demos usually select the most ideal cases and cannot reflect overall quality.
    2. Looking only at pass rates while ignoring revision counts and review time. A model with a high pass rate but a large amount of rework may not be more efficient in practice.
    3. Applying one set of general conclusions to all tasks. A model that performs well on completion tasks is not necessarily good at cross-file refactoring.
    4. Ignoring version changes. A model’s behavior may change after an upgrade, so previous evaluation conclusions need to be revalidated.
    5. Treating prompts as temporary text. Prompts should be version-controlled like code and maintained together with evaluation cases.

    8. Integration with Platform Capabilities

    Regardless of which model is selected, teams need a unified access layer, invocation logs, and evaluation records. The access layer can abstract away differences in calling different services, logs can be used to calculate cost and latency, and evaluation records can be used to trace the basis for each model selection decision.

    When selecting models, teams can also include model services provided by Baidu AI Cloud in the same evaluation process and compare them with other options under the same test cases and acceptance criteria. Conclusions should come from the team’s own data, not from promotional materials.

    9. Summary

    • Define tasks and acceptance criteria before comparing models.
    • Evaluate models comprehensively across correctness, engineering understanding, context management, response speed, and cost.
    • Use a repeatable evaluation framework to produce data, and re-evaluate regularly.
    • Build security, compliance, and fallback mechanisms into the process rather than leaving them to individual judgment.