How to Choose an AI Coding Model: Convert Quotas into Per-Task Cost
This article walks through a practical framework for evaluating AI coding models: converting token quotas into per-call and per-successful-task costs, measuring TTFT and TPS consistently, estimating self-hosting unit costs with clearly stated assumptions, and building multi-model failover. Each step includes ready-to-use formulas, tables, checklists, and example code. All numbers in the examples are hypothetical and do not reflect any provider's real pricing.
This article is organized in the following order: cost conversion, latency and throughput measurement, self-hosting cost estimation, a failover example, and a checklist. Each step provides formulas, tables, or checklists you can apply directly.
1. Convert Quotas into Per-Task Cost
A quota tells you how much resource a platform has committed, but not how much a single task costs or how long a code change will take. Before selecting a model, convert the quota into money. The conversion rules should follow the platform’s official documentation, such as how much quota is deducted per call relative to the billing unit. After conversion, the per-call cost formula is:
Per-call cost = input tokens ÷ 1,000,000 × input price + output tokens ÷ 1,000,000 × output price
The variables are defined as follows:
| Variable | Meaning | Source |
|---|---|---|
| Input tokens | Everything sent in one call, including the prompt, code snippets, and conversation history | Request logs or estimates |
| Output tokens | Everything the model generates, including code and explanations | Usage field in the response or estimates |
| Input price | Price per million input tokens | Official pricing page |
| Output price | Price per million output tokens | Official pricing page |
The cost of output tokens is often overlooked. On many platforms, the output price is significantly higher than the input price, and code generation tasks tend to produce a large share of output. Looking only at input will seriously underestimate the cost.
Cached Token Billing
If the platform supports context caching, the cached portion of the input is usually billed at a lower rate. Split the input into two parts: the non-cached portion is billed at the input price, and the cached portion at the cache price.
Cache hit rate depends on whether the context is stable, so do not assume a value. Measure it as follows:
- Export input tokens and cache-hit tokens for each call from request logs.
- Group by session, repository, or task type.
- For each group, hit rate = sum of cache-hit tokens ÷ sum of input tokens. Weight by tokens; do not simply average the per-call hit rates.
- Plug the weighted overall hit rate into the cost formula.
How to Collect Pricing Data
Prices may vary by region, currency, and billing period. Record the basis of every price you use:
- Open the model provider’s official pricing page.
- Record the currency, billing region, billing unit (per million tokens), and whether taxes are included.
- Record the effective date of the price.
- Use the same price version across the same batch of comparisons; do not mix prices from different dates.
- When prices change, recalculate all existing cost figures.
Example
All numbers below are hypothetical and do not represent any platform’s real pricing. Assume a code modification task averages 20,000 input tokens and 2,000 output tokens, with a 60% cache hit rate. Assume an input price of 10 per million tokens, an output price of 40 per million tokens, and a cache-hit price of 2.5 per million tokens.
- Non-cached input: 8,000 ÷ 1,000,000 × 10 = 0.08
- Cached input: 12,000 ÷ 1,000,000 × 2.5 = 0.03
- Output: 2,000 ÷ 1,000,000 × 40 = 0.08
Total per-call cost: 0.19, of which output accounts for 42%.
Cost per Successful Task
Per-call cost only reflects a single request. When a model fails or produces unusable output and you must retry, failed calls still incur charges. Therefore, compute cost per successful task:
Cost per successful task = total call cost per task (including retries) ÷ task pass rate
Continuing the example, if the pass rate is 80% and each task needs only one call on average, the cost per successful task is 0.19 ÷ 0.8 = 0.2375. The lower the pass rate, the higher this number. When two models cost the same per call, the one with the lower pass rate is actually more expensive.
2. Measure TTFT and TPS Consistently
Time to first token and generation speed determine how long a developer waits for results. Both metrics must be measured with the same definition and the same method, or the comparison is meaningless.
Metric Definitions
- TTFT (Time To First Token): the time from sending a request to receiving the first output token.
- TPS (Tokens Per Second): output tokens ÷ (end time − first-token time). This excludes the wait for the first token and reflects only generation-phase speed. If you need overall speed including the wait, define it separately and state so explicitly.
Measurement Procedure
- Prepare a fixed set of test prompts covering real task types, such as bug fixing, unit test generation, and code explanation. Record the input tokens of each prompt.
- Test all models with the same prompt set, in the same region, during the same time window.
- Enable streaming and record the send time, first-token time, and end time of every request.
- Discard the first few warm-up requests for each model to avoid cold-start effects.
- For each model, collect at least 30 valid samples at each concurrency level. Concurrency levels should cover daily peaks, for example 1, 4, and 8.
- Report p50, p90, p95, and the mean for both TTFT and TPS. Reporting only averages hides tail latency, and the tail is exactly where developers feel the stutter.
- Record the number of timeouts, rate limits, and error codes, and keep them together with the latency data.
Recording Table Template
| Field | Description |
|---|---|
| Model or deployment | For example, a cloud model or a self-hosted instance |
| Request ID | For tracing back to logs |
| Concurrency | The concurrency level of this request |
| Send time | Millisecond precision |
| First-token time | Time the first output token was received |
| End time | Time streaming output finished |
| Input tokens | From the usage field or tokenizer |
| Output tokens | From the usage field or tokenizer |
| Timeout or failure | Record the error type |
3. Estimate Self-Hosting Unit Cost and Its Assumptions
Self-hosting has no per-token bill, so cost must be derived from hardware, electricity, facilities, and operations. The estimation formulas are:
Total hourly cost = hardware depreciation + electricity + facilities and network + operations labor amortization + software licenses
Effective output tokens per hour = peak generation speed × 3,600 × average utilization
Unit output cost = total hourly cost ÷ effective output tokens per hour
Cost Item Details
- Hardware depreciation: purchase price minus residual value, amortized over the expected service life and running time.
- Electricity: based on rated or measured power, electricity price, and running time. Cooling also counts toward electricity.
- Facilities and network: racks, bandwidth, and dedicated-line fees, amortized proportionally.
- Operations labor: amortized by hours actually invested, not by the entire team’s salaries.
- Software licenses: inference frameworks, monitoring, or commercial licenses.
Assumptions You Must State
Self-hosting unit cost is highly sensitive to assumptions. When reporting results, list the following:
- Hardware purchase price, service life, and residual value assumptions.
- Average utilization. Utilization determines unit cost: for example, if utilization drops from 60% to 30%, unit cost roughly doubles, because hardware and electricity costs do not fall with request volume.
- Quantization method and batching strategy, which directly affect peak generation speed.
- Electricity price, PUE (Power Usage Effectiveness), or the facility’s actual energy consumption.
- Whether backup nodes are included. When high availability is required, the cost of standby nodes must be counted.
- Planned expansion and upgrade costs.
- Additional costs from compliance, security audits, and data retention.
Assume a node’s total hourly cost is 80 (hypothetical) and its peak generation speed translates to 300,000 output tokens per hour (hypothetical). At 60% utilization, effective output is 180,000 tokens per hour, giving a unit output cost of about 80 ÷ 180,000 × 1,000,000 ≈ 444 per million tokens. At 30% utilization, unit cost rises to about 889 per million tokens. This example shows that self-hosting’s cost advantage depends on sustaining high utilization.
4. Example Code for Multi-Model Failover
The code below demonstrates a model call chain: try multiple models in order, each with a timeout and a limited number of retries, fall back to the next model on failure, and log everything. The code is illustrative only; stub functions simulate random failures. Before production use, evaluate idempotency, rate limiting, circuit breaking, secret management, and differences in output quality across models.
import loggingimport randomimport timelogging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")log = logging.getLogger("model_failover")class RetryableError(Exception):"""Retryable errors, e.g., timeouts, rate limits (429), server errors (5xx)."""class FatalError(Exception):"""Non-retryable errors, e.g., invalid parameters, auth failure. Switch models immediately."""def call_provider(name, prompt, timeout_s):# Illustrative: a real implementation should call the SDK or HTTP API# and pass timeout_s to the underlying client.# Random results are used here to simulate success and failure.time.sleep(0.05)if random.random() < 0.3:raise RetryableError(f"{name} timed out or was rate-limited")return f"[{name}] generated result (input length {len(prompt)})"def call_with_failover(prompt, chain, timeout_s=30, max_retries=2):last_error = Nonefor provider in chain:for attempt in range(1, max_retries + 2):start = time.monotonic()try:result = call_provider(provider, prompt, timeout_s)elapsed = time.monotonic() - startlog.info("provider=%s attempt=%d latency=%.2fs status=ok",provider, attempt, elapsed)return resultexcept RetryableError as e:last_error = eelapsed = time.monotonic() - startlog.warning("provider=%s attempt=%d latency=%.2fs status=retryable err=%s",provider, attempt, elapsed, e)if attempt <= max_retries:# Exponential backoff with jitter to avoid synchronized retries.backoff = min(8, 2 ** (attempt - 1)) + random.uniform(0, 0.5)time.sleep(backoff)except FatalError as e:last_error = elog.error("provider=%s status=fatal err=%s, switching to next model", provider, e)breaklog.warning("provider=%s retries exhausted, falling back to next model", provider)# All models failed: raise an exception and let the caller decide# whether manual intervention is needed.raise RuntimeError(f"All models failed, last error: {last_error}")if __name__ == "__main__":result = call_with_failover(prompt="Fix the null pointer exception in the login endpoint",chain=["model_a", "model_b", "model_c"],timeout_s=30,max_retries=2,)print(result)
Design Considerations
- Retries increase per-task cost. When computing cost per successful task, include the cost of failed calls.
- The timeout should be slightly larger than the model’s measured p95 latency, or normal slow requests will be misclassified as failures.
- After falling back to another model, output style and code quality may differ. For tasks that modify code, add automated tests or manual review.
- For operations with side effects, such as writing files or committing code, confirm the operation is idempotent before retrying.
