LLM Model Selection and API Cost Optimization: A Practical Guide for Engineering Teams
Choosing a large language model is an engineering problem, not a matter of preference. This guide explains how to break down usage scenarios, build a reproducible evaluation method, understand weighted credit-based billing formulas, and apply routing, caching, and fallback patterns to control API costs while preserving user experience. It also covers quota management, observability, and a four-step rollout plan.
1. Why Model Selection Is an Engineering Problem
When teams integrate a large language model, the first question is usually “which one is the best?” In production, however, user experience is rarely determined by leaderboard rankings. It comes down to three measurable dimensions: task quality, throughput, and unit cost.
A common real-world trigger is a developer who subscribes to an AI coding service and finds that the quota drains far faster than expected, then needs to make a second purchasing decision across several candidate models.
The underlying problem is this: under a limited budget, how do you route requests to models that are “good enough and cheap”? That is why selection must start with scenarios, not models.
2. Break Down Scenarios First
Daily calls can be roughly grouped into four categories, each with different core metrics:
- Code completion and refactoring: strong context understanding and low latency; short outputs with high call frequency, so cost is extremely sensitive to latency and input multipliers.
- Long-document understanding and summarization: long inputs, short outputs; cost is driven mainly by the input side and cache hit rate.
- Creative generation and copywriting: long outputs with high sampling randomness; cost is dominated by the output multiplier.
- Structured extraction and classification: small models are sufficient; the goal is high concurrency and low unit price.
The conclusion up front: there is no universally best model, only the best combination per scenario. Turning “pick one” into “pick a set and configure routing” is the single most important step in cost optimization.
3. Build a Reproducible Evaluation Method
The original material shows a simple but effective approach: run batch scoring with fixed prompts, recording elapsed time, input/output tokens, total consumption, and throughput. To make this engineering-grade, four things need to be added:
- A fixed evaluation set: prepare 20–50 real business samples covering the four scenario categories, instead of representing all capabilities with a single creative prompt.
- Controlled variables: unify temperature, maximum output length, and system prompt so results are comparable.
- Multiple samples: run each sample 3–5 times and take the median to filter out cold-start jitter.
- Record both metric pairs: quality (human rating or automated pass rate) and performance (time to first token, tokens/s, credit consumption).
A sample evaluation record structure:
record = {"scene": "code_refactor", # scenario label"model": "model_a", # anonymized model identifier"latency_ms": 4690, # end-to-end elapsed time"in_tokens": 633,"out_tokens": 239,"score": 4.5, # 1-5 human or automated score"cost_units": 270 # normalized cost unit}
With structured data, selection turns from a “feeling” into a regression-friendly table.
4. Cost Model: The Billing Formula Matters More Than the Unit Price
Most platforms use a weighted credit system, which can be abstracted in a general form as:
consumption = input tokens × input multiplier+ cache creation tokens × cache creation multiplier+ cache hit tokens × cache read multiplier+ output tokens × output multiplier
Three practical implications follow:
- The output multiplier is usually significantly higher than the input multiplier, so long-form generation tasks should be evaluated on output-side pricing first.
- The cache read multiplier is generally far lower than the input multiplier, so a stable system prompt and reused long documents can cut costs substantially.
- Overall value = quality score ÷ unit cost, not the absolute unit price. In the original data, smaller and domestic models showed clearly friendlier “credits per total token” figures, which is exactly what this implication predicts.
Throughput then serves as a second filter:
tokens/s ≈ output tokens / (elapsed time - time to first token)effective value ≈ (quality score × tokens/s) / unit cost
For interactive code completion, weight tokens/s higher; for offline batch processing, weight cost higher.
5. Architecture: Routing, Caching, and Fallback
1. Model routing
Split traffic by scenario and difficulty: simple requests go to small models, complex reasoning goes to large models. Rules or a lightweight classifier are enough:
def route(req):if req.scene in ("extract", "classify"):return "small_model"if req.in_tokens > 8000 or req.need_strong_reasoning:return "large_model"return "mid_model"
2. Prompt and document caching
Fix the system prompt, tool descriptions, and long-document prefixes so the prefix stays byte-level stable and cache hits can occur; avoid inserting volatile content such as timestamps at the beginning of the prompt.
3. Fallback and graceful degradation
When the primary model is rate limited or times out, switch to a backup model automatically and return partial results to preserve availability. Also set a maximum output length and a timeout budget so a single request cannot consume a large amount of quota.
6. Quota Management and Observability
Running out of quota is usually not a unit-price problem but a missing budget guardrail. Recommended practices:
- Set daily quotas and concurrency limits per project or per user, and queue over-limit requests instead of failing them outright;
- Instrument every request with input, output, cache hits, and elapsed time to build dashboards and alerts;
- Automatically break circuits on abnormally long outputs, repeated retries, and loop-like completions;
- Re-run the evaluation set weekly to catch quality drift caused by model version updates.
7. Rollout Plan: Four Steps
- Inventory: analyze the scenario distribution and token structure of real requests over the past two weeks, and find the 20% that consumes the most.
- Evaluate: run 3–5 candidate models on a unified evaluation set and produce a quality–cost–speed table.
- Pilot: enable routing and caching in one business module first, and watch the quota curve for two weeks.
- Solidify: write routing rules, caching strategy, and the fallback path into configuration, and include them in CI regression.
8. Common Pitfalls
- Looking only at unit price while ignoring multipliers and caching, which causes severe overspending on long-input scenarios;
- Using one creative prompt to represent all capabilities, making selection conclusions non-transferable;
- Ignoring rate limits and time to first token, letting throughput drag down the interactive experience;
- Skipping version regression, so both quality and cost spiral out of control after a model upgrade.
9. Conclusion
The number of available domestic large language models keeps growing. The rational approach is not to look for a single answer but to build a closed loop of scenario breakdown, quantitative evaluation, cost accounting, and routing with fallback. Once selection becomes a measurable, regression-friendly engineering process, budget and user experience no longer have to be traded against each other. If you need to host model services, log collection, monitoring and alerting, and elastic compute in one place, you can build on the relevant general capabilities of Baidu AI Cloud, keeping interfaces and configuration decoupled so that later replacement and horizontal scaling stay easy.
