How to Choose an LLM the Right Way: From Unit Price to Cost per Task

    A practical guide to LLM selection that goes beyond the price page. Learn why a low per-token price does not guarantee a low bill, how to build a per-task cost model that accounts for token mix, cache hits, retries, and success rate, and how to run a controlled one-week A/B test to find the true cost optimum. Includes a vendor-agnostic Python snippet for per-task accounting and a layered evaluation approach for coding, agentic, and visual tasks.

    1. A Cheap Unit Price Is Not a Cheap Bill

    Model pricing pages usually show just two numbers: the price per million input tokens and the price per million output tokens. These two numbers are easy to compare side by side, yet they tell you almost nothing about your end-of-month bill. The reason is simple: a real bill is determined by four variables, and unit price is only one of them.

    • Token mix: In a single request, input tokens are often several to tens of times the output tokens, especially in long-context, code-repository Q&A, and document-understanding scenarios, where input can account for more than ninety percent of the total.
    • Cache hits: Workloads with a stable prefix (a fixed system prompt, fixed knowledge-base snippets, fixed code context) can hit the cache, and the cached portion is billed well below the regular input rate.
    • Average attempts: A slightly weaker model often needs to “try a few more times” to reach the same accuracy, and doubling the attempts doubles the cost.
    • Task success rate: Cost is only comparable once failed tasks are folded in. A cheap option that requires manual rework carries a very high hidden cost.

    So the right thing to compare is not the unit price, but the cost per effective task.

    2. Build a Per-Task Cost Model

    Fold the variables above into a single formula:

    1. cost per task = (regular input tokens × P_in
    2. + cached input tokens × P_cache
    3. + output tokens × P_out)
    4. × average attempts
    5. ÷ task success rate

    Here P_in, P_cache, and P_out are the corresponding unit prices. average attempts and task success rate must come from real measurements, not from guesswork.

    The script below plugs directly into an existing call chain for per-task accounting. It does not depend on any specific vendor’s API; you only need to add instrumentation at your model-call wrapper layer:

    1. from dataclasses import dataclass, field
    2. @dataclass
    3. class ModelPrice:
    4. p_in: float # regular input price (per 1M tokens)
    5. p_cache: float # cache-hit input price
    6. p_out: float # output price
    7. @dataclass
    8. class TaskRecord:
    9. model: str
    10. in_tokens: int = 0
    11. cache_tokens: int = 0
    12. out_tokens: int = 0
    13. attempts: int = 0
    14. success: bool = False
    15. price: ModelPrice = None
    16. def cost(self) -> float:
    17. p = self.price
    18. return (self.in_tokens * p.p_in
    19. + self.cache_tokens * p.p_cache
    20. + self.out_tokens * p.p_out) / 1_000_000
    21. def aggregate(records: list[TaskRecord]) -> dict:
    22. """Aggregate by model: cost per effective task = total spend / successful tasks"""
    23. stat = {}
    24. for r in records:
    25. s = stat.setdefault(r.model, {"spend": 0.0, "ok": 0, "total": 0, "attempts": 0})
    26. s["spend"] += r.cost() * max(r.attempts, 1)
    27. s["total"] += 1
    28. s["ok"] += int(r.success)
    29. s["attempts"] += max(r.attempts, 1)
    30. for m, s in stat.items():
    31. s["cost_per_success"] = s["spend"] / max(s["ok"], 1)
    32. s["success_rate"] = s["ok"] / max(s["total"], 1)
    33. s["avg_attempts"] = s["attempts"] / max(s["total"], 1)
    34. return stat

    Two easily overlooked details here. First, retry cost must be multiplied across the entire call, not just the output portion, because a retry usually resends the full context. Second, the denominator of the success rate is “all tasks,” not “successful tasks”; otherwise you systematically underestimate the cost on a hard task set.

    Note: The unit prices and token counts in the formula and script above are placeholder examples. Use the official billing documentation of the service you use and your own load-test results for real values.

    3. Caching and Retries: The Two Biggest Cost Levers

    In long-context workloads, the cache hit rate often affects the bill more than the unit-price difference itself. Improving the hit rate is an engineering task, independent of model selection:

    1. Stable prefix: Put the system prompt, tool definitions, and knowledge-base snippets at the very front and keep them byte-for-byte unchanged; move volatile content such as timestamps, random IDs, and user input to the end. Once the prefix changes, all subsequent tokens fall back to regular input billing.
    2. Control context bloat: Rerank and truncate retrieval results, keeping only the snippets relevant to the current question; summarize conversation history structurally rather than concatenating it in full.
    3. Reduce wasted attempts: Replace “generate once + human judgment” with “constrained decoding + automated validation + a limited number of repairs.” Using programmatic checks (compilation, unit tests, schema validation) instead of the model’s self-confirmation can significantly lower the average number of attempts.
    4. Tiered routing: Send simple requests to a small-parameter model and escalate complex requests to a large-parameter model. Routing rules should be based on computable signals (input length, whether multiple files are involved, whether a tool-call chain is needed), not hard-coded keywords.
    1. def route(req) -> str:
    2. if req.in_tokens < 2000 and not req.needs_tools:
    3. return "small" # low complexity, cost first
    4. if req.needs_tools and req.steps > 5:
    5. return "large" # long agentic chain, capability first
    6. return "medium"

    4. Replace a Single Composite Score with Component Evaluations

    A composite intelligence score is easy to spread, but nearly useless for selection, because it compresses coding, agentic execution, visual understanding, and other capabilities into a single scalar. A more valuable approach is layered evaluation:

    • Capability layers: coding (completion, cross-file refactoring, defect fixing), agentic (multi-step tool calls, long-horizon planning, failure recovery), vision (UI screenshot understanding, chart reading, document layout reconstruction), and long context (retrieval and localization, cross-passage reasoning).
    • Metric layers: beyond accuracy, you must record average attempts, average token consumption, timeout rate, and format-compliance rate. At the same accuracy, the option with fewer attempts may cost only half as much.
    • Difficulty layers: bucket the task set by difficulty and observe how the gap between models widens with difficulty. Many models tie on the easy bucket and pull apart by multiples on the hard bucket—exactly the range that determines production cost.

    The evaluation set should come from sampling your own real traffic, not from public leaderboard questions. A pragmatic starting point is to pull 100–200 real online requests, manually annotate the expected output to form a regression set, and run it every time the model or prompt changes.

    5. Designing a One-Week A/B Test

    To answer “which one is cheaper,” the only credible method is a controlled experiment in the same environment. Key design points:

    • Single variable: Change only the model; keep the prompt, temperature, max output length, retry policy, and task set all identical.
    • Equal-weight splitting: Split by request hash to ensure both groups have the same task-difficulty distribution; record the split key so results can be recomputed.
    • Complete instrumentation: For every call, record input/cache/output tokens, attempts, latency, a success flag, and a manual-rework flag.
    • Define metrics up front: Before the experiment starts, fix the definition of “cost per effective task” and the criteria for success, to avoid cherry-picking metrics after the fact.
    • Guardrail metrics: Monitor P95 latency and failure rate at the same time, to prevent trading latency for cost.

    For data landing, it is best to write everything into a logging service and set thresholds on “cost per task” and “success rate” with monitoring alerts; store experiment artifacts (prompt versions, task-set snapshots, result tables) in object storage with versioning to ensure reproducibility. Run the whole experiment orchestration on a container platform so isolated environments can be spun up quickly.

    6. Frontend and Visual Capabilities Can Be Validated the Same Day

    Coding and agentic capabilities need long-horizon statistics, but UI generation and visual-understanding capabilities can be judged instantly, making them suitable as an initial screen:

    • Give a screenshot of an existing page and ask for an equivalent component structure; check whether the layout hierarchy, spacing, and responsive breakpoints are reproduced.
    • Give an interaction description and ask for a runnable single-file page; check whether it pulls in undeclared external resources and whether there are console errors.
    • Give a video/animation requirement and check whether the timeline, frame rate, and keyframe descriptions are self-consistent.

    Judging these three task types can be highly automated: whether the page renders, whether there are errors, and the similarity between the screenshot and the reference image can all be scored by script, with no need to review each case manually.

    7. Conclusion

    The right order for model selection is: first define the business task set and success criteria, then build a per-task cost model, then use component evaluations to filter out candidates that lack capability, and finally run a one-week same-environment A/B test to determine the cost optimum. Unit price is only the entry ticket; cache hit rate, average attempts, and success rate are what truly determine the bill. Turning this process into a repeatable evaluation and accounting pipeline is more valuable in the long run than any one-off comparison.