# Evaluating, Pricing, and Choosing LLMs for Coding: A Practical Guide

    This article walks through three steps for selecting a coding LLM: how to evaluate it, how to calculate its real cost, and how to choose the right model. By the end, you'll know how to build your own test set, estimate the true cost per task, and get ready-to-run API call code.

    1. How to Evaluate: Build Your Own Test Set First

    Leaderboard scores are useful as a reference, but they measure public problems that may not reflect your codebase. When selecting a model, pick benchmarks based on task type first, then make the final judgment with your own data.

    1.1 Tool Calling

    Tool calling determines whether a model can serve as the core of an AI agent: it must select the right functions, fill in parameters correctly, and call external APIs and databases. Two popular benchmarks focus on different aspects:

    Dimension BFCL tau-bench
    Main focus Function selection, parameter conformance to JSON Schema, multi-turn and parallel calls Calling tools according to business rules in multi-turn conversations, e.g., customer service scenarios
    Core metric Call accuracy pass^k — the proportion of attempts that succeed k times in a row
    Scope Best for checking format and semantic correctness of single calls Best for checking stability, but only within its simulated business scenarios

    These benchmarks use public APIs. Your internal API fields are usually more complex, so you should also write a batch of test cases using your own API definitions, covering missing parameters, invalid enum values, oversized parameters, and similar edge cases.

    1.2 Terminal Coding and Refactoring

    Real-world development is far more complex than algorithm puzzles. A model must understand cross-file dependencies, read legacy code, and debug in the command line.

    SWE-bench Verified contains 500 human-verified real GitHub issues; the metric is the proportion of model-generated patches that pass the tests. Terminal-Bench has the model complete tasks in a terminal environment and measures the task success rate.

    Both benchmarks are heavily influenced by the test framework and agent scaffolding. The same model can score noticeably differently with a different invocation setup. When citing benchmark data, record the following:

    • Source page and access date
    • Model name and version
    • Scaffolding name, tool set, temperature, max steps, and timeout settings
    • Whether the result is a single run or an aggregate of repeated runs

    1.3 Scientific Computing and Data Science Coding

    Scientific computing demands high algorithmic precision and correct library usage. SciCode covers research code generation in physics, chemistry, biology, mathematics, and materials science, reporting accuracy on both sub-problems and full problems. DS-1000 contains 1,000 data science problems involving Pandas, NumPy, SciPy, scikit-learn, and PyTorch, typically measured by pass@1 — the proportion of problems solved on the first generation.

    HumanEval’s pass@1 is still a basic reference for general coding ability, but most frontier models are near saturation on it, so it offers limited differentiation. In that case, consider benchmarks with continuously updated problem sets, such as LiveCodeBench, or simply use private test cases.

    1.4 Building a Private Regression Set

    A private regression set is the most reliable data for model selection. A good starting point is 50 to 200 real tasks drawn from your team’s past quarter, each containing:

    1. Input context — relevant files, error logs, and requirement descriptions
    2. Acceptance criteria — unit tests, API tests, or human scoring rubrics
    3. Task type labels — completion, refactoring, debugging, or documentation generation

    The closer the tasks are to your daily work, the more reliable the conclusions. Every time you switch models or change prompts, rerun the same set and record pass rate, average cost, and latency together.

    2. How to Calculate: Count Retries and Failures in the Cost

    2.1 Single-Call Cost Formula

    Billed separately by input and output tokens is now the mainstream pricing model. A single call can be estimated as:

    Single call cost = input tokens × input price + output tokens × output price

    The total cost per task must include every attempt — retries after failures and the multi-step calls made by agents:

    Total task cost = Σ (single call cost per attempt)

    Here’s a hypothetical example. Suppose input is priced at 1 currency unit per million tokens and output at 4. One call uses 50,000 input tokens and 2,000 output tokens, so the single-call cost is 0.05 + 0.008 = 0.058.

    Assume a 20% retry rate, meaning each task averages 0.2 extra calls. Under three assumptions — failed attempts are billed at full price for both input and output tokens, retries cost the same as the first call, and no cache hits — the average cost per task is 0.058 × 1.2 ≈ 0.070. If the provider only bills input tokens for failed requests, or if part of the input hits the cache, the result changes and must be recalculated under that provider’s billing rules.

    The prices above are illustrative only. Always check the provider’s official pricing page, and pay attention to the terms that apply to promotions, discounts, and tiered pricing.

    2.2 When Caching and Summarization Help — and When They Don’t

    Context caching suits scenarios where the prefix stays unchanged for a long time, such as system prompts, repo conventions, and rarely modified files. Most implementations require an exact prefix match; check the provider’s documentation for details. If every call has a different prefix, caching will almost never hit.

    Summarization preprocessing reduces input tokens but loses detail. It works well as background context, but not for directly generating code that needs to be modified. Rewritten code still must be verified through tests.

    2.3 Retry Risks and Backoff Strategy

    Rate limits, timeouts, and intermittent failures are common in production. The code below retries with exponential backoff on 429 and 5xx errors, prioritizing the server-provided Retry-After header.

    Two retry risks to consider up front:

    • Every retry may incur new charges. The server may have already processed a timed-out request even though the client never received the result.
    • If a tool the model calls has side effects — placing orders, sending messages, or writing to a database — retries can cause duplicate operations. Such calls should use idempotency keys first, or check task status before retrying.

    The code sets a maximum of 5 retries with a 30-second per-attempt wait cap. For errors like 400, 401, and 403, retrying will not succeed, so the exception is raised immediately.

    3. How to Choose: Decide Based on Cost, Stability, and Compliance

    3.1 Selection Dimensions

    Looking only at unit price makes it easy to pick the wrong model. Compare all four of the following dimensions:

    • Price: measured as cost per passed task — total cost divided by the number of tasks that pass.
    • Latency: record both time-to-first-token and full response time. Interactive scenarios care more about the former.
    • Stability: track failure rate, timeout rate, and rate-limit frequency on your private regression set.
    • Compliance: confirm data storage location, log retention period, and whether the provider trains models on your data.

    3.2 Model Routing Rules

    Task difficulty varies widely. Sending every request to the strongest model gets expensive fast. The basic idea of routing is to tier tasks:

    1. Format conversion, simple completions, log summarization, and similar tasks go to a low-cost model.
    2. Multi-file refactoring, architecture design, complex debugging, and similar tasks go to a stronger model.
    3. When the low-cost model fails, escalate to the stronger model and retry once. Cap the number of escalations to keep costs bounded.

    Escalation costs count toward the total task cost. If escalation doesn’t noticeably improve the pass rate, tighten the routing conditions.

    3.3 Selection Workflow

    1. Run 2 to 3 candidate models against your private regression set.
    2. Compute each model’s pass rate, average cost, P95 latency, and dominant failure types.
    3. Rank by cost per passed task and drop any option that fails your compliance requirements.
    4. Design routing rules, then validate total cost and pass rate after routing using the same test set.
    5. Re-test quarterly or whenever a model version updates.

    4. Integration: Ready-to-Run Calling Code

    The following client uses the OpenAI-compatible /v1/chat/completions endpoint. To integrate other providers, just replace the base URL and model name in the environment variables — refer to the relevant provider’s documentation for specifics. Install the dependency with pip install requests; requests 2.31 or later is recommended.

    1. import os
    2. import random
    3. import time
    4. from datetime import datetime, timezone
    5. from email.utils import parsedate_to_datetime
    6. from typing import Any, Dict, List, Optional
    7. import requests
    8. RETRYABLE_STATUS = {429, 500, 502, 503, 504}
    9. MAX_RETRIES = 5
    10. BACKOFF_CAP = 30.0
    11. TIMEOUT = (10, 120) # 10s connection timeout, 120s read timeout
    12. def backoff_seconds(attempt: int) -> float:
    13. """Exponential backoff with random jitter, capped at 30 seconds per wait."""
    14. return min(2 ** attempt, BACKOFF_CAP) + random.uniform(0, 1)
    15. def parse_retry_after(value: Optional[str], attempt: int) -> float:
    16. """Parse the Retry-After header. It may be seconds or an HTTP date.
    17. Falls back to exponential backoff if parsing fails."""
    18. if not value:
    19. return backoff_seconds(attempt)
    20. value = value.strip()
    21. if value.isdigit():
    22. return min(float(value), BACKOFF_CAP)
    23. try:
    24. target = parsedate_to_datetime(value)
    25. except (TypeError, ValueError):
    26. return backoff_seconds(attempt)
    27. if target.tzinfo is None:
    28. target = target.replace(tzinfo=timezone.utc)
    29. wait = (target - datetime.now(timezone.utc)).total_seconds()
    30. return min(max(wait, 0.0), BACKOFF_CAP)
    31. def chat_with_retry(
    32. messages: List[Dict[str, Any]],
    33. model: str,
    34. base_url: str,
    35. api_key: str,
    36. temperature: float = 0.0,
    37. ) -> Dict[str, Any]:
    38. url = base_url.rstrip("/") + "/v1/chat/completions"
    39. headers = {
    40. "Authorization": f"Bearer {api_key}",
    41. "Content-Type": "application/json",
    42. }
    43. payload = {"model": model, "messages": messages, "temperature": temperature}
    44. last_error: Optional[Exception] = None
    45. for attempt in range(MAX_RETRIES + 1):
    46. try:
    47. resp = requests.post(url, headers=headers, json=payload, timeout=TIMEOUT)
    48. except (requests.Timeout, requests.ConnectionError) as exc:
    49. last_error = exc
    50. if attempt == MAX_RETRIES:
    51. break
    52. time.sleep(backoff_seconds(attempt))
    53. continue
    54. if resp.status_code == 200:
    55. return resp.json()
    56. if resp.status_code not in RETRYABLE_STATUS:
    57. # Errors like 400, 401, 403 will not succeed on retry; raise directly.
    58. raise RuntimeError(f"Request failed with HTTP {resp.status_code}: {resp.text[:500]}")
    59. last_error = RuntimeError(f"HTTP {resp.status_code}")
    60. if attempt == MAX_RETRIES:
    61. break
    62. wait = parse_retry_after(resp.headers.get("Retry-After"), attempt)
    63. time.sleep(wait)
    64. raise RuntimeError(f"Failed after {MAX_RETRIES} retries: {last_error}")
    65. if __name__ == "__main__":
    66. api_key = os.environ["LLM_API_KEY"]
    67. base_url = os.environ.get("LLM_BASE_URL", "https://api.example.com")
    68. model = os.environ.get("LLM_MODEL", "your-model-name")
    69. messages = [
    70. {"role": "system", "content": "You are a senior Python engineer."},
    71. {"role": "user", "content": "Explain what this code does: print(sum(range(10)))"},
    72. ]
    73. result = chat_with_retry(messages, model, base_url, api_key)
    74. print(result["choices"][0]["message"]["content"])

    Set the environment variables LLM_API_KEY, LLM_BASE_URL, and LLM_MODEL before running. Keep the API key in environment variables — never hardcode it into code or logs. Before going live, run this code through your private regression set first, then decide whether to roll it into production.