LLM API Selection and Cost Optimization: A Practical Guide
This guide explains how to choose a large language model API based on engineering criteria rather than brand preference. It introduces a four-dimension evaluation framework covering quality, latency, throughput, and cost, shows how weighted-token credit billing drives real spending, and maps model tiers to specific workloads. It also covers practical cost controls such as prefix caching, output budgets, semantic routing with fallback, and observability. The goal is to balance output quality, user experience, and the bill under real constraints.
1. Why Model Choice Cannot Be Made by Intuition
In real projects, teams often run into an awkward situation: the demo looks great, but once real traffic arrives the bill inflates quickly and response times start to fluctuate. The reason is not complicated — model capability, service latency, and billing are coupled to each other. Making a decision while looking at only one of them means paying for it on the other two.
Public benchmark data shows how differently models behave on the same batch of requests. Some finish in around one second with output speeds of tens of tokens per second; others take more than thirty seconds per request with output speeds of only single-digit tokens per second. Credit consumption ranges from a few hundred to over ten thousand, and the per-token credit cost can differ by tens of times. This means the “strongest model” and the “most suitable model” are often two different answers.
Model selection should therefore be treated as an engineering decision, not an expression of brand preference. The method below is reusable.
2. A Four-Dimension Evaluation Framework
Score candidate models in a shared four-dimension coordinate system:
- Quality: task completion rate on your own business dataset, structured output compliance rate, and long-context recall rate.
- Latency: time to first token (TTFT) and end-to-end total time, which affect interactive experience differently.
- Throughput: output tokens/s, which determines the actual wait for long-form generation.
- Cost: credits consumed per request, plus the ratio of credits to total tokens.
The key point: all dimensions must be measured on the same batch of requests, with the same prompts and the same temperature and max output settings, otherwise the numbers are not comparable. In practice, a simple load-test script can fix the input and output size:
# Skeleton: comparison load test with fixed input/output sizecases = [{"prompt": p, "max_tokens": 512} for p in sample_prompts]for model in candidates:for c in cases:t0 = time.perf_counter()resp = client.chat(model=model, messages=[{"role": "user", "content": c["prompt"]}],max_tokens=c["max_tokens"])cost_ms = (time.perf_counter() - t0) * 1000usage = resp.usage # input/output/cached tokensrecord(model, cost_ms, usage)
3. Reading Credit-Based Billing: How to Estimate Cost Correctly
Most platforms bill with “weighted tokens”, generally in this form:
credits = input tokens × input multiplier + cache write tokens × cache write multiplier + cache read tokens × cache read multiplier + output tokens × output multiplier
This formula explains three common observations:
- Output is far more expensive than input. Typical multiplier tables show the output multiplier is several times the input multiplier, and for flagship models the gap can exceed twenty times. So “making the model write less filler” is the most direct way to save money.
- Caching is the leverage point. The cache read multiplier is usually only a small fraction of the input multiplier. Putting stable system prompts, knowledge snippets, and tool descriptions at the front as a cacheable prefix significantly reduces the cost of long sessions.
- Unit cost should be measured as credits per total token. A short total time does not mean cheap — long chain-of-thought models often emit more tokens, so credits per total token can actually be higher.
A practical estimation function:
def estimate_credits(inp, out, cache_write=0, cache_read=0, r=(1, 4, 1.25, 0.25)):ri, ro, rw, rr = rreturn inp*ri + out*ro + cache_write*rw + cache_read*rr
4. Scenario-Based Tiering: Put Each Model in the Right Place
- High-concurrency light tasks (classification, extraction, format conversion, intent recognition): choose small-parameter, high-throughput, low-multiplier models, and focus on TTFT and stability.
- Complex reasoning and code generation: choose a tier with stronger reasoning and code ability, accept a higher unit cost, but strictly cap the maximum output length.
- Long-document processing: prefer options that support long context with cheap cache reads, and use segmented summarization to reduce per-request input size.
- Interactive conversation: output speed is the core metric. Models below ten tokens per second are not suitable as the main path for real-time conversation.
5. Cost Control in Practice
- Prefix caching: put invariant instructions and knowledge at the front, keep the prefix byte-level stable, and avoid polluting the cache with volatile content such as timestamps.
- Output budget: set a max_tokens cap per task type and disallow unbounded generation.
- Semantic routing and fallback: use a lightweight model to judge difficulty first and escalate hard problems; the main path can fall back automatically on timeout.
def route(task):if task["difficulty"] == "hard":return "reasoning_tier"if time.now() - task["start"] > SLA_MS:return "fast_tier"return "cheap_tier"
- Observability: instrument TTFT, total time, input/output/cached tokens, and credits, aggregate by business line, and build a cost dashboard with alerts.
6. Conclusion
There is no single right answer for model selection, only an optimal solution under constraints. Use the four-dimension framework for benchmarking, the weighted-token formula for budget estimation, and close the loop with caching, output budgets, routing and fallback, and monitoring — that is how you balance quality, experience, and the bill. If you need to host multiple model types and compute resources together, you can build your own evaluation and cost governance pipeline on top of general capabilities from Baidu AI Cloud (such as the container platform, log service, monitoring and alerting, and object storage), turning selection from experience-based judgment into a data-driven process.
