LLM Model Selection and AI Agent Implementation Practices for R&D
Selecting the right Large Language Model (LLM) is a critical engineering decision that directly impacts R&D efficiency. This article explores four core evaluation dimensions—inference speed, cost structure, context management, and tool-calling stability—and introduces a layered architecture that separates planning from execution. It also outlines how to build a reproducible evaluation pipeline and highlights key risk control measures for securely implementing AI agents in development workflows.
Why LLM Model Selection is Critical for R&D Efficiency
Large Language Models (LLMs) are now deeply integrated into daily R&D operations, including code generation, documentation, and test creation. The challenge for teams has shifted from “can we use it” to “which one should we use and in what scenario.” When the same set of tasks is handed to different models, the differences in completion speed, cost per run, long-context handling, and tool-calling stability are often significant. Without a systematic evaluation method, teams tend to switch models based on intuition, leading to either uncontrollable expenses or inconsistent output quality.
Therefore, model selection should be treated as an engineering decision rather than a one-time procurement choice. It requires clear evaluation dimensions, reproducible test sets, and a continuous re-testing mechanism.
Four Core Evaluation Dimensions
2.1 Inference Speed
Speed is typically measured by two metrics: output throughput (tokens generated per second) and time to first token (TTFT), which determines how long a user waits for initial feedback. For programming tasks, the impact of speed is magnified. A single code modification involving a dozen rounds of tool calls can accumulate significant waiting time, even if only a few seconds are saved per round.
However, speed cannot be the sole basis for selection. A fast model might require more correction rounds for complex reasoning, meaning the total end-to-end time might not actually be shorter. Evaluation should prioritize the “end-to-end task completion time” rather than just raw throughput numbers.
2.2 Cost Structure
Model billing is generally divided into three parts: input, output, and cache hits, each with different unit prices. Output tokens are usually more expensive, so having the model generate lengthy explanations will noticeably drive up costs. Prompt caching is suitable for repetitive content, such as fixed system prompts, coding standards, and project background descriptions.
Teams should estimate the cost per typical task and factor in the internal tokens generated during the model’s reasoning process. Looking only at the list price while ignoring actual consumption is a common cause of budget overruns.
2.3 Context Length and Information Organization
The context window determines how much code and documentation a model can process at once. A larger window does not equate to better results; the key lies in retrieval and trimming strategies. Stuffing an entire code repository into the context dilutes the model’s attention to key information and increases both latency and cost.
A more robust approach is to first locate the relevant files, supplement the context based on dependency relationships, and finally retain only the snippets directly related to the current task. This controls costs while allowing the model to focus its attention on the parts that genuinely need modification.
2.4 Tool-Calling Stability
Coding agents rely on function calls to read files, run tests, and submit changes. Evaluation should focus on three types of metrics: the accuracy of parameter formatting, error recovery capability, and the absence of meaningless repetitive calls.
A model that performs exceptionally well in a single-turn dialogue might not maintain state consistency in long-chain tool calls. Therefore, tool-calling evaluation should be conducted within a complete task workflow rather than just testing isolated calls.
Layered Collaboration: Separating Planning and Execution
For complex tasks, work can be split into two layers. The planning layer is responsible for understanding requirements, breaking down steps, defining the scope of changes, and setting acceptance criteria; this layer requires strong reasoning capabilities. The execution layer is responsible for writing code according to the plan, running checks, and reporting results; this layer prioritizes speed and cost.
The value of this structure is that it concentrates expensive reasoning capabilities where they are needed most, while delegating large volumes of repetitive execution work to faster, cheaper models.
Tasks suitable for the planning layer include:
- Requirements involving multiple modules with unclear change boundaries;
- The need to design interfaces or adjust data structures;
- Situations with multiple feasible solutions requiring trade-offs.
Tasks suitable for the execution layer include:
- Adding unit tests according to established specifications;
- Renaming variables or standardizing code style;
- Fixing local issues based on clear error messages.
The example below illustrates a simple routing concept. The model names are placeholders; in actual use, they should be managed via configuration files and replaced with the model identifiers your team has integrated.
from dataclasses import dataclass@dataclassclass TaskSpec:goal: strcomplexity: str # "low" | "medium" | "high"needs_long_context: bool# Model identifiers are placeholders and should be read from a config fileMODEL_CONFIG = {"planner": "planner-model","executor": "executor-model","long_context": "long-context-model",}def route_model(task: TaskSpec) -> str:"""Selects the model tier based on task characteristics."""if task.complexity == "high":return MODEL_CONFIG["planner"]if task.needs_long_context:return MODEL_CONFIG["long_context"]return MODEL_CONFIG["executor"]
In a real-world system, routing rules must also consider budget limits, retry counts upon failure, and human review checkpoints. The simpler the routing logic, the easier it is to test and maintain.
Building a Reproducible Evaluation Pipeline
Without evaluation data, model selection relies solely on subjective impressions. A reliable evaluation pipeline typically includes the following steps:
- Build an Evaluation Set: Extract real tasks from historical tickets and code review records, covering various difficulties and modules. Start with a few dozen tasks and expand gradually.
- Define Scoring Criteria: Common metrics include test pass rate, code review pass rate, rework rounds, whether the number of changed lines is reasonable, and whether new defects are introduced.
- Record End-to-End Data: Simultaneously record latency and cost, and tally the number of tool calls consumed per task.
- Run Multiple Times for Statistical Values: Model outputs have a degree of randomness; a single run is insufficient. Run multiple times and use the median or mean.
- Re-evaluate Periodically: Model versions update frequently, and the same model may perform differently over time. Set a fixed cycle for re-testing and re-evaluate routing rules when versions change.
Evaluation results should be saved as structured data to facilitate cross-time comparisons. Below is an example of a recording format:
from dataclasses import dataclass, asdictimport json@dataclassclass EvalRecord:task_id: strmodel: strpassed_tests: boolreview_rounds: intlatency_seconds: floatcost_usd: floatdef save_records(records: list[EvalRecord], path: str) -> None:with open(path, "w", encoding="utf-8") as f:json.dump([asdict(r) for r in records], f, ensure_ascii=False, indent=2)
Risk Control in Implementation
Because agents can read and write code and execute commands, security and compliance must be prioritized. Key measures include:
- Minimum Privilege: Agents should only be granted the repository and environment permissions strictly necessary to complete the task. Production environment credentials should not be shared.
- Key Isolation: Access tokens and passwords should be injected via environment variables or a secret management service, never written into code or exposed in the model’s context.
- Sensitive Information Masking: Before sending logs or data snippets to the model, remove personal information and internal identifiers.
- Human Review: Changes involving core modules, security logic, or database structures must undergo human review before merging.
- Operation Auditing: Log every tool call and file modification made by the agent for post-hoc traceability.
- Cost Alerts: Utilize standard monitoring and alerting capabilities to set thresholds for daily expenses and abnormal API call volumes.
Implementation Recommendations
Teams can proceed in the following order:
Step 1: Establish an evaluation set and scoring criteria to confirm the baseline performance of the current solution using real tasks.
Step 2: Design layered routing rules based on evaluation data. Trial these rules first on low-risk tasks, such as adding tests and formatting code.
Step 3: Gradually expand coverage while retaining human review checkpoints. With each expansion, re-evaluate quality and cost.
Step 4: Establish a periodic re-testing mechanism, incorporating model version changes into routine checks.
There is no one-size-fits-all answer to model selection. What teams truly need is a continuously running evaluation mechanism that supports every model switch with data, ensuring that the agent’s output maintains a controllable balance among speed, cost, and quality.
