LLM Cost Breakdown: Per-Task Billing and Cost Optimization

    This article explains how to move beyond total bills and per-call pricing by calculating the full model cost of one business task. It covers billing components, a four-step estimation method with sample code, cache-hit practices, invalid-token control, model tiering and routing, and cost-per-successful-task metrics, ending with an engineering checklist.

    Why Break Costs Down to the Per-Task Level

    Many teams evaluate LLM costs by looking only at the total bill or the price of a single call. That view is hard to use for optimization. A user-facing feature usually includes multiple model calls, such as intent recognition, information retrieval, content generation, and result validation. Looking only at per-call pricing cannot tell you the cost of the entire pipeline.

    Per-task cost means the total model cost required to complete one business objective, including all intermediate steps, re-inference after tool calls, and failed retries. When cost is calculated per task, product managers can judge whether a feature is economically worthwhile, and engineers can locate the real cost hotspots.

    Basic Components of Billing

    Pricing for mainstream LLM services usually includes three parts.

    1. Input tokens: the total length of user prompts, system instructions, conversation history, and external materials.
    2. Output tokens: the length of the content generated by the model. The output unit price is generally higher than the input unit price because generation requires computing token by token.
    3. Cache-hit portion: when a request prefix matches a recent request, the service can reuse already-computed intermediate results. This portion is usually billed at a lower unit price.

    Specific prices depend on each provider’s official pricing. They can also vary widely across models, time periods, and billing tiers. In engineering, unit prices should be configurable rather than hardcoded in business logic.

    The cost of a single call can be expressed as:

    Cost per call = uncached input tokens × input price + cached input tokens × cached price + output tokens × output price

    Unit prices are usually quoted per million tokens, so units must be converted consistently in the calculation.

    How to Estimate Per-Task Cost

    Estimation can be divided into four steps.

    Step 1: Map the task pipeline. Draw the complete flow from task trigger to completion, and mark every node that calls a model.

    Step 2: Count the call frequency of each node. Pay attention to conditional branches. For example, a second validation may run only when confidence is low. The expected number of calls for such a node should be weighted by probability.

    Step 3: Sample average token usage. Draw a batch of samples from production logs, count the input, output, and cache-hit tokens for each node, and calculate the mean and percentiles. Estimating from ideal examples alone usually produces results that are too low.

    Step 4: Add retry and failure costs. Network timeouts, invalid output formats, and similar issues can trigger retries. The cost of retries must be included.

    Below is an illustrative calculation function. Prices are passed in as arguments so they can be replaced with actual configuration:

    1. from dataclasses import dataclass
    2. @dataclass
    3. class PriceConfig:
    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. def call_cost(cfg: PriceConfig, input_tokens: int, output_tokens: int,
    8. cached_tokens: int = 0) -> float:
    9. fresh = max(input_tokens - cached_tokens, 0)
    10. total = (fresh * cfg.input_per_m
    11. + cached_tokens * cfg.cached_per_m
    12. + output_tokens * cfg.output_per_m)
    13. return total / 1_000_000
    14. def task_cost(cfg: PriceConfig, steps: list[dict]) -> float:
    15. # Each item in steps describes average usage, expected call ratio, and retries for one node
    16. cost = 0.0
    17. for s in steps:
    18. unit = call_cost(cfg, s["input"], s["output"], s.get("cached", 0))
    19. expected_calls = s.get("call_ratio", 1.0) * (1 + s.get("retries", 0))
    20. cost += unit * expected_calls
    21. return cost

    This function only performs accounting logic and contains no specific prices. In actual use, fill the configuration with production sample data and official pricing, and update it regularly.

    How Cache Hits Affect Cost

    Cache hits can significantly reduce input-side costs, provided that the request prefix remains stable. There are several practical guidelines.

    1. Put system instructions, role settings, and fixed knowledge at the very beginning of the prompt, and put user input and dynamic data later. Cache-hit probability is higher only when the prefix is consistent.
    2. Avoid inserting timestamps, request IDs, or random fields into the prefix. These fields differ on every request and will invalidate the cache.
    3. For multiple turns in the same session, keep the order and format of history messages stable. Rewriting history arbitrarily will break the cache chain.
    4. Monitor the cache hit rate. When the hit rate drops, it often means the prompt template has been changed or a dynamic field has been misplaced in the prefix.

    Control Invalid Tokens

    Much cost waste comes from unnecessary context and verbose output.

    On the input side, consider the following.

    • Use rolling summaries for conversation history and keep only the parts relevant to the current task.
    • Truncate retrieval results by relevance and inject only the necessary snippets rather than entire documents.
    • Clean raw data returned by tools into a structured form and remove fields unrelated to the task.

    On the output side, consider the following.

    • Specify output length and structure in instructions, such as limiting the number of fields or items.
    • Use structured output formats to reduce greetings and explanatory text.
    • For nodes that only need a judgment result, ask the model to return a label or boolean value instead of a full paragraph.

    Choose Models by Task Difficulty

    Not every node needs the strongest model. Simple tasks such as intent classification, keyword extraction, and format conversion can usually be handled by smaller models. Complex reasoning, long-form generation, and multi-step planning require more capable models.

    A common approach to model tiering is routing. The router decides which model tier to call based on task type or input characteristics.

    1. def route(task_type: str, input_length: int) -> str:
    2. if task_type in {"classify", "extract", "format"}:
    3. return "small"
    4. if task_type == "summarize" and input_length < 2000:
    5. return "small"
    6. return "large"

    Routing rules must be validated against an offline evaluation set before launch. The set should cover typical and boundary samples for each task type and confirm that the small model reaches an acceptable level on target metrics. Downgrading without validation can easily cause quality regressions and manual rework, ultimately offsetting the savings.

    Measure Optimization with Cost per Successful Task

    Looking only at per-task cost can lead to misleading conclusions. A cheap approach with a low success rate will trigger many retries and manual interventions, making the total cost higher instead. A more reasonable metric is cost per successful task:

    Cost per successful task = total cost ÷ number of successfully completed tasks

    Review it together with the following metrics.

    • Task success rate: measured according to the business definition of correctness.
    • Average latency: affects user experience and concurrent resource usage.
    • Manual correction rate: reflects output quality in actual use.

    After every change to a model, prompt, or routing rule, observe these metrics together. A change is effective only when cost per successful task decreases and quality metrics do not show obvious regression.

    Engineering Checklist

    1. For every model call, log input, output, cache-hit token counts, and task labels to the logging system.
    2. Break down costs by task type, feature module, and model tier to locate cost hotspots.
    3. Set monitoring alerts for per-task cost and cache hit rate, with thresholds based on historical baselines.
    4. Put prices, routing rules, and prompt templates under version control so changes are traceable and rollback-ready.
    5. Regularly recheck the quality of each model tier with an evaluation set to avoid silent changes after model updates.
    6. Cache or deduplicate results for high-frequency tasks to reduce repeated calls.

    In summary, the core of LLM cost optimization is to break costs down by task pipeline, then reduce invalid tokens segment by segment, improve cache reuse, and allocate models by difficulty. The measurement standard should be cost per successful task, not the price of a single call.