Open Source Does Not Mean Cheap: A Breakdown of LLM API Costs

    This article explains why hosted API prices for open-weight large language models remain high, breaking down the structural cost drivers behind token pricing, why agentic workloads can suddenly inflate a bill, and six practical techniques for cost governance. It also introduces a framework for comparing cost per successful output rather than raw per-token price, helping developers make measurable model selection decisions.

    1. It Starts with a Bill

    One developer’s experience is fairly typical: a small task with simple logic produced a bill of over twenty yuan, and the next day a task that ran for less than fifteen minutes cost more than one hundred yuan. To control spending, he stopped the calls and switched to a lower-priced alternative, bringing the cost under five yuan with acceptable results. He then checked the published pricing for the model he had been using: 8 yuan per million input tokens and 28 yuan per million output tokens, with a major cloud provider’s hosted service at the same rate—roughly ten times the cheaper option.

    The real question here is not “which one should I pick,” but a more general technical one: why is the hosted API of a model with open weights still not cheap? What is the actual relationship between open source and API pricing?

    2. Open Source, Open Weights, and API Billing Are Three Different Things

    Before discussing cost, it helps to clear up a common misconception: open source does not mean zero cost, nor does it guarantee a low API price.

    • Open source / open weights address whether you can self-deploy, inspect, and fine-tune a model. They lower the barrier to entry, not the cost of inference.
    • API billing buys you a usable inference service, which includes compute, GPU memory, networking, scheduling, operations, and reliability guarantees.
    • Unit price is determined by supply and demand together with product positioning, and has no necessary causal link to whether weights are public.

    So treating “open source” as a premise for “should be cheaper” is a logical leap. What actually determines the bill are the structural factors below.

    3. Six Structural Reasons API Unit Prices Are High

    3.1 Autoregressive decoding makes unit cost rigid

    LLM inference has two phases: prefill and decode. Prefill processes the input sequence in parallel and is compute-intensive; decode generates tokens one at a time and is mainly limited by memory bandwidth. Output tokens cannot be produced in parallel, so the output price is generally much higher than the input price—in this example, output is 3.5 times the input price, which is a common range in the industry. This is not an arbitrary pricing choice but a reflection of the underlying resource consumption structure.

    3.2 Long context brings non-linear memory and attention costs

    Attention computation rises quickly as sequence length grows, and the KV Cache expands linearly with context length. The larger the context window, the more GPU memory each request occupies, the fewer requests can run concurrently, and the higher the fixed cost allocated per token. A task that “looks short” can cost far more than expected if it carries a large amount of code or documentation as context.

    3.3 Quality service itself has a cost

    A production-grade API needs to provide more than the model’s forward pass: elastic scaling, multi-availability-zone failover, rate limiting and quotas, logging and monitoring alerts, content safety, compliance auditing, and more. These capabilities exist as fixed costs and ultimately show up in the unit price. Part of what you pay for is stability, not tokens.

    3.4 Caching and scheduling optimizations may not cover your call pattern

    The industry commonly uses prefix caching, continuous batching, quantization, and speculative decoding to reduce unit cost. But these optimizations work best for workloads with stable prefixes and homogeneous requests. If the system prompt and context differ on every request, cache hit rates stay low and the optimization gains never reach your bill.

    3.5 Small teams struggle to amortize fixed costs

    Model hosting requires long-term occupancy of high-value accelerator resources, with redundancy reserved for peak capacity. Teams with low call volume cannot achieve economies of scale, leaving little room for the unit price to drop.

    3.6 Product positioning and demand rigidity

    More capable models with longer context windows usually target quality-sensitive scenarios where demand is price-inelastic, so pricing tends to follow value-based rather than cost-based logic.

    4. Why the Bill Suddenly Grows: A Quantitative Walkthrough

    Suppose a task has 120,000 input tokens and 20,000 output tokens, priced at 8 yuan and 28 yuan per million tokens:

    1. Input cost = 120000 / 1e6 * 8 ≈ 0.96 yuan
    2. Output cost = 20000 / 1e6 * 28 ≈ 0.56 yuan
    3. Total per call ≈ 1.52 yuan

    To accumulate 100 yuan from calls of 1.52 yuan each takes about 66 requests of the same size. An agent-style task running for a dozen minutes, using a “think—call a tool—think again” loop that resends the full history each round, can easily go through dozens of iterations. Cost is not driven up by a single call, but amplified by iteration count and repeated context transmission.

    This walkthrough yields a reusable estimation formula:

    1. Total cost ≈ Σ(input tokens per round × input price) + Σ(output tokens per round × output price)
    2. where input tokens per round ≈ system prompt + accumulated history + new input this round

    5. Cost Governance: Six Things You Can Do Right Now

    5.1 Establish token metering and attribution

    On the application side, log input/output tokens, model identifier, business identifier, and latency for each call, producing usage reports that can be attributed by business line. Without metering, there is no optimization.

    1. def estimate_cost(in_tokens, out_tokens, in_price=8, out_price=28):
    2. return in_tokens / 1e6 * in_price + out_tokens / 1e6 * out_price
    3. # Example: accumulate by business identifier for later attribution analysis
    4. usage = {}
    5. def record(biz, in_tokens, out_tokens):
    6. cost = estimate_cost(in_tokens, out_tokens)
    7. usage[biz] = usage.get(biz, 0.0) + cost
    8. return cost

    5.2 Slim down and compress context

    Inject only the necessary fragments and retrieve them on demand instead of stuffing everything in; produce a structured summary for long documents first; apply rolling compression to conversation history, keeping conclusions and dropping the process.

    5.3 Improve prefix cache hit rates

    Put stable, unchanging content at the front of the prompt and variable content at the end so the prefix stays consistent.

    1. [fixed] System role + tool descriptions + policy constraints
    2. [fixed] Long-term knowledge fragments
    3. [variable] Current user input and newly added context

    5.4 Tiered model routing

    Route by task difficulty: send deterministic tasks like extraction, classification, and formatting to small models or a rules engine; escalate to a large model only when complex reasoning is needed.

    1. def route(task):
    2. if task["type"] in ("extract", "classify", "format"):
    3. return "small_model"
    4. if task["difficulty"] >= 3:
    5. return "large_model"
    6. return "mid_model"

    5.5 Batching and asynchronous processing

    For offline, latency-tolerant tasks, use batch interfaces, which usually offer better unit prices; use a message queue to smooth peaks and avoid reserving too much capacity for them.

    5.6 Budget guardrails and circuit breaking

    Set per-task and per-day budget caps, and trip a circuit breaker with an alert once a threshold is exceeded to prevent runaway loops.

    1. class Budget:
    2. def __init__(self, limit):
    3. self.limit, self.spent = limit, 0.0
    4. def allow(self, cost):
    5. if self.spent + cost > self.limit:
    6. raise RuntimeError("budget exceeded")
    7. self.spent += cost
    8. return True

    6. A Selection Framework: Turning “Expensive” into Something Comparable

    Do not compare unit prices; compare cost per unit of effective output:

    1. Effective cost = total spend to complete one qualified task / task pass rate

    A low-unit-price model that needs more rounds, longer prompts, or a higher retry rate to reach the same quality may end up with a higher effective cost. It is worth running a small-scale benchmark on your own business sample set, recording quality, latency, and cost across all three dimensions before deciding.

    If an organization has the engineering and operations capability, self-deployment is also worth evaluating: running your own inference service means bearing the cost of purchasing or renting accelerators, tuning the inference framework, and building scaling, monitoring, and alerting systems. It suits scenarios with high call volume and stable load; for small-to-medium scale or fluctuating workloads, a hosted API is usually better on total cost of ownership. In Baidu AI Cloud’s product portfolio, for example, the typical approach is a combination of general cloud capabilities and tiered model services that teams can mix and match per scenario.

    7. Conclusion

    Open source lowers the barrier to use, not the physical cost of inference. API pricing is determined jointly by the compute characteristics of decoding, context overhead, service level, the coverage of optimization gains, and economies of scale. For developers, there are three levers you can actually control: understand the metering basis, cut repeated context, and route tasks to models of the right size. Do these three things and your bill becomes far more predictable, and model selection shifts from “feels expensive” to measurable cost-effectiveness.