Cost Evaluation and Model Selection for Large Language Models: A Practical Guide

    Choosing an LLM API is not about comparing unit prices—it is about comparing the total cost of completing a task, the variance in that cost, and the quality you get in return. This article breaks down how to separate input, cached input, and output token pricing, define task boundaries for auditable cost estimates, and use quality-cost curves to make informed routing decisions. It covers practical engineering levers such as cache-prefix optimization, model-family tiering, retry-aware cost tracking, and common pitfalls that inflate bills beyond the sticker price.

    When teams compare large language model (LLM) APIs, the debate often starts and ends with per-million-token prices. That is a mistake. What actually matters is how much it costs to finish a unit of business work, how much that cost fluctuates, and what quality level you get for the money. Many teams copy input and output prices from a vendor page into a spreadsheet and call the selection done. After launch, they discover that long contexts, multi-turn tool calls, and retries have multiplied the bill by several times—and that the cheaper model’s tendency to fail on critical steps has pulled the total cost back up. A more robust approach: break down the pricing structure, define task boundaries explicitly, and plot quality against cost on the same chart using a fixed evaluation set.

    Start by Understanding the Three Types of Tokens, Not a Blended Average

    Most commercial LLM billing splits tokens into at least three categories:

    • Input tokens: The new prompt content sent with each request—instructions, retrieved passages, tool outputs, and user content.
    • Cached input tokens: Tokens that repeat across requests and can be reused by the server from a prefix cache. These are typically billed at a lower rate than fresh input because the compute can be partially skipped.
    • Output tokens: The text or structured results the model generates. Generation is compute-heavy, so output prices are usually higher than input prices.

    Quoting a single “average price per token” hides the structure that matters. A conversational assistant with a long system prompt that is reused across many turns will have a high percentage of cached input tokens, making the bill sensitive to cache discounts. A one-shot long-document generation task, by contrast, is dominated by output tokens, so the output price effectively decides the cost. When comparing two solutions, record the three unit prices separately and measure actual token usage by replaying real traffic. Do not extrapolate from a short sample prompt in the vendor’s documentation.

    Caching is not automatic savings. It only works if the prefix is stable, the order is consistent, and the request meets the server’s reuse conditions. Putting timestamps, random numbers, or user nicknames at the start of a system prompt—or reordering retrieved passages on every turn—will defeat the cache. On the engineering side, place invariant content (instructions, tool definitions, fixed knowledge) at the front, and put volatile content at the end. Use logs to distinguish new input tokens from cached input tokens.

    Per-Token Price Does Not Explain Task Bills

    A single task cost can be written as an auditable formula, not a slogan:

    Task cost ≈ fresh input tokens × input price + cached input tokens × cache price + output tokens × output price + extra calls from retries and tool round-trips.

    The “task” must be defined with clear boundaries. For example, “generate an executable fix description from a ticket” counts as one task—not each model invocation treated as an independent business result. A single business task often includes retrieval, planning, generation, validation, and sometimes a second generation round. If a cheaper model fails validation frequently, two retries can push the total token count and latency past the cost of one successful run of a more capable model.

    Therefore, any model-selection document should report:

    • Success rate or human-acceptance rate;
    • Median cost per successful task and the P95 cost;
    • End-to-end latency;
    • Number of tasks completable under a fixed budget.

    The median reflects the common case; the P95 captures the risk of long contexts, tool loops, and retries blowing up the bill. Averages alone are easily skewed by a few outlier samples, and they hide the long tail of “most requests are cheap, a few are extremely expensive.”

    Compare with Quality–Cost Curves

    Plot the quality score on a fixed evaluation set on the vertical axis and the cost per task on the horizontal axis. Each candidate model—or each routing strategy—becomes a point. Connect the points into a curve. The decision then shifts from “which is cheaper” to “below what quality threshold, and how much more quality does the next budget tier buy.”

    For the curve to be comparable, four constraints must hold:

    1. Evaluation set comes from real or replayed traffic, covering short queries, long contexts, multi-turn conversations, and failure samples—not just demo problems the model performs well on.
    2. Quality metrics align with business objectives. For classification tasks, use accuracy and recall. For generation tasks, use factual consistency, format validity, and human spot-checks. For code-related tasks, use test-pass rate. Do not substitute non-reproducible subjective impressions for scores.
    3. Cost is replayed under the same billing assumptions, including retries, and cache hit rate is not assumed to be an unrealistic 100%.
    4. Sampling temperature, maximum output length, and forced structured-output settings are kept consistent, or are treated explicitly as experimental variables—otherwise prompt-engineering differences get conflated with model-quality differences.

    The curve is usually not monotonic. There is often a “cheap and good enough” plateau, plus a region where quality barely improves while cost climbs steeply. The plateau is the right default for general routing. The steep region is reserved for high-risk steps: financial decisions, contract summaries for external use, or release notes that must pass on the first attempt.

    Layer Within a Model Family Rather Than Replacing Everything

    Vendors often offer several tiers within the same generation of models: a high-capability tier for hard samples, a standard tier for the bulk of requests, and a lightweight tier for classification, extraction, and routing. A price may stay the same while capability improves. That means after a model update, the evaluation should be rerun—do not keep the old routing table out of habit. Conversely, a lower unit price does not automatically mean a lower task cost: if the model produces more verbose output or relies on lengthy chain-of-thought reasoning, output token counts may rise.

    A practical routing strategy can be quite simple:

    • Use a lightweight model to classify intent and difficulty first.
    • Send low-difficulty, highly formatted requests to the standard tier with a strict output-length limit.
    • Escalate low-confidence, multi-step reasoning, or historically failing types to the high-capability tier.
    • Set a daily budget and circuit breaker for the high-capability tier; on overrun, degrade to the standard tier and surface a manual-review prompt.

    The key to tiering is recording why an escalation happened. If the escalation rate is persistently higher than expected, the classifier threshold or the prompt is the problem, not the default model.

    Engineering Levers to Make Cost a Controllable Variable

    Prompts and context:

    • Fix the prefix to maximize cache hits.
    • Truncate retrieved passages by relevance. Do not stuff the entire knowledge base into the context.
    • Require structured, short outputs. Use field constraints to replace long free-text explanations, unless the product explicitly needs the text.

    Invocation strategy:

    • Set per-task output and step limits to prevent runaway tool loops.
    • On validation failure, narrow the problem scope before retrying. Do not resend the same request unchanged.
    • For idempotent read-heavy, write-light results, apply application-level caching. Be explicit about invalidation conditions—do not let stale answers masquerade as savings.

    Observability and budgeting:

    • Split token usage and cost by application, tenant, and task type.
    • Monitor cost, quality spot-checks, and latency together. A cost-only alert can silently degrade quality without anyone noticing.
    • Use week-over-week trends rather than daily spikes for capacity planning, and distinguish between promotional traffic and prompt degradation.

    Below is a simplified cost-aggregation pseudocode that illustrates the accounting logic. Prices and token counts come from usage metering and do not represent any vendor’s actual rates:

    1. def task_cost(usage, price):
    2. return (
    3. usage.new_input_tokens * price.input
    4. + usage.cached_input_tokens * price.cached_input
    5. + usage.output_tokens * price.output
    6. )
    7. def summarize(records):
    8. costs = sorted(task_cost(r.usage, r.price) for r in records)
    9. n = len(costs)
    10. return {
    11. "median": costs[n // 2],
    12. "p95": costs[int(n * 0.95) - 1],
    13. "success_rate": sum(r.ok for r in records) / n,
    14. }

    The pseudocode makes a point: cost must be derived from metered fields, and success or failure must be recorded in the same record, so that retry costs can be added back after the fact.

    Common Misjudgments

    • Treating a lower cache price as an automatic bill reduction without measuring the actual cache hit rate.
    • Taking a high-capability model’s demo scores as scores for the full production traffic.
    • Comparing a “discounted model” under conditions of longer prompts and looser output limits, then attributing prompt bloat to model regression or improvement.
    • Ignoring the difference between offline batch processing and online interaction. Offline can queue and retry; online is more sensitive to latency and tail costs.
    • Optimizing only the input price while the model emits long chain-of-thought text that is later truncated—output tokens end up dominating the bill.

    A Suggested Rollout Sequence

    A four-week cadence is more practical than a one-shot full-traffic migration.

    • Week 1: Freeze task definitions, quality metrics, and metered fields.
    • Week 2: Replay historical requests. Plot the current solution’s quality–cost point and fix cache-prefix issues.
    • Week 3: Run layered routing for one low-risk task type. Compare median cost, P95, and human spot-check results.
    • Week 4: Decide whether to expand the high-capability tier’s triggering conditions.

    Keep routing configurations rollback-ready and keep one fixed evaluation set, so that “feels faster and cheaper” can be verified after the fact.

    If the enterprise already uses a cloud platform for unified model inference, logging, and monitoring, wire the accounting described above into the existing log and alerting pipeline: object storage for retaining evaluation samples, a message queue for peak-shaving replay, and monitoring that aggregates cost and success rate by task type. A platform like Baidu AI Cloud typically provides containers, logging, monitoring, and related general capabilities that are suitable for running the evaluation job and online metering under the same permission and audit framework. However, whether a model is sufficient for a specific workload is still determined by the business’s own evaluation set, not by platform capabilities.

    The conclusion is straightforward: input, cached input, and output tokens must be priced separately; the comparison unit is the task, not an isolated token; quality and cost belong on the same curve; and capability tiering plus cache-prefix design are the main levers. The price list is just an input parameter. The per-task success rate, tail cost, and latency are the grounds for go/no-go decisions.