Multi-Model Selection: Reliable Choices with Real Cost and Latency Data
For AI application and platform teams running multiple models, this article presents a four-step method for reliable selection: measure quality on an in-house evaluation set, calculate cost from real token usage including cache hits, compare latency and data terms in one table, and make scenario-based decisions. It covers a unified evaluation adapter, cache-aware cost formulas, latency measurement, data-term checks, and a reproducible record-keeping approach.
Introduction: Multi-Model Selection Decisions Need Verifiable Data
New models are released more and more frequently, and teams can easily be swayed by benchmark scores and per-token prices from launch events. A comparison document should answer at least three questions: what the evaluation methodology is, under what conditions the price applies, and where the data comes from. Numbers that cannot answer these three questions are only clues, not a basis for decisions.
This article is for AI application and platform teams that use multiple models at the same time, and it presents a durable approach. The method has four steps: measure quality with your own evaluation set, calculate cost from real token usage, put latency and data terms into the same table, and make tiered decisions by scenario. The following sections cover the evaluation script, cache-aware cost, latency measurement, and data terms, and conclude with a reproducible record-keeping checklist.
1. First, Align the Definitions: Leaderboards, Prices, and Data Sources
Leaderboard scores come from specific question sets, specific prompts, and specific scoring rules. Two models that differ by a few points on a leaderboard may rank completely differently in your code repository, customer-support knowledge base, or long-document QA. Leaderboards indicate a rough capability range; they do not replace your own evaluation.
Prices also need to be unpacked. A single model is often billed separately for uncached input, cache-hit input, and output. Some providers also differentiate batch calls, regions, context-length ranges, or subscription tiers. Comparing only a single number such as “dollars per million tokens” can easily lead to the wrong conclusion. Every price entry should record the currency, effective date, billing conditions, and source page.
2. Build a Unified Evaluation Script
The core of the evaluation script is a call adapter layer. Whenever a new model comes online, connect it to the same adapter, run it against the same set of cases, and write the results into the same table. Business code should call only the adapter layer and should not depend directly on any vendor SDK.
2.1 Adapter Layer and Unified Fields
Providers use different names and definitions for the usage fields they return. Some include cache-hit tokens in total input tokens; others list them separately. The adapter layer absorbs these differences in one place and exposes four unified fields: total input tokens, cached tokens, output tokens, and latency. Before onboarding a new provider, verify against the official documentation whether cached tokens are included in total input tokens; otherwise the cost formula will be wrong.
import jsonimport osimport statisticsimport timefrom dataclasses import dataclassfrom pathlib import Path@dataclassclass Result:text: strinput_tokens: int # total input tokens, including cached tokenscached_tokens: int # portion that hit cacheoutput_tokens: inttotal_ms: float # total latency in millisecondsok: boolerror: str = ""def build_client(provider: str, api_key: str, timeout_s: float):"""Example: OpenAI-compatible endpoint. Verify the base URL and usage mapping against the provider's documentation."""from openai import OpenAIbase_url = os.environ.get(f"{provider.upper()}_BASE_URL") # read the base URL from configurationreturn OpenAI(api_key=api_key, base_url=base_url, timeout=timeout_s)class ModelAdapter:RETRYABLE = (TimeoutError, ConnectionError) # replace with the provider SDK's 429 and 5xx exceptions in practicedef __init__(self, provider: str, model: str, timeout_s: float = 60.0, max_retries: int = 2):key_name = f"{provider.upper()}_API_KEY"api_key = os.environ.get(key_name) # read the key only from environment variables; never write it to code or logsif not api_key:raise RuntimeError(f"Environment variable {key_name} is not set")self.model = modelself.client = build_client(provider, api_key, timeout_s)self.max_retries = max_retriesdef complete(self, prompt: str) -> Result:last_error = ""for attempt in range(self.max_retries + 1):start = time.perf_counter()try:resp = self.client.chat.completions.create(model=self.model,messages=[{"role": "user", "content": prompt}],)except self.RETRYABLE as e:last_error = repr(e)time.sleep(2 ** attempt) # exponential backoffcontinueexcept Exception as e: # auth, parameter, and similar errors are unlikely to be retryable; record the failure directlyreturn Result("", 0, 0, 0, 0.0, False, repr(e))total = (time.perf_counter() - start) * 1000u = resp.usagedetails = getattr(u, "prompt_tokens_details", None)cached = getattr(details, "cached_tokens", 0) or 0return Result(resp.choices[0].message.content,u.prompt_tokens, cached, u.completion_tokens, total, True)return Result("", 0, 0, 0, 0.0, False, last_error)CASES = {"repo_level_fix": "cases/repo_fix.md","long_doc_qa": "cases/long_doc.md","tool_call_loop": "cases/agent.md",}def load_case(path: str) -> str:return Path(path).read_text(encoding="utf-8")def grade(case_name: str, text: str) -> float:"""Rule-based grading example: output must be valid JSON containing a patch field. Semantic results are sampled separately."""try:return 1.0 if "patch" in json.loads(text) else 0.0except (json.JSONDecodeError, TypeError):return 0.0def cost_usd(r: Result, price: dict) -> float:"""price is in USD per million tokens; keys are input, cache_hit, and output."""uncached = r.input_tokens - r.cached_tokensreturn (uncached * price["input"]+ r.cached_tokens * price["cache_hit"]+ r.output_tokens * price["output"]) / 1_000_000WARMUP, REPEAT = 2, 20def percentile(values, p):ordered = sorted(values)return ordered[min(len(ordered) - 1, round(p * (len(ordered) - 1)))]def run_eval(models, prices, prompt_version: str):rows = []for m in models:for name, path in CASES.items():prompt = load_case(path)for _ in range(WARMUP): # warm-up; discard resultsm.complete(prompt)samples = [m.complete(prompt) for _ in range(REPEAT)]ok = [s for s in samples if s.ok]row = {"model": m.model, "case": name,"prompt_version": prompt_version,"success_rate": len(ok) / REPEAT}if ok:latencies = [s.total_ms for s in ok]row.update({"score": statistics.mean(grade(name, s.text) for s in ok),"cost_usd": statistics.mean(cost_usd(s, prices[m.model]) for s in ok),"latency_p50_ms": statistics.median(latencies),"latency_p95_ms": percentile(latencies, 0.95),})rows.append(row)return rows
Before running it, keep a few points in mind. Read prices from a dated configuration file rather than hard-coding them. The files in CASES should come from real business cases, not generic benchmark sets.
2.2 Grading and Manual Review
Results that can be graded by rules should go to the script—for example, whether the format is correct, whether tests pass, or whether JSON fields are complete. Semantic results, such as whether a summary is accurate or whether an answer is grounded in the document, require manual review. Start by sampling 10% to 20% of cases, with at least 30 items per round. Two reviewers should grade independently. If agreement is below 80%, revise the grading criteria before continuing. Cases that fail manual review should be added to the evaluation set so similar errors are not missed.
3. Real Cost Must Include Caching
The formula for a single call is:
Single-call cost = (uncached input tokens × input price + cached input tokens × cached input price + output tokens × output price) ÷ 1,000,000
The prices below are used only to demonstrate the arithmetic and do not represent any real quote. Assume an input price of $2 per million tokens, a cached input price of $0.20 per million tokens, and an output price of $8 per million tokens. A multi-turn agent call uses 100,000 input tokens, of which 90,000 hit cache, and produces 2,000 output tokens. With these hypothetical prices, the call costs $0.054. Without caching, the same call costs $0.216—about four times more. In actual accounting, prices must be verified by tier across input, output, cache, batch, region, and context-length range.
Cache benefits depend on the hit rate. Caching usually requires a stable prompt prefix. If the system prompt changes every turn, or if a timestamp is placed at the very beginning of the prompt, the hit rate will drop noticeably. The table below uses the same call (100,000 input tokens, 2,000 output tokens) to show cost at different cache hit rates. Prices are the hypothetical values above, in USD:
| Cache hit rate | Uncached input cost | Cached input cost | Output cost | Total cost per call |
|---|---|---|---|---|
| 0% | 0.200 | 0.000 | 0.016 | 0.216 |
| 50% | 0.100 | 0.010 | 0.016 | 0.126 |
| 90% | 0.020 | 0.018 | 0.016 | 0.054 |
Multi-turn agent loops and scenarios that repeatedly reference the same long document benefit the most. Single-turn short Q&A sees almost no benefit; in that case, treating cache cost as the main advantage leads to unreliable conclusions. During evaluation, record the actual hit rate separately. Warm-up calls will cause subsequent samples to hit cache, so reported costs should state whether cold starts are included.
4. Latency, Data Terms, and Tiered Selection
4.1 How to Measure Latency Credibly
Latency for a single call varies widely, so one result is not enough to draw a conclusion. During measurement, warm up first, discard the first few calls, and then sample each case at least 20 times. Report the median (P50) and P95. With fewer than 20 samples, P95 is unstable; report only the median and note the sample size. For streaming interfaces, also record time to first token (TTFT) separately, because the user experience of conversational products depends mainly on first-token speed, while batch tasks care more about total elapsed time.
4.2 Data-Term Checklist
Latency and cost can be measured directly, but data terms must be verified against contracts and official terms text. Before selection, confirm each of the following:
- Data retention period: how long requests and responses are stored, and whether this can be shortened or disabled.
- Training use: whether user data is used for training, what the default state is, and how to opt out.
- Storage region and cross-border transfer: where data is stored and whether cross-border transfer is involved.
- Right to deletion: whether deletion can be requested, and what the time limit and method are.
- Data processing agreement (DPA): whether one can be signed and which subprocessors are involved.
- Log redaction: whether platform logs record prompts, and whether sensitive fields can be redacted.
Terms change over time, so record the review date and recheck periodically.
4.3 Tiered Selection Table
Decisions proceed in order. First pass the compliance gate: models that do not meet the data terms are eliminated. Then pass the quality threshold, which the business defines—for example, the test pass rate for repository-level fixes. Among those that pass, choose the model with the best cost or latency for the scenario. For latency-sensitive scenarios, use P95 rather than the average.
| Scenario | Quality threshold | Real cost (including cache) | Latency P50 / P95 | Data retention and training terms | Conclusion |
|---|---|---|---|---|---|
| Repository-level code fix | Test pass rate reaches the business threshold | Calculated with the formula in Section 3 | No hard requirement | Meets the compliance gate | Lowest cost among models that meet quality |
| Long-document QA | Manual review pass rate reaches the threshold | Calculated with the formula, with emphasis on cache hit rate | No hard requirement | Meets the compliance gate and supports deletion | Lowest cost among models that meet quality |
| Online tool-call loop | Tool-call format correctness reaches the threshold | Calculated with the formula; multi-turn prefixes must be stable | P95 meets product requirements | Meets the compliance gate | Lowest cost among models that meet P95 |
For scenarios involving sensitive data, prefer models with stricter retention and training terms, and use private deployment when necessary. Batch offline tasks are not latency-sensitive and can accept slower, lower-cost models.
5. Conclusion and Reproducibility Checklist
Multi-model selection should not rely on impressions or a single leaderboard. A reliable conclusion requires three conditions at the same time: the evaluation set comes from your own business, cost includes cache hits, and latency and data terms have been measured and verified. Every conclusion should be reproducible by others, so each evaluation should be documented for reproducibility.
