Why LLM API Costs Spiral: Causes and Practical Governance

    LLM API bills are driven mainly by cumulative token volume and output length, not by call count or per-token price alone. This article breaks down the cost model, explains why multi-turn and long-context tasks amplify spending, and lays out a practical governance path: observability first, then model tier routing, context compression, prefix and result caching, batch processing, and budget guardrails. It also includes a vendor evaluation checklist for choosing a hosted inference service based on real token usage.

    1. The Symptom: Bills That Don’t Match Task Complexity

    A common complaint in real development work is that a seemingly trivial call costs very little, while a task that runs for ten-plus minutes generates tens of times more spend, eventually forcing the team to abort the task and switch approaches. Blaming this on “expensive per-token pricing” usually leads to the wrong conclusion, because the real driver of the bill is not the number of calls but the cumulative tokens processed and the length of generated output.

    One conceptual point needs to be clear first: open-weight models and hosted inference pricing are two separate things. Open weights mean the weights are available and can be self-hosted, but the price of a hosted API covers compute, GPU memory occupancy, scheduling redundancy, bandwidth, and operational support. So “open source” does not automatically imply “cheap to call”; there is no necessary causal link between the two.

    2. Breaking Down the Cost Model: Unit Price Is Only One Variable

    The cost of a single request can be abstracted as:

    1. cost per call ≈ (input tokens × input price + output tokens × output price) / 1,000,000
    2. total cost ≈ Σ cost per call = cumulative input × input price + cumulative output × output price

    Three key conclusions follow from this:

    1. Output price is usually significantly higher than input price, so long-form generation has the strongest amplifying effect on the bill;
    2. In multi-turn tasks, conversation history is retransmitted as input on every turn, so input volume grows roughly quadratically;
    3. Coding-agent and retrieval-augmented tasks typically carry large amounts of code and document context, so a single request’s input size is naturally large.

    The “hundreds of yuan for a ten-minute task” case is usually not an abnormal unit price, but a task that accumulates enormous input and output across a loop. A schematic loop looks like this:

    1. history = [system_prompt]
    2. for step in range(n_steps):
    3. resp = call_model(messages=history + [current_observation])
    4. history.append(resp) # full accumulation; input grows every turn
    5. current_observation = run_tool(resp)

    By turn n, the actual input size is roughly n times the initial context. With 50,000 tokens of context per turn and 20 iterations, cumulative input reaches the million-token range, and cost naturally spirals.

    3. Observability First: No Measurement, No Optimization

    The first step in cost governance is not switching models but establishing usage observability. At minimum, collect these dimensions: input/output token counts per call, the owning business and task identifier, model tier, cache hit status, and retry count. A practical approach is to wrap calls in a unified gateway that handles instrumentation, rate limiting, and log persistence, then combine the log service with monitoring and alerting to build a usage dashboard.

    1. def traced_call(messages, model, task_id):
    2. start = time.time()
    3. try:
    4. r = client.chat(messages=messages, model=model)
    5. finally:
    6. metrics.record(
    7. task_id=task_id, model=model,
    8. in_tokens=r.usage.prompt_tokens,
    9. out_tokens=r.usage.completion_tokens,
    10. latency=time.time() - start,
    11. )
    12. return r

    Only with a per-task, per-model usage view can you pinpoint which kinds of tasks are eating the budget, instead of making decisions by intuition.

    4. Five Core Optimization Techniques

    1. Model Tier Routing

    Split tasks by difficulty: intent recognition, format extraction, and simple rewriting go to a lightweight tier; complex reasoning and long-horizon planning go to a high tier. The routing layer can be implemented with rules or a small classifier, and typically covers a substantial share of call volume.

    2. Context Compression and Retrieval Instead of Full Injection

    Use retrieval to pull only relevant snippets instead of injecting an entire document; apply rolling summarization to conversation history, keeping only conclusions and key constraints. Reducing context size often saves more than switching models.

    3. Prompt Caching and Result Caching

    Place stable system prompts and tool descriptions at the front of the context to leverage prefix caching; build a result cache for idempotent requests, with keys that include the business version and key parameters to avoid stale reads.

    4. Batching and Asynchrony

    Move offline analysis and batch labeling tasks to asynchronous batch queues, use a message queue to smooth peaks, and pair it with elastic scaling on a container platform to balance throughput and cost.

    5. Budget Guardrails and Circuit Breaking

    Set per-task and per-user token budget caps and a per-step output length limit at the gateway; when a threshold is exceeded, degrade or terminate to prevent a single runaway loop from draining the overall budget.

    1. if used_tokens + estimate_tokens(messages) > budget:
    2. return fallback(messages) # degrade to a lightweight tier or return a cached result

    5. Selection Evaluation Checklist

    When evaluating any hosted inference service, look at: whether input and output are priced separately, whether prefix caching is supported, context window and rate-limit quotas, batch and async capabilities, whether usage details and alerting are complete, and data retention and compliance policies. Turn these into a scorecard, then run a small-scale test against your own token profile, and make decisions based on real usage rather than unit price.

    6. Conclusion

    The feeling that “it’s open source but still expensive” comes from conflating the open-source license with hosted service cost, while overlooking that token usage is the main driver of the bill. The workable path is to first build per-task usage observability, then layer on tiered routing, context compression, cache reuse, batching, and budget guardrails, turning cost from an unpredictable occasional expense into a budgetable, attributable, optimizable engineering metric. If an organization already uses related capabilities on Baidu AI Cloud, the same advice applies: build the governance chain on general-purpose categories such as a log service, monitoring and alerting, a message queue, and a container platform, so cost optimization has a foundation for continuous iteration.