LLM API Cost Accounting and Optimization: A Practical Guide

    Model APIs charge by tokens, but businesses ultimately care about the cost of completing a task. This guide explains how to calculate cost at the task level, account for input, output, caching, retries, and human review, and reduce spending through context trimming, prompt-prefix caching, retrieval, structured outputs, model routing, and continuous quality evaluation. It also provides monitoring metrics and a practical rollout plan.

    1. Measure Cost per Task, Not per Token

    Model providers typically charge by token, but business teams care about how much it costs to complete a task. A ticket-classification workflow may require only one API call, while a code-review workflow may involve reading files, generating recommendations, validating results, and making several additional calls. For this reason, the task—not the individual request—should be the basic unit of cost accounting.

    A lower unit price does not necessarily mean a lower task cost. If a model generates unnecessarily long responses or frequently requires retries, it may cost more than a slightly more expensive model that completes the task successfully on the first attempt.

    2. Break Down the Cost of a Single Task

    The cost of one task can be divided into four categories:

    • Input cost: The total input tokens, including system prompts, conversation history, retrieved passages, and tool results.
    • Output cost: Generated text, structured fields, and any reasoning content included in the billing scope.
    • Cache cost: The portion of the input that matches a prefix cache, which is usually priced significantly lower than uncached input.
    • Hidden cost: Expenses caused by quality issues, such as failed retries, timeout compensation, and human review.

    The calculation can be expressed as:

    Task cost = Σ (uncached input tokens × input price) + Σ (cached input tokens × cache price) + Σ (output tokens × output price) + retry and review costs

    The summation covers every model call made during the task.

    3. Build a Reusable Cost-Accounting Script

    Writing every call record into a unified accounting function makes it possible to analyze the cost distribution of individual tasks rather than looking only at averages. The following pseudocode illustrates the approach:

    1. function calculateTaskCost(callRecords, pricing):
    2. totalCost = 0
    3. for call in callRecords:
    4. uncachedTokens = call.inputTokens - call.cachedInputTokens
    5. totalCost += uncachedTokens * pricing.inputPrice / 1000000
    6. totalCost += call.cachedInputTokens * pricing.cachePrice / 1000000
    7. totalCost += call.outputTokens * pricing.outputPrice / 1000000
    8. return totalCost

    Consider the following hypothetical example. These values are for illustration only and do not represent actual pricing:

    • Input price: 1 currency unit per million tokens
    • Cached input price: 0.1 currency units per million tokens
    • Output price: 4 currency units per million tokens

    • First call: 20,000 input tokens, including 15,000 cached tokens, and 1,000 output tokens.
      Cost = 5,000 × 1 / 10⁶ + 15,000 × 0.1 / 10⁶ + 1,000 × 4 / 10⁶ = 0.0105 currency units.

    • Second call: 22,000 input tokens, including 20,000 cached tokens, and 500 output tokens.
      Cost = 2,000 × 1 / 10⁶ + 20,000 × 0.1 / 10⁶ + 500 × 4 / 10⁶ = 0.006 currency units.

    The total task cost is 0.0165 currency units. If none of the input tokens were cached, the total would rise to 0.048 currency units. Caching therefore reduces the cost by approximately 66%. This makes cache hit rate one of the most important metrics to monitor.

    4. Reduce Input Costs

    4.1 Trim the Context

    Keep only the historical content relevant to the current request. Older conversation turns can be compressed into summaries, and duplicate tool results should be removed. A shorter context reduces input costs for every call and helps the model focus on the most important information.

    4.2 Put Stable Content at the Beginning

    Prefix caching usually relies on prefix matching. If even one character in the prefix changes, subsequent cached content may no longer match. Place stable content first and changing content later:

    1. [Stable: system instructions, role definition, output requirements, tool descriptions]
    2. [Semi-stable: project summary, business rules]
    3. [Dynamic: current user request, current retrieval results]

    Avoid placing timestamps, request IDs, or other fields that change on every request in the prefix. Although these fields may be small, they can significantly reduce the cache hit rate.

    4.3 Use Retrieval Instead of Injecting Entire Documents

    Split long documents into passages and retrieve only the most relevant sections for the current question. This reduces the input size and decreases the chance that irrelevant content will distract the model. Retrieval settings, such as passage length and the number of returned passages, should be determined through an evaluation set rather than fixed purely from experience.

    4.4 Minimize Tool Responses

    Tool APIs often return many fields that the model does not need. Before passing a tool result to the model, retain only the fields required for the task. This can substantially reduce input token usage.

    5. Control Output Costs

    Output tokens are usually more expensive than input tokens, so reducing unnecessary output can have a significant impact. Common approaches include:

    • Constrain the format: For classification and extraction tasks, require only the specified fields. For example, return a structured result containing only the category and confidence score, without an explanation.
    • Limit the length: Specify a maximum response length in the prompt and set the maximum output length in the request parameters to prevent unnecessary elaboration.
    • Use layered output: Return the conclusion first, and request additional details only when the user or the next workflow step needs them.

    The more consistent the output format, the more reliable downstream parsing becomes—and the lower the retry rate is likely to be.

    6. Route Requests by Task Difficulty

    Not every task requires the most capable model. Simple tasks such as classification, extraction, and rewriting can be handled by a lightweight model, while complex reasoning tasks can be routed to a more capable model.

    1. function selectModel(task):
    2. if task.type in {classification, extraction, rewriting}
    3. and task.difficulty < 0.4:
    4. return lightweightModel
    5. if task.requiresMultiStepReasoning:
    6. return advancedModel
    7. return standardModel

    A more conservative strategy is lightweight first, advanced when necessary: use a lightweight model initially, then apply validation rules to determine whether the result is acceptable. Escalate to an advanced model only when validation fails.

    The expected cost can be estimated as:

    Expected cost = cost of one lightweight-model call + escalation rate × cost of one advanced-model call

    For example, if a lightweight-model call costs 0.1 units, an advanced-model call costs 1 unit, and the escalation rate is 15%, the expected cost is:

    0.1 + 0.15 × 1 = 0.25 units

    This is one quarter of the cost of using the advanced model for every request. The escalation rate should be continuously calibrated using production data.

    7. Protect Quality: Cost Optimization Must Not Reduce Accuracy

    Every cost-reduction measure can affect output quality, so it must be accompanied by systematic evaluation.

    1. Build an evaluation set: Collect several hundred real samples with reference answers, covering both common and edge cases.
    2. Track three types of metrics together: Accuracy, end-to-end latency, and cost per task. Looking only at cost can lead to poor decisions.
    3. Change one variable at a time: For example, adjust only the context length or only the routing threshold so that the impact can be isolated.
    4. Define acceptance thresholds: For example, allow a release only when accuracy drops by no more than one percentage point and task cost decreases by more than 20%. The exact thresholds should reflect the business risk tolerance.

    8. Monitoring and Alerts

    Cost problems often become visible only after deployment, so continuous monitoring is necessary. Record the token counts, cache status, model identifier, and task identifier for every call in the logging system. Recommended dashboards and alert rules include:

    • P50 and P95 cost per task
    • Cache hit rate, segmented by business line and prompt version
    • Retry rate and escalation rate
    • Week-over-week changes in average output token count

    Trigger an alert when the P95 task cost exceeds the budget by 20%. Include the most recent prompt or routing-rule changes in the alert context so that the cause can be investigated quickly.

    9. Implementation Plan

    1. Identify the task types in the business and establish the current cost-per-task baseline for each type.
    2. Integrate the accounting script and associate call logs with task IDs.
    3. Restructure prompts by placing stable content first, then check how the cache hit rate changes.
    4. Build an evaluation set and run controlled experiments for model routing and context trimming.
    5. Launch monitoring dashboards and alerts, then review cost and quality trends every week.

    Following these five steps can help most teams significantly reduce overall LLM API spending without compromising result quality.