Task-Level Cost Evaluation for LLM APIs: Beyond Per-Token Pricing

    Per-token prices are not enough to predict real LLM API spending. This article explains why task-level cost matters, breaks down the four variables that drive it—input tokens, output tokens, cache hits, and call count—and shows how to use cost per successful task to compare models. It includes a Python cost-estimation example, monitoring guidance for model upgrades, and a practical selection checklist.

    Why Per-Token Price Is Not Enough

    LLM APIs are usually priced per million tokens, with separate rates for input, output, and cached input tokens. Many teams compare those three numbers when choosing a model. But the actual bill depends on how many tokens a task consumes, not just the price sheet.

    A task cost can be expressed as:

    Task cost = Σ (uncached input tokens × input price + cached input tokens × cached price + output tokens × output price)

    With the same unit price, cost rises as a task needs more output tokens or more API calls. Unit price is one component of cost, not the cost itself.

    Four Variables That Drive Task Cost

    1. Input Tokens

    Input tokens include system instructions, tool definitions, conversation history, retrieved document fragments, and tool results. In agent-style applications, every call carries the previous context, so input volume accumulates across turns.

    Common optimizations:

    • Remove duplicate or outdated system instructions.
    • Summarize conversation history instead of keeping it verbatim.
    • Retrieve document snippets on demand instead of inserting full documents into context.
    • Keep only the fields the task needs from tool results.

    2. Output Tokens

    Output tokens are usually more expensive than input tokens, so they have a larger impact on cost. Output bloat is often caused by unnecessary explanations, overly verbose format descriptions, and code or text far longer than needed.

    Ways to control output:

    • State the output format and length limit explicitly in the prompt.
    • Use structured output to return only the required fields.
    • For fixed-format results, let the program generate display content instead of having the model produce the full text.

    3. Cache Hits

    Caching applies to the input prefix. When repeated requests share an identical prefix, the server can reuse the already computed portion, and those input tokens are billed at the cached rate.

    To improve cache hit rate:

    • Put stable content (system instructions, tool definitions, fixed knowledge) at the front of the request.
    • Put dynamic content (user questions, current state) at the end.
    • Avoid inserting timestamps, random IDs, or other per-request changes into the prefix.
    • Keep the field order in the prompt template stable.

    4. Number of Calls

    The number of calls is driven by the task flow. Failed retries, multi-step tool calls in an agent loop, and self-checking steps all increase call count. Each extra call adds input and output costs again.

    Set max steps, per-task timeout, and clear termination conditions for agents. Distinguish retryable errors (such as network timeouts) from non-retryable errors (such as invalid parameters) to prevent invalid retries from amplifying cost.

    Use Cost per Successful Task to Compare Models

    General benchmarks give a composite score that reflects broad model capability, but that score is not the same as success rate on a specific business task. A more useful metric for model selection is:

    Cost per successful task = total spend ÷ number of successful tasks

    This metric includes the cost of failed tasks. A model with a lower unit price but a higher failure rate can become more expensive due to repeated retries than a model with a higher unit price that succeeds on the first attempt.

    Evaluation process:

    1. Build a set of representative tasks and define clear success criteria.
    2. Run all candidate models with the same prompts, tools, and data.
    3. Record input tokens, cached tokens, output tokens, and call count for each task.
    4. Calculate success rate, average token consumption, average latency, and cost per successful task.
    5. Use these data with business priorities to make the decision.

    Example: Task Cost Estimation Code

    The following code estimates single-call cost, task cost, and cost per successful task. The price parameters are placeholders; replace them with the official prices of the service you use.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Price:
    4. input_per_m: float # Price per million uncached input tokens
    5. output_per_m: float # Price per million output tokens
    6. cached_per_m: float # Price per million cached input tokens
    7. @dataclass
    8. class CallUsage:
    9. input_tokens: int # Total input tokens for this call, including cached part
    10. cached_tokens: int # Cached tokens, must be <= input_tokens
    11. output_tokens: int # Output tokens for this call
    12. def call_cost(usage: CallUsage, price: Price) -> float:
    13. uncached = usage.input_tokens - usage.cached_tokens
    14. return (
    15. uncached * price.input_per_m
    16. + usage.cached_tokens * price.cached_per_m
    17. + usage.output_tokens * price.output_per_m
    18. ) / 1_000_000
    19. def task_cost(calls: list[CallUsage], price: Price) -> float:
    20. return sum(call_cost(c, price) for c in calls)
    21. def cost_per_success(task_costs: list[float], successes: list[bool]) -> float:
    22. total = sum(task_costs)
    23. ok = sum(successes)
    24. return total / ok if ok else float("inf")
    25. if __name__ == "__main__":
    26. # Placeholder prices
    27. price = Price(input_per_m=1.0, output_per_m=2.0, cached_per_m=0.1)
    28. run_a = [
    29. CallUsage(input_tokens=8000, cached_tokens=6000, output_tokens=600),
    30. CallUsage(input_tokens=9000, cached_tokens=8000, output_tokens=400),
    31. ]
    32. run_b = [
    33. CallUsage(input_tokens=5000, cached_tokens=0, output_tokens=1500),
    34. ]
    35. costs = [task_cost(run_a, price), task_cost(run_b, price)]
    36. successes = [True, False]
    37. print(f"Cost per successful task: {cost_per_success(costs, successes):.6f}")

    A few notes on the code:

    • cached_tokens must be a subset of input_tokens; otherwise the result can become negative.
    • Costs of failed tasks must be included in total spend.
    • Record prices by model and by date so version upgrades do not reuse stale pricing data.

    Long-Term Monitoring and Model Version Changes

    Model upgrades often change capability, output style, and token consumption at the same time. Even if the unit price stays unchanged, the number of output tokens for the same task can shift noticeably. Therefore, after every model version switch, re-run the benchmark task set and compare:

    • Change in success rate
    • Change in average input and output tokens
    • Change in cost per successful task
    • Change in average latency and call count

    In production, record these metrics by task type, model name, and version. Set alert thresholds. If output tokens for a task type keep rising over multiple days, check whether the prompt, tool return format, or model output style has changed.

    Selection Checklist

    • Have you defined task types and success criteria?
    • Are you comparing models with the same task set and prompts?
    • Are you measuring cost per successful task instead of only unit price?
    • Have you checked output bloat in long tasks?
    • Does the cache prefix structure produce stable hits?
    • Have you recorded token consumption before and after version upgrades?
    • Are max steps, timeouts, and termination conditions set for agents?

    Conclusion

    A stable API unit price does not mean stable task cost. Capability improvements often bring longer reasoning or more output, while call count and context length also affect the final bill.

    As models become closer in capability, cost efficiency becomes a major comparison dimension. The most reliable approach for developers is to build an evaluation baseline around real tasks, use cost per successful task as the measure, and keep monitoring token consumption. This way, model selection decisions can hold up as business volume grows.