Evaluating LLM API Cost Efficiency and Practical Cost Optimization
This article explains why LLM API cost efficiency depends on effective cost per completed task rather than per-token price alone. It breaks down the four main cost levers—off-peak pricing, prefix caching, context length control, and output length limits—and shows how to use free quotas safely, with a minimal cost-control code skeleton and metrics for reproducible model selection.
1. The Core Issue: Cost Efficiency Is Effective Cost, Not Unit Price
When comparing the cost efficiency of different LLM services, the most common mistake is focusing only on the price per million tokens. The real bill is determined by four variables working together: the ratio of input to output tokens, cache hit rate, time-based pricing policies, and redundant consumption caused by context length. Comparing unit prices alone often leads to conclusions that differ from actual spending by several times.
A simplified formula helps build intuition:
Effective cost = (Input tokens × Input price × (1 - cache hit rate)+ Output tokens × Output price) / Actual tasks completed
The denominator, “actual tasks completed,” is the most easily overlooked factor. If a call fails and is retried because too much irrelevant content was stuffed into the context, the denominator shrinks and effective cost rises quickly.
2. Four Key Cost Levers
2.1 Time-Based Differential Pricing
Some platforms offer significant discounts during off-peak hours—for example, calls from night to early morning may cost far less than daytime calls. This is unfriendly to interactive products but extremely friendly to batch workloads: offline evaluation, log analysis, bulk code refactoring, data cleaning, and nightly regression tests can all be shifted to off-peak windows. In engineering terms, you only need a scheduling switch in the call layer that selects a different model alias or configuration group based on the current time.
2.2 Cache Reuse
Prefix caching typically bills on the logic that “cached portions are free or heavily discounted.” This requires the request prefix to remain stable: place the system prompt, tool definitions, and knowledge base snippets at the front and avoid meaningless changes, while putting volatile user input at the end. A common anti-pattern is concatenating a timestamp or random request ID into the system prompt, which invalidates the entire cache.
[Stable prefix: system instructions + tool schema + reference docs][Semi-stable zone: multi-turn history][Volatile zone: current user input + timestamp/session identifier]
2.3 Context Length Governance
A longer context window does not mean lower cost. Repeatedly feeding an entire document causes input tokens to grow linearly. Practical approaches include retrieving and keeping only relevant snippets, summarizing and compressing conversation history, and trimming fields from tool return results. As a rule of thumb, cutting ineffective context in half is equivalent to doubling the budget.
2.4 Output Length Constraints
Output tokens usually cost more than input tokens. Using structured output, limiting the number of fields, and requiring “return only the diff rather than the full file” can noticeably reduce spending without sacrificing usability.
3. Using Free Quotas and Trial Resources Correctly
Common promotional forms in the industry include one-time token credits for new registrations, limited-time free access to a certain model tier, and small paid packages combined with free caching policies. When using such resources, follow three principles:
- Isolate usage: run only low-risk tasks on free quotas and avoid carrying production traffic;
- Establish a capability baseline: first build a fixed evaluation set and compare the usability of different services horizontally using the same set of samples;
- Prepare fallbacks: free quotas can change at any time, so the call layer should support one-click switching to a backup configuration.
4. A Practical Cost-Control Skeleton
The sample code below shows a minimal viable cost-control layer that includes time-based routing, cache-friendly assembly, and usage accounting:
import time, jsondef build_prompt(system, docs, user_input):# Keep the stable prefix first and volatile content last to improve cache hit ratestable = system + "\n" + "\n".join(docs)return stable + "\n[User input]\n" + user_input + f"\n[req_id={user_input[:8]}]"def pick_profile(now=None):hour = (now or time.localtime()).tm_hourreturn "offpeak" if hour >= 22 or hour < 8 else "peak"def call_llm(cfg, prompt, profile):usage = cfg[profile]["invoke"](prompt)log_usage(profile, usage) # Log input/output/cache hitsreturn usagedef log_usage(profile, usage):with open("usage.log", "a", encoding="utf-8") as f:f.write(json.dumps({"profile": profile, **usage}) + "\n")
Additional recommendations: instrument input, output, and cache hits separately and connect them to monitoring and alerting; set a daily quota threshold that triggers a reminder at 80%; and apply backoff retries for failed requests to avoid wasted consumption.
5. Conclusion
To judge whether something is “more cost-efficient,” return to measurable metrics: cost per task, cache hit rate, peak/off-peak call ratio, and average context length. Build the evaluation set and accounting system first, then discuss model selection—only then are the conclusions reproducible. If you are already using the relevant model services from Baidu AI Cloud, it is likewise recommended to use this framework for baseline calculations and make decisions with data rather than impressions.
