Cutting LLM Costs in Practice: What Enterprises Should Calculate Beyond Unit Prices

    Lower per-token prices do not guarantee a lower bill. This article explains how call volume, input length, and output length drive LLM API costs. It covers a total cost of ownership estimate, model routing, semantic caching, output length control, a demo routing and caching example, and a checklist to review before launch.

    Lower unit prices do not always lower the bill. LLM API costs depend on three things: the number of calls, the input length of each request, and the output length of each request. A newer model with a lower unit price can still raise total spending if the way it is called does not change. This article starts with the cost structure, then covers practical control methods and includes a code example for demonstration only.

    1. Why the bill did not fall when the unit price dropped

    Most vendors charge by token, with separate prices for input and output. Output tokens usually cost more than input tokens. The exact ratio depends on each vendor’s pricing page. A newer model lowers the input price, but its gains often come with three changes. Each one raises the cost of every request.

    First, context windows have grown. New models can process hundreds of thousands or even millions of tokens of context. This encourages developers to put more material into the prompt. In retrieval-augmented generation (RAG) systems, a loose retrieval strategy sends many irrelevant documents with each request, and the number of input tokens grows quickly.

    Second, outputs have become longer. More capable models tend to give fuller reasoning and explanations. If the business only needs a single classification label but the model returns a full analysis, output token costs rise noticeably.

    Third, agent architectures multiply the number of calls. One user task may require the model to plan, choose a tool, read the result, and then write an answer. Each step is a separate API call, so the total call volume can be several times the number of user-facing requests.

    2. Use total cost of ownership (TCO) to see the full picture

    When you evaluate LLM costs, look at total spending, not just the unit price. You can estimate the monthly cost with this formula:

    Monthly cost = average daily requests × 30 × [average input tokens ÷ 1,000 × input price + average output tokens ÷ 1,000 × output price] × (1 − cache hit rate) + other infrastructure costs

    The table below explains each metric. The example values are assumptions only and do not represent any vendor’s actual prices.

    Metric Meaning Example value (assumed)
    Average daily requests Number of requests sent to the model each day 10,000
    Average input tokens Length of the prompt and context in each request 2,000
    Average output tokens Length of the model’s response in each request 500
    Input price Price per 1,000 input tokens CNY 0.002
    Output price Price per 1,000 output tokens CNY 0.008
    Cache hit rate Share of requests answered without calling the model 30%

    With these values, each request costs 2 × 0.002 + 0.5 × 0.008 = CNY 0.008. The daily cost is 10,000 × 0.008 = CNY 80, and the monthly cost is about CNY 2,400. When the cache hit rate rises to 30%, fewer calls reach the model, and the monthly cost drops to about CNY 1,680.

    TCO should also include business value. If one request produces conversions or labor savings that far exceed its call cost, a high call cost may be acceptable. Conversely, low-value requests add waste over time, even when each call is cheap.

    3. Model routing: not every request needs a flagship model

    Sending every request to the most powerful model is one of the most common sources of waste. A better approach is to route requests by task difficulty. Tasks such as text classification, entity extraction, and simple question answering can usually be handled by a lightweight model. Tasks such as complex reasoning, code generation, and long-document summarization can go to a higher-tier model.

    You can start with three routing approaches. The first is configurable rules, such as routing by input length, keywords, or task type. These rules are simple to implement and easy to debug. The second is a small classifier trained on historical labeled data to predict task difficulty. Its accuracy is usually higher than that of fixed rules. The third is an API gateway that manages multiple models in one place. Examples include the open-source gateway LiteLLM, which you can self-host, and unified model access platforms from cloud providers. Several cloud providers in China and abroad offer such services. When you compare options, check billing granularity, model coverage, latency, and data compliance terms.

    Routing can misclassify requests, and the two types of error have different costs. Classifying a complex task as simple lowers answer quality. In customer service, healthcare, and legal applications, that can have serious consequences. Classifying a simple task as complex only costs more money. For this reason, set thresholds that favor the higher-quality model, and check the misclassification rate regularly with sampled evaluations.

    4. Semantic caching: the hit rate depends on the threshold and evaluation

    Semantic caching works like this: convert the user’s question into a vector, then compare its similarity with the vectors of earlier questions. When the similarity exceeds a threshold, return the cached answer directly. Caching reduces model calls for repeated questions, but the benefit depends on the use case. In customer service and frequently asked questions (FAQ) scenarios, users often phrase the same questions in similar ways, so the hit rate is usually high. In open-ended creative writing, requests rarely repeat, so the hit rate is limited. Measure the actual hit rate by replaying online request logs. Do not rely on rule-of-thumb figures.

    When you use semantic caching, pay attention to the following issues.

    1. Tune the threshold. A high threshold lowers the hit rate and limits savings. A low threshold can return wrong answers for questions with different meanings. Prepare a set of labeled question pairs, then test the accuracy and hit rate at different thresholds.
    2. Set expiration rules. After a knowledge base update, a model version change, or a prompt change, old cache entries may no longer be correct. Time-sensitive questions, such as “today’s exchange rate,” should not be cached.
    3. Protect privacy. The cache stores users’ original questions, which may contain names, phone numbers, or other personal information. Remove personal data before writing to the cache, and set access permissions and retention periods for cached data.
    4. Use dedicated storage in production. The in-memory lists in the example cannot be shared across processes and do not persist. A production deployment should use Redis, a vector database, or storage with a vector index.

    5. Prompt constraints: control output length

    Output tokens cost more than input tokens, so controlling output length can save significantly. Common methods include the following.

    • State the length in the prompt, for example, “Answer in no more than 50 words.”
    • Require structured output, for example, “Output only JSON, with no explanation.” Downstream programs can parse the result directly, and the response contains less extra text.
    • Set a maximum output token count in the API parameters as a final safeguard.

    Overly strict constraints can drop necessary information. For example, truncated JSON cannot be parsed. After you change a constraint, check the output quality again, and add retry or fallback logic for parsing failures.

    6. Example code: for illustration only, not for direct production use

    The code below shows how routing and semantic caching work together. The model calls are placeholder functions. In real use, replace them with the actual SDK calls, and set timeouts, retries, and rate limits. The thresholds and routing rules are examples only. Tune them with your own data.

    1. # Dependencies: pip install sentence-transformers numpy
    2. import numpy as np
    3. from sentence_transformers import SentenceTransformer
    4. # The example uses the open-source Chinese embedding model bge-small-zh-v1.5. You can replace it with another embedding model.
    5. embedder = SentenceTransformer("BAAI/bge-small-zh-v1.5")
    6. SIM_THRESHOLD = 0.92 # Example value. Tune it with labeled data. Do not copy it directly.
    7. def get_embedding(text: str) -> np.ndarray:
    8. # normalize_embeddings=True makes each vector length 1, so the dot product equals cosine similarity
    9. return embedder.encode(text, normalize_embeddings=True)
    10. def call_lightweight_model(prompt: str) -> str:
    11. # Placeholder function. Replace with a real lightweight model SDK call, and set a timeout.
    12. return f"[轻量模型] 对“{prompt[:20]}”的回复"
    13. def call_flagship_model(prompt: str) -> str:
    14. # Placeholder function. Replace with a real flagship model SDK call, and set a timeout.
    15. return f"[旗舰模型] 对“{prompt[:20]}”的深度回复"
    16. def is_complex(prompt: str) -> bool:
    17. # These rules are examples only. In production, combine them with business data or a small classifier.
    18. keywords = ("推理", "总结", "代码", "分析")
    19. return len(prompt) > 500 or any(k in prompt for k in keywords)
    20. class CostAwareRouter:
    21. def __init__(self):
    22. # Production should use a vector database or storage with a vector index.
    23. self.cache_vecs = []
    24. self.cache_resps = []
    25. def _search_cache(self, vec: np.ndarray):
    26. if not self.cache_vecs:
    27. return None
    28. mat = np.stack(self.cache_vecs)
    29. sims = mat @ vec
    30. idx = int(np.argmax(sims))
    31. if sims[idx] >= SIM_THRESHOLD:
    32. return self.cache_resps[idx]
    33. return None
    34. def query(self, prompt: str) -> str:
    35. vec = get_embedding(prompt)
    36. cached = self._search_cache(vec)
    37. if cached is not None:
    38. return cached # Cache hit. No model call cost.
    39. try:
    40. if is_complex(prompt):
    41. resp = call_flagship_model(prompt)
    42. else:
    43. resp = call_lightweight_model(prompt)
    44. except Exception:
    45. # On failure, return a fallback message and do not write to the cache, so wrong results are not returned repeatedly.
    46. return "服务暂时繁忙,请稍后再试。"
    47. self.cache_vecs.append(vec)
    48. self.cache_resps.append(resp)
    49. return resp
    50. if __name__ == "__main__":
    51. router = CostAwareRouter()
    52. print(router.query("帮我写一首关于春天的诗"))

    7. Checklist before launch

    Before launch, confirm the following items one by one.

    1. Replay real production requests to measure cost, cache hit rate, and routing misclassification rate. Do not rely only on hand-written samples.
    2. For high-risk scenarios, turn off automatic routing and caching, or add human review.
    3. Set expiration rules for the cache. Clear related entries when the knowledge base or model version changes.
    4. Remove personal information from cache entries and logs, and restrict access to them.
    5. Set fallback plans for timeouts, rate limits, and model errors.
    6. Set cost alerts, monitor token usage daily, and catch unusual call patterns early.

    The goal of cost control is to reduce unnecessary calls while keeping quality acceptable. Each measure needs a measurable metric. Decide whether to keep or adjust it based on online data.