LLM API Selection Guide: How to Systematically Evaluate Cost and Performance
Public leaderboards can provide direction, but they rarely answer whether a model fits a specific workload. This guide outlines a practical evaluation process for LLM APIs, covering task decomposition, test set design, single-call and effective cost calculation, automated pass/fail checks, stability metrics, integration constraints, and a phased migration plan with rollback. It ends with an implementation checklist for making selection decisions based on your own test data rather than one-off rankings.
1. Why Leaderboards Alone Are Not Enough
Public leaderboards provide directional reference, but they rarely answer directly whether a model fits your business. There are three main reasons.
First, leaderboard tasks differ from real business work. Leaderboards mostly use standardized questions, while actual projects often involve historical code constraints, team naming conventions, incomplete requirement descriptions, and similar issues.
Second, evaluation settings are usually not transparent. Model version, sampling parameters, prompt templates, and whether tool calling is allowed can all significantly affect results. The same model can produce very different scores under different settings.
Third, versions iterate quickly. Today’s ranking may change within a few weeks, so a one-time conclusion can quickly become outdated.
Therefore, a more reliable approach is to break evaluation into your own testing process and draw conclusions from your own data and metrics. In general, you need to cover five dimensions: task effectiveness, cost per call, stability, integration convenience, and usage limits.
2. Decompose Tasks Before Choosing a Model
Independent developer workloads usually fall into several categories:
- Code generation and refactoring: write functions based on requirements, modify existing modules, and eliminate duplicate logic.
- Documentation generation: generate documentation, changelogs, and usage examples from code or interface definitions.
- Data processing scripts: clean data, convert formats, and write statistical or visualization scripts.
- Multi-step tool calling: the model needs to decide which interface to call next based on results and fill in parameters correctly.
Each task category should have its own test set. For each set, prepare 10 to 50 samples, and each sample should include an input plus an expected result or judgment method. Samples should preferably come from real historical tickets or daily requirements, and some uncommon edge cases should be kept.
Test sets should be stored separately from prompt templates so that inputs remain consistent when comparing different models later.
3. Cost Evaluation: Look Beyond Unit Price
API billing is usually calculated separately for input tokens and output tokens. The formula for the cost of a single call is:
Cost per call = input tokens × input unit price + output tokens × output unit price
Output unit prices are generally higher than input unit prices, so for tasks that generate long text or large blocks of code, the cost mainly comes from the output side.
Looking only at the cost per call is not enough. When model output fails to meet requirements, retries or manual corrections are needed, and that cost should also be included. Effective cost can be estimated as follows:
Effective cost per task = cost per call ÷ task success rate
Example (the following unit prices are hypothetical values for demonstration and are not real prices from any platform): suppose the input price is CNY 2 per million tokens and the output price is CNY 12 per million tokens. A task uses 30,000 input tokens and 2,000 output tokens, so the cost per call is:
0.03 × 2 + 0.002 × 12 = 0.06 + 0.024 = 0.084 CNY
If the task success rate is 80%, the effective cost per task is approximately 0.084 ÷ 0.8 = 0.105 CNY.
Also note the following when calculating:
- Different platforms may use different billing units, currencies, and billing cycles, so convert them to a common basis before comparison.
- If there are per-request fees, minimum spend, or concurrency fees, include them in the estimate.
- Free quotas should only be used for testing and should not be treated as a basis for long-term cost.
Example code:
def estimate_cost(input_tokens, output_tokens, price_in_per_m, price_out_per_m):"""Estimate single-call cost using price per million tokens; units match the price units."""return (input_tokens / 1_000_000) * price_in_per_m \+ (output_tokens / 1_000_000) * price_out_per_mdef effective_cost(single_cost, success_rate):"""Calculate effective cost per task after accounting for failed retries."""if success_rate <= 0:raise ValueError("Success rate must be greater than 0")return single_cost / success_rate
4. Capability Evaluation: Make Results Automatically Verifiable
Reading outputs manually is inefficient and easily affected by subjectivity. Therefore, try to design automated judgment methods for each task category:
- Code generation and refactoring: run unit tests and calculate the pass rate; add static checks such as code formatting and type checking when necessary.
- Data processing scripts: run scripts with fixed input data and compare outputs item by item against expected results.
- Documentation generation: check section structure, required fields, and whether code examples can be executed; then manually spot-check a small subset of samples.
- Multi-step tool calling: check whether each step’s interface name, parameter types, and required fields are correct, and verify the call order.
Below is a simple evaluation framework for counting pass rate, failure count, and response latency:
import timefrom dataclasses import dataclass, fieldfrom typing import Callable@dataclassclass Case:prompt: strcheck: Callable[[str], bool] # Receives model output; returns whether it passes@dataclassclass Report:passed: int = 0total: int = 0failures: int = 0latencies: list = field(default_factory=list)def run_eval(call_model: Callable[[str], str], cases: list[Case], repeat: int = 3) -> Report:"""Call each sample multiple times and aggregate pass rate, failures, and latency."""report = Report()for case in cases:for _ in range(repeat):report.total += 1start = time.perf_counter()try:output = call_model(case.prompt)except Exception:report.failures += 1continuereport.latencies.append(time.perf_counter() - start)if case.check(output):report.passed += 1return report
Two points require attention when using this. First, the same sample should be called multiple times because model outputs are random, and a single result is not enough to draw a conclusion. Second, test sets should be updated regularly to avoid inflated scores after samples are covered by model training data.
5. Stability Evaluation: Success Rate Matters More Than Peak Performance
Stability directly affects the online experience. Consider the following metrics:
- Call success rate: the proportion of requests that return valid results.
- Latency distribution: focus on P50 and P95; tail latency has a greater impact on interactive experience.
- Timeout and rate-limit ratio: observe whether rate limiting or timeouts occur frequently during peak hours.
- Format consistency: if JSON output is required, measure the proportion that can be parsed correctly.
Tests should cover different time periods because service load changes over time. It is advisable to run several rounds of tests in fixed time slots each day and observe for about a week before drawing conclusions.
6. Integration Convenience and Usage Limits
With the same model capability, integration costs can differ greatly. Use the following checklist during evaluation:
- Authentication: whether key management is simple and whether permissions can be isolated by project or environment.
- API specification: whether request and response structures are clear, error code meanings are explicit, and retries are easy.
- Context length: whether long documents or large codebases exceed the context limit.
- Rate and quota: whether requests per minute and daily token quotas meet business peaks.
- Data policy: whether request content is retained, for how long, and whether it meets project compliance requirements.
- Feature limits: whether required features such as streaming output, function calling, and structured output are supported.
These limits are usually stated in the service documentation. Check them item by item before selection rather than relying on impressions.
7. Migration Strategy: Canary Switching and Rollback
Even after evaluation results meet the criteria, switching everything at once is not recommended. A safer approach is to proceed in stages:
- Shadow testing: the new model and the existing model process the same batch of requests in parallel, recording results only without affecting production.
- Comparative analysis: compare pass rate, cost, latency, and human ratings to determine which task types are suitable for migration.
- Canary release: set ratios by task type and gradually increase traffic to the new model.
- Define rollback conditions: for example, automatically switch back to the original model when the success rate falls below a threshold, latency exceeds a limit, or cost per task exceeds budget.
The following code demonstrates proportional routing and keeps a rollback path when issues occur:
import randomROUTES = {"code_refactor": {"primary": "existing model", "candidate": "new model", "ratio": 0.10},"doc_generation": {"primary": "existing model", "candidate": "new model", "ratio": 0.30},}DEFAULT_ROUTE = {"primary": "existing model", "candidate": None, "ratio": 0.0}def pick_backend(task_type: str) -> str:"""Select a model by task type and canary ratio; unconfigured task types use the existing model."""route = ROUTES.get(task_type, DEFAULT_ROUTE)if route["candidate"] and random.random() < route["ratio"]:return route["candidate"]return route["primary"]
Canary ratios should be adjusted gradually based on evaluation data. After each adjustment, recheck success rate and cost to confirm that no unexpected changes have occurred.
8. Implementation Checklist
To complete a round of selection, follow this order:
- Split the business into several task types and build a test set for each type.
- Standardize prompt templates, sampling parameters, and judgment methods.
- Calculate cost per call and effective cost per task.
- Run repeated tests and record pass rate, failure count, and latency distribution.
- Verify integration specifications, rate quotas, and data policies.
- Migrate gradually through shadow testing and canary release, and set rollback conditions.
Following this process will make selection conclusions closer to real business needs. Public leaderboards can be used to narrow the candidate range, but the final decision should be based on your own test data.
