LLM API Selection in Practice: Cost, Coding Ability, and Evaluation Methods
A practical guide to selecting LLM APIs by comparing token costs, coding-task performance, latency, and format stability. It covers cost estimation, building a small evaluation set, engineering practices for credentials, retries, input reduction, output constraints, and data security, and provides an implementation checklist for ongoing evaluation.
1. Why Cost and Capability Should Be Evaluated Together
When independent developers and small teams choose an LLM API, they often look at the unit price first. A low unit price is attractive, but the actual cost of a call also depends on two factors: how many tokens each request consumes, and whether the model’s output passes on the first attempt without repeated calls.
If a model has a lower unit price but requires three rounds of prompt correction to produce usable code, its total cost may not be lower. Conversely, a higher-priced model that returns the correct result in one attempt may be more cost-effective overall. Therefore, selection should compare unit price, task completion rate, and response latency in the same table.
This article does not judge the price or capability of any specific provider. The methods described here apply to any model service compatible with a common chat interface format, and readers can replace the example parameters with their own data.
2. Understand the Basic Structure of Token Billing
Most LLM services bill by token and distinguish between input and output. Input tokens include the system prompt, conversation history, and user question; output tokens are the model-generated answer. The two prices are usually different, and output is generally priced higher than input.
This means the same task can vary significantly in cost under different designs. For example, putting an entire project’s code into every request will rapidly increase input tokens. Splitting the task and passing only relevant file snippets can significantly reduce input cost.
2.1 Estimate the Cost per Call
The following function estimates the cost of a single call. Unit price parameters should be obtained from the provider’s official pricing page and should be based on currently published prices.
def estimate_cost(input_tokens: int, output_tokens: int,price_in_per_million: float,price_out_per_million: float) -> float:"""Estimate the cost of a single call (in the same unit as the price, e.g., USD).price_*_per_million is the price per million tokens."""if input_tokens < 0 or output_tokens < 0:raise ValueError("Token counts cannot be negative")cost_in = input_tokens / 1_000_000 * price_in_per_millioncost_out = output_tokens / 1_000_000 * price_out_per_millionreturn cost_in + cost_out# Example: replace the unit prices with actual published pricestotal = estimate_cost(input_tokens=12_000,output_tokens=2_500,price_in_per_million=0.0, # Replace with the actual input priceprice_out_per_million=0.0, # Replace with the actual output price)print(f"Cost per call: {total:.6f}")
2.2 Estimate Monthly Cost by Task Volume
A single-call cost has limited meaning on its own; it needs to be combined with call frequency. Suppose a code review tool handles 200 requests per day, with an average of 8,000 input tokens and 1,500 output tokens per request. You can use the function above multiplied by the number of calls to obtain a monthly budget. It is advisable to keep at least a 20% margin for longer prompts, retries, and burst traffic.
3. How to Evaluate Coding Ability
Public benchmarks can reflect a model’s general level, but benchmark tasks often differ from the code style, dependencies, and business constraints of personal projects. A more reliable approach is to build your own small evaluation set.
3.1 Construct Evaluation Samples
Evaluation samples should cover several categories of tasks from real work:
- Feature implementation: write a function or module based on a requirements description.
- Bug fixing: provide error messages and related code, and ask the model to locate and modify the issue.
- Code refactoring: improve structure while preserving behavior.
- Test writing: generate unit tests for existing functions.
- Explanation and review: explain the logic of a piece of code and identify potential issues.
Prepare 10 to 30 samples for each category, and record reference answers or executable acceptance tests. The closer the samples are to real business scenarios, the more useful the evaluation results will be.
3.2 Design Quantifiable Metrics
Consider the following metrics:
- First-pass rate: the proportion of generated code that passes acceptance tests without modification.
- Average correction rounds: the number of interactions required to reach a usable state.
- Cost per task: total token cost including all retries.
- Response latency: the time from sending a request to receiving the complete result; percentiles are more useful than averages.
- Format stability: whether the output follows the expected structure, for example, whether it strictly returns the specified JSON fields.
Looking at a single metric can easily lead to misjudgment. For example, a model with the highest first-pass rate may have very long latency, which can lead to a poor experience in interactive scenarios.
3.3 A Simple Evaluation Framework
The following script shows the skeleton of an evaluation workflow. It reads the API base URL and key from environment variables to avoid hardcoding credentials in the code.
import osimport timeimport jsonimport requestsAPI_BASE_URL = os.environ["MODEL_API_BASE_URL"]API_KEY = os.environ["MODEL_API_KEY"]MODEL_NAME = os.environ.get("MODEL_NAME", "your-model-name")def call_model(prompt: str, timeout: int = 60) -> dict:headers = {"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json",}payload = {"model": MODEL_NAME,"messages": [{"role": "user", "content": prompt}],}start = time.perf_counter()resp = requests.post(f"{API_BASE_URL}/chat/completions",headers=headers,data=json.dumps(payload),timeout=timeout,)resp.raise_for_status()latency = time.perf_counter() - startbody = resp.json()return {"text": body["choices"][0]["message"]["content"],"usage": body.get("usage", {}),"latency": latency,}def run_case(case: dict) -> dict:"""case contains two fields, prompt and check; check is an acceptance function that returns a boolean."""result = call_model(case["prompt"])passed = case["check"](result["text"])return {"passed": passed,"latency": result["latency"],"usage": result["usage"],}
The acceptance functions in the script should use executable tests where possible, such as running the generated code and checking the output, rather than relying on subjective manual scoring. Manual judgment can be used as a supplement to evaluate readability and style.
4. Engineering Considerations for Integration
4.1 Credential Management
Keys should be stored in environment variables or a dedicated secret management service, not written into source code or logs. Before committing code, check whether the repository contains credential files. Teams can assign independent keys to different projects to facilitate auditing and rotation.
4.2 Timeouts, Retries, and Backoff
Both network requests and model services can experience transient failures. Set explicit timeouts, use exponential backoff retries for rate limiting and server errors, and limit the maximum number of retries. Retries increase token consumption and need to be included in cost evaluation.
4.3 Reduce Input Cost
The following practices can effectively control input tokens:
- Pass only code snippets relevant to the task, not the entire repository.
- Summarize conversation history to avoid unbounded context accumulation.
- Keep fixed system instructions short, and place reusable content in a unified location.
- Cache results for identical questions to avoid repeated billing.
4.4 Output Constraints
Specify the output format in the prompt, for example, requiring only a code block or JSON with a specified structure. This can reduce parsing failures and subsequent correction overhead. Output length should also be capped to prevent the model from generating more content than needed.
5. Data and Security Considerations
When calling models through third-party aggregation APIs or middleware, extra attention should be paid to data security. Code, business data, and user information may be recorded or used for other purposes when passing through an intermediate service, so you should:
- Read the provider’s data retention and usage terms, and confirm whether request content is logged.
- For businesses involving sensitive information, desensitize the data before sending it to the model.
- Evaluate the service’s availability commitments and failure handling to avoid single points of dependency in critical workflows.
- For free trial quotas, pay attention to their validity period and restrictions, and do not treat trial-stage pricing as long-term cost.
6. Common Pitfalls
First, treating public benchmark scores directly as an indicator of capability for your own business. Benchmark tasks differ significantly from real projects, so your own evaluation set should be the reference.
Second, comparing only unit prices. Ignoring retry counts, context length, and correction rounds can easily lead to incorrect cost conclusions.
Third, treating one successful case as stable performance. LLM outputs have randomness, so the same prompt should be run multiple times and the pass rate should be counted.
Fourth, ignoring migration cost. If business code is deeply coupled to the details of a particular interface, switching models may require substantial rework. Add a thin abstraction at the call layer, and put the model name, address, and parameters into configuration.
7. Implementation Checklist
- Define task types and list the five to ten most common real scenarios.
- Prepare an automatically acceptable sample set for each scenario.
- Run the same evaluation on candidate models and record pass rate, cost, latency, and format stability.
- Use the cost function in this article to estimate the monthly budget and reserve a margin.
- Put the API address, key, and model name into configuration to facilitate switching and rollback.
- Re-evaluate periodically because model versions and prices may change.
Selection is not a one-time decision. By making evaluation and cost accounting routine processes, teams can continuously find the right balance among capability, price, and stability.
