LLM API Cost per Task: Why Unchanged Unit Prices Can Still Raise Your Bill

    Comparing LLM APIs by price per million tokens leaves out how many tokens a task actually consumes and how each token type is billed. This article explains how to calculate cost per task, why longer outputs and retries can raise a bill even when unit prices stay the same, and how prompt structure, caching, output constraints, and model routing help control spending. It also covers what to check before moving to production.

    1. Unchanged Unit Prices Can Still Mean a Higher Bill

    Many developers compare models by looking only at the price per million tokens. This comparison leaves out two variables: the number of tokens actually billed, and the price differences between token types. A more useful metric is the cost per task, meaning the total spend to complete one full task.

    The formula for cost per task is:

    Cost per task = uncached input tokens × input price + cached input tokens × cache price + output tokens × output price

    Two points matter here. First, cached tokens are not free. They are billed at a discounted rate below the standard input price. Second, some providers charge an extra fee when a cache entry is first written. Check the official pricing sheet of each provider for the exact rules.

    Here is a hypothetical example. Set the input price to 1, the cache price to 0.2, and the output price to 4, all in relative units. A request has 10,000 input tokens, of which 8,000 hit the cache, and produces 1,000 output tokens:

    • Uncached input: 2,000 × 1 = 2,000
    • Cached input: 8,000 × 0.2 = 1,600
    • Output: 1,000 × 4 = 4,000
    • Total: 7,600

    If a new model version raises the output for the same task to 1,500 tokens, with everything else unchanged, the output cost becomes 6,000 and the total becomes 9,600. The unit prices did not change, but the cost per task rose by about 26%. Developers need to watch for exactly this case.

    Output tokens tend to increase for several reasons. The model may show more of its reasoning, write more detailed comments, or run more boundary checks. These changes can be valuable for some tasks. For simple tasks, they may be pure overhead.

    Other boundary conditions also matter. When a cache entry expires, it must be written again. Setting the output token limit too low can truncate the answer and trigger a retry. Retries and loop calls can bill the same task multiple times. All of these factors should be included when you measure cost per task.

    2. Where Capability Gains Apply

    Newer models have improved at programming, security analysis, and long-running agent tasks. The size of the gain depends on the model version and the specific task. Higher benchmark scores do not mean every scenario improves, so validate with your own data before deploying.

    Deep programming and code refactoring. The model can read a larger range of code context, propose refactoring based on the existing structure, and trace some cross-file call relationships. Actual results depend on codebase size, context window size, and coding style. Test with a set of representative past tasks, and record whether the modified code passes the original tests. Do not judge only by whether the generated code looks reasonable.

    Defensive security analysis. The model can help analyze anomaly patterns in system logs. It can point out common vulnerability types during code review, such as SQL injection and cross-site scripting, and suggest fixes. Its output should serve as input for security engineers, not replace a manual audit. Limit this use to defensive and audit scope, and keep a human review step.

    Long-running agent tasks. An agent must maintain state across multi-step, multi-turn interactions and recover after errors. The model has improved at task decomposition and error recovery. During long tasks, however, it can still drift from the goal or repeat ineffective actions. Developers should design their own state storage, step limits, and loop detection, and should not hand all of this responsibility to the model.

    3. Use Caching to Lower Direct Costs

    The core idea of caching is to keep the prefix of each request identical. Place the system prompt, tool definitions, and fixed reference documents at the start of the request, and put dynamic user input at the end. When the prefix stays the same, the server is more likely to hit the cache.

    The following example shows this structure:

    1. # Put the fixed system prompt first so every request has the same prefix
    2. SYSTEM_PROMPT = (
    3. "You are a code audit expert. "
    4. "Check the code against security standards and output only the risk level and a list of issues."
    5. )
    6. def audit_code(code_snippet: str) -> str:
    7. # Place dynamic content last so it does not break the prefix cache
    8. response = llm_api.chat(
    9. system=SYSTEM_PROMPT,
    10. user=f"Audit the following code:\n{code_snippet}",
    11. enable_cache=True,
    12. )
    13. return response.text

    Two practical recommendations follow. First, do not embed timestamps, request IDs, or other values that change on every call in the system prompt. Otherwise, the cache cannot hit. Second, track the cache hit rate continuously. If the rate stays low for a long time, the prefix is often being changed unintentionally, or the interval between requests exceeds the cache’s validity period.

    4. Constrain Output Length and Format

    The most direct way to control output tokens is to state the limits explicitly in the prompt. A reusable constraint template has five parts: role, task, output format, length limit, and prohibitions.

    1. Role: You are a backend code review assistant.
    2. Task: Review the functions provided by the user and identify possible security issues.
    3. Output format: Output strictly in JSON that conforms to the schema below.
    4. Length limit: The issues array has at most 5 items, and each item is no longer than 40 characters.
    5. Prohibitions: Do not explain the reasoning process, and do not output full code fixes.

    If the downstream system needs to parse the result, use a JSON Schema to constrain the output structure directly:

    1. {
    2. "type": "object",
    3. "properties": {
    4. "risk_level": {
    5. "type": "string",
    6. "enum": ["low", "medium", "high"]
    7. },
    8. "issues": {
    9. "type": "array",
    10. "items": {"type": "string"},
    11. "maxItems": 5
    12. }
    13. },
    14. "required": ["risk_level", "issues"]
    15. }

    Structured output reduces customer-service-style pleasantries and repeated explanations. It also makes the results easier for programs to process. Be aware that overly strict constraints can lower quality, so compare accuracy with and without the constraints before going live.

    5. Model Routing and Cloud Services

    Tasks differ widely in how much intelligence they require. Sending every request to the strongest model usually creates unnecessary cost. A model routing layer can select a suitable model for each task type and apply a different retry policy to each type.

    Task type Quality requirement Cost focus Retry strategy
    Classification, field extraction Stable format, verifiable results Cost per call and response latency Retry once after a validation failure, then escalate to a human if it fails again
    Code generation High correctness Reduce total cost from rework Retry with the test error messages, and set a maximum number of rounds
    Long-running agent planning Consistent logic across steps Total tokens grow with the number of steps Set a step limit and loop detection to prevent infinite loops

    Routing can be simple, for example by looking up a model by task label. The key is to record the actual cost per task for each route so you can adjust the rules over time.

    At the infrastructure level, general-purpose cloud services can also help reduce costs. For batch tasks that do not need real-time responses, put them in a message queue and process them during low-load periods, which reduces concurrency pressure. Conversation history and long documents can go into object storage. Only the relevant fragments are retrieved and passed into the model context when needed, so each request does not carry the full history. Logging services can record the input, output, and cached token counts of each call, and trigger alerts when usage spikes.

    6. Three Metrics to Check Before Launch

    Before connecting the API to production, confirm the following three items:

    1. Cost is calculated per task. Use the formula above to compute the average cost for each task type, rather than comparing token unit prices alone.
    2. Cache hit rate and output token distribution are monitored. When the hit rate drops or output length spikes, check your prompts and request structure promptly.
    3. Token alert thresholds and retry limits are set. Set a token limit for each task, and cap the number of retries to prevent runaway costs from abnormal loops.

    Record the model version, task set, output length, and measurement period for every evaluation. Without these details, cost comparisons cannot be reproduced, and you cannot tell whether an optimization actually worked.

    Better LLM capability and cost control can go together. Measure both with the same method, and you can tell whether a model upgrade lowers your costs or raises them.