How to Calculate LLM Call Cost: Per-Task Cost and Budget Caps

    List prices for large language model APIs are easy to misread. A cheaper rate does not guarantee a cheaper completed task, and a higher rate can still cost less for the same outcome. The bill is driven by tokens consumed, number of calls, and retries after failures. This article starts from the billing model and describes a practical way to estimate cost in your own workload.

    List prices for large language model APIs are easy to misread. An endpoint with a low unit price is not necessarily cheap for a finished job, and a higher unit price can still cost less for the same job. What actually determines the bill is how many tokens a task consumes, how many calls it makes, and how many rounds of retries follow a failure. Starting from the billing model, this article lays out a cost-evaluation method you can apply in your own system.

    Understand the billing unit first

    A token is the basic unit a model uses to split text. A passage is divided into tokens, and Chinese, English, and code are segmented differently. The same meaning can consume a noticeably different number of tokens in different languages. Do not estimate cost from character count. Use the usage figures returned by the API.

    Most usage-based APIs price input and output separately. Input is everything sent to the model, including system instructions, conversation history, retrieved material, and tool results. Output is what the model generates. Output is commonly priced higher than input, so longer generations raise cost faster.

    Under that rule, the cost of one call is:

    Single-call cost = input tokens × input price + output tokens × output price

    Prices are usually quoted per million tokens, so divide by one million before calculating. If the input price is 2 yuan per million input tokens and a call uses 10,000 input tokens, the input portion is 10000 ÷ 1000000 × 2 = 0.02 yuan.

    From a single call to per-task cost

    The cost of one call is not the cost of finishing a job. In practice, a task often includes several calls:

    • In a multi-turn conversation, each turn resends the previous context as input, so input grows with each turn.
    • After the model calls an external tool, the tool result enters the next turn’s input.
    • When the output format is wrong, tests fail, or the result is incomplete, the system retries or appends further instructions.
    • A complex task is split into substeps, and each substep is a separate call.

    Define per-task cost as:

    Per-task cost = the sum of all call costs required to finish the task (including retries) + tool-call fees

    That definition has a clear boundary. It includes model input and output fees, fees from retries, and charges for the tool calls themselves. It does not include human review time, external tool subscriptions, or infrastructure such as servers. If cache-hit discounts or batch discounts apply, list them separately. Do not fold them into the same number, or the cost will be understated or overstated.

    Looking only at the unit price misses context growth and retries, and often underestimates real spend.

    Break the cost model down in code

    The sample below splits per-task cost into parts you can measure. The prices are fictional placeholders used only to show the calculation. They do not match any real price.

    1. def call_cost(call, price):
    2. # price: unit price per million tokens, {"in": input price, "out": output price}
    3. return (call["in_tokens"] * price["in"] + call["out_tokens"] * price["out"]) / 1_000_000
    4. def task_cost(calls, price_table):
    5. # When mixing models, bill each call at the price of the model it used
    6. total = 0.0
    7. for c in calls:
    8. price = price_table[c["model"]]
    9. total += call_cost(c, price) + c.get("tool_fee", 0.0)
    10. return total
    11. price_table = {
    12. "model_small": {"in": 1.0, "out": 4.0}, # fictional placeholder price
    13. "model_large": {"in": 3.0, "out": 12.0}, # fictional placeholder price
    14. }
    15. calls = [
    16. {"model": "model_small", "in_tokens": 12000, "out_tokens": 800},
    17. {"model": "model_small", "in_tokens": 15500, "out_tokens": 1200}, # second turn, longer context
    18. {"model": "model_large", "in_tokens": 16100, "out_tokens": 400}, # one retry after upgrading the model
    19. ]
    20. print(task_cost(calls, price_table))

    The important point is where the numbers come from. Take each call’s token counts from the usage field returned by the API, not from a later estimate. Estimates tend to miss system instructions and tool descriptions, so the total comes out low. Also record the model name on every call so mixed-model traffic can be priced correctly.

    Build your own benchmark

    Cost reductions published by vendors are usually based on test sets they chose. Those sets may be far from your workload. The most reliable way to judge whether a model is economical is to run it on your real tasks.

    Build the benchmark as follows:

    1. Collect samples. Stratify by task type, such as document summarization, code edits, data cleaning, and question answering. Prepare at least twenty to thirty real tasks per type, covering both common and edge cases. Redact sensitive data first.
    2. Define pass criteria. Write acceptance conditions that can be checked automatically for each task. Typical conditions include output that passes format validation (for example, parseable JSON), complete required fields, passing unit tests, and key facts that match a reference answer. For checks that cannot be automated, use sampling plus human scoring, often 10% to 20% of the total.
    3. Fix the experiment. Run the same sample set, the same prompts, and the same tool configuration on each candidate model. If conditions differ, the results are not comparable.
    4. Record metrics. For each task, record token usage, latency, whether it passed, and the retry count.
    5. Compute effective cost.

    The core metric is cost per successful task:

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

    Total spend includes input and output fees, retry fees, and tool-call fees for every sample on that model. The denominator counts only tasks that passed, because failed tasks still cost money and produced no usable result.

    Consider a fictional example. On the same set of 30 tasks, a small model spends 1.2 yuan and passes 12; a large model spends 2.4 yuan and passes 27. Cost per successful task is 1.2 ÷ 12 = 0.10 yuan for the small model and 2.4 ÷ 27 ≈ 0.089 yuan for the large model. The small model has the lower unit price, but its lower pass rate makes each usable result more expensive. That is exactly where list price misleads. These figures only illustrate the calculation. Use your own samples for a real result.

    Choose a model tier by task difficulty

    Once you have cost per successful task, you can choose tiers. A common approach is tiered routing:

    • Low-difficulty tasks, such as format conversion, simple classification, and filling a fixed template, should prefer the small model. Do not upgrade if its pass rate and cost per successful task already meet the bar.
    • Medium-difficulty tasks, such as routine document summaries and ordinary code edits, should compare cost per successful task across two tiers and pick the lower one.
    • High-difficulty tasks, such as multi-step reasoning and cross-file code edits, should be validated on the large model first. Move to the higher tier only when the small model’s pass rate is clearly insufficient and the cost per successful task after the upgrade is still acceptable.

    The decision depends on pass rate, unit price, and average retries together, not on unit price alone. A model with a low list price can still have a higher cost per successful task if it retries often.

    Set a budget cap and circuit breakers

    A reliable cost per successful task is what makes a budget possible. Calculate it this way:

    • Per-task cap = P90 cost for that task type × 1.5. P90 means 90% of sample costs fall below that value. Using it instead of the average keeps a few outliers from pulling the cap off.
    • Monthly cap = estimated monthly task volume × cost per successful task × a safety factor. A factor of 1.2 to 1.5 covers variation outside the sample.

    A cap alone is not enough. You also need automatic circuit breakers:

    • When the retry rate exceeds a set threshold (for example, more than two retries on the same task), pause that task and alert so the prompt or the data can be checked.
    • When input tokens on a single call exceed a set length, truncate conversation history or switch to a summary so context does not grow without limit.
    • When daily spend reaches a set share of the monthly cap (for example, 50%), raise an alert. At 100%, pause non-critical tasks.

    Write these numbers into configuration and review them on a schedule. Do not set them once before launch and leave them.

    Common mistakes and risks

    Common mistakes include comparing only unit prices; ignoring context growth and looking only at a single turn; ignoring retries and tool fees; not stratifying samples and treating easy tasks as the whole workload; replacing your own samples with a vendor test set; and estimating usage after the fact instead of recording real usage.

    On risk: redact real business samples before use, removing personal data, secrets, and sensitive customer content. Give API keys the minimum permissions they need, and store them in environment variables or a secrets manager, not in code. Do not keep the original sensitive text of samples in logs; record only the statistics you need. Confirm that data handling meets your organization’s compliance requirements before sending it to an external API.

    With this method, you can compute a reviewable cost per successful task from your own samples, then choose a tier and set a budget cap. How reliable that conclusion is depends on whether the samples are representative, whether usage data is real and available, and whether acceptance criteria can be judged automatically.