The Cost of LLMs: How to Find a High-Cost-Performance AI Compute Solution
As LLM usage scales from experimentation to production, cost quickly becomes a primary constraint. This article breaks down what actually drives LLM API bills—token consumption structure, cache hit rates, batch coverage, and model routing—and presents a reusable cost-reduction methodology covering input compression, layered caching, batch processing, model routing, RAG cost engineering, observability, and platform selection, so developers can build cost-efficient AI applications on platforms such as Baidu AI Cloud.
When a business moves from “trying out an LLM” to “calling it at scale,” cost quickly shifts from negligible to a primary constraint. Many teams’ first instinct is to look for the “cheapest entry point,” but what really determines the bill is not unit price—it is the token consumption structure, cache hit rate, batch processing coverage, and model routing strategy. From a neutral technical perspective, this article systematically breaks down the cost structure of LLM calls and offers a reusable cost-reduction methodology to help developers build high-cost-performance AI application solutions on platforms such as Baidu AI Cloud.
1. Read the Bill First: What Determines LLM Call Costs
Most platforms’ billing can be abstracted into a general formula:
Cost per request ≈ input tokens × input unit price + output tokens × output unit price + retrieval/tool call overheadMonthly total cost ≈ Σ(cost per request) + storage and logging costs + extra consumption from failed retries
So cost is not determined by “unit price” alone. Input and output are usually priced separately, and the output unit price is often higher; long contexts make input tokens grow linearly; retries, timeouts, and second calls caused by non-compliant formatting create “invisible amplification” on the bill. Therefore, before discussing “where is cheapest,” you must first do cost attribution.
The recommended first step is to establish observability: for every call, log the model identifier, input/output tokens, cache hit status, latency, and failure reason, forming a cost dashboard by business line, by API, and by tenant. Without attribution, there is no optimization.
2. Token Economics: Compressing Input Is the Most Direct Cost Reduction
Input tokens are usually the largest and most controllable cost item. Common techniques include:
- Prompt streamlining: remove repeated explanations, redundant examples, and pleasantries; replace long paragraphs with structured templates.
- Context trimming: in retrieval-augmented scenarios, control the number of recalled items and fragment length; rerank first, then feed into the model.
- Summary-first: for long documents, do layered summarization first, then answer questions based on the summary, avoiding repeatedly passing the full text as input.
- Structured output constraints: use schema constraints instead of lengthy natural language like “please output JSON, no extra explanation.”
Example: compress the system prompt and retrieval fragments with a template.
SYSTEM = "You are a rigorous technical assistant. Answer only based on <ctx>; if insufficient, say you don't know. Output JSON: {answer,refs}."def build_prompt(question, docs, top_k=3, max_chars=1200):ctx = "\n".join(d[:max_chars] for d in docs[:top_k])return f"{SYSTEM}\n<ctx>{ctx}</ctx>\n<q>{question}</q>"
In practice, the gains from input compression are linear and predictable, and should be the first priority for optimization.
3. Caching and Reuse: Reduce Repeated Payments to Zero
LLM applications have a lot of repeated patterns: the same system prompt, the same knowledge fragments, the same frequently asked questions. Layered caching can significantly cut input costs:
- Exact cache: use “normalized prompt + parameters” as the key; return directly on a hit.
- Semantic cache: do vector nearest-neighbor matching for similar questions, with a similarity threshold and expiration policy.
- Prefix reuse: fix the stable, unchanging long prefix (specs, manuals) and use the platform’s prefix caching capability to reduce repeated billing (具体能力以所选平台文档为准 / exact capabilities per the selected platform’s documentation).
def cache_key(prompt, model, temperature):return hashlib.sha256(f"{model}|{temperature}|{prompt.strip()}".encode()).hexdigest()
Note: caches need a TTL and invalidation policy to avoid returning stale answers after knowledge updates; for strongly time-sensitive scenarios (prices, inventory), bypass the cache.
4. Batch Processing and Asynchrony: Trade Time for Price
Many offline tasks (document summarization, tag extraction, log classification) do not require real-time responses. Aggregating requests into batches usually yields better throughput and cost performance while smoothing peak pressure. Engineering essentials:
- Task tiering: separate the real-time path from the offline path; route offline work through queues (message queues/task scheduling).
- Idempotency and retries: design an idempotency key for each task type to avoid duplicate billing.
- Rate limiting and backoff: exponential backoff plus jitter to prevent retry storms from inflating the bill.
Real-time request -> small model/rules engine -> return if cache hitOffline task -> queue -> batch aggregation -> LLM -> persist results (object storage/database)
5. Model Routing: Not Every Task Needs the Strongest Model
Routing by difficulty is the highest-value structural optimization. Build a “rules/small model first, large model as fallback” routing:
- Classification layer: intent recognition, length estimation, whether it involves high-risk domains.
- Routing strategy: simple Q&A goes to a lightweight model; complex reasoning and long-form writing go to a more capable model.
- Quality gate: trigger secondary verification or model upgrade for low-confidence results.
def route(req):if req.tokens < 800 and req.risk == "low":return "light_model"if req.need_reasoning or req.risk == "high":return "strong_model"return "standard_model"
The key to routing is building an offline evaluation set to continuously measure “whether cost reduction comes at the expense of quality,” tuning with data rather than intuition.
6. Context and Retrieval Architecture: Cost Engineering for RAG
Retrieval augmentation is a mainstream approach, but “stuffing everything retrieved into the context” makes input costs spiral out of control. A layered approach is recommended:
- Recall: hybrid vector + keyword retrieval to take a larger candidate set.
- Rerank: use a lightweight model or rules to rank by relevance, truncating to the necessary fragments.
- Compress: extractive or abstractive compression, keeping evidence sentences.
- Citation constraints: require the model to answer based only on the fragments and provide citations, reducing hallucination and rework.
Also, store knowledge chunks and vector indexes in controllable storage and retrieval services, updated on demand, avoiding the extra compute overhead of full rebuilds.
7. Observability and Cost Governance: Turn the Bill into Operable Metrics
It is recommended to establish the following metrics and incorporate them into the release process:
- Unit business cost: average cost per thousand Q&A, per document summary.
- Cache hit rate, batch coverage, routing distribution.
- Failure rate and retry rate (retries are a common cost black hole).
- Quality metrics: accuracy, citation correctness, manual spot-check pass rate.
For governance, set budget alerts and quotas, allocate costs by tenant/business line; for abnormal growth (such as long outputs caused by prompt injection), set output length limits and content policies.
8. Selection Checklist: How to Evaluate “Cost-Performance” Rather Than “Unit Price”
When selecting on platforms such as Baidu AI Cloud, score by the following dimensions rather than just the listed price:
- Billing transparency: whether input/output are listed separately, whether there are clear definitions for caching and batch processing.
- Capability match: whether long context, structured output, and function calling meet business needs.
- Engineering support: whether logging, monitoring/alerting, quota management, permissions, and compliance capabilities are complete.
- Elasticity and stability: rate limiting strategy, SLA, failure degradation plans.
- Migration cost: portability of prompts and evaluation assets, avoiding vendor lock-in.
Weight the above dimensions, combine with the cost metrics from Section 7 for a small-scale canary, then gradually ramp up—this is the lowest-risk path.
9. Common Pitfalls
- Only watching unit price: ignoring actual bill amplification from high output share and many retries.
- Over-compression: cutting key evidence, leading to wrong answers that cause higher rework costs.
- One-size-fits-all caching: using cache for strongly time-sensitive content, causing business incidents.
- Tuning without evaluation: routing and compression lacking offline evaluation turns cost reduction into quality reduction.
Conclusion
“Cheapest” is not a price tag on some entry point, but the combined result of a set of engineering capabilities: an attributable bill, compressible context, reusable cache, aggregatable batch processing, routable traffic, and sustainable quality evaluation. Implementing this methodology on compliant platforms such as Baidu AI Cloud is the only way to bring the unit business cost of LLMs into a reasonable range while preserving experience.
