LLM API Selection: A Practical Guide to Pricing, Capabilities, and AI Agent Scenarios
This article explains how to evaluate LLM APIs for production use by focusing on total cost of ownership rather than the largest model. It covers five key specification checks, a unified cost model, additional metrics and control strategies for AI agents, a six-step evaluation process, and common selection mistakes.
LLM API Selection: A Practical Guide to Pricing, Capabilities, and AI Agent Scenarios
1. The Real Problem: Choose the Combination with the Lowest Total Cost of Ownership
Many teams begin LLM API selection by opening vendor documentation, comparing context length, parameter count, and benchmark scores, and choosing the model with the largest numbers. This is not wrong, but it covers only a small part of the decision.
Production cost has three main components:
- Per-call cost: determined by input tokens, output tokens, cache hits, and how thinking tokens are billed.
- Rework cost: retries, additional context, and secondary validation after a call does not get the task right the first time. This is often underestimated in multi-turn agent workflows.
- Engineering and operations cost: rate limits, SDK compatibility, structured-output stability, and the effort required to add logging and monitoring.
Therefore, the real question is not “Which model is stronger?” but:
Can the cheaper model pass in one attempt? Can the more expensive model reduce rework?
A recommended trial sequence is:
- Use a high-frequency, low-difficulty image/text understanding or structured extraction task to run a lightweight (Flash-class) model first, establishing cost and latency baselines.
- Add another model that has an advantage in large output budgets as a comparison, and observe whether long-form generation tasks are truncated.
- If the business involves video, audio, or other non-text inputs, separately filter for the small set of candidate models that support those modalities.
- For the final selection of a complex agent workflow, retest all candidates horizontally on the same business task set.
2. Five Specification Areas to Verify First
Vendor documentation does not always use consistent terminology. Direct side-by-side comparison can therefore lead to incorrect conclusions. It is better to build a checklist at the start of the selection process and confirm each item.
2.1 Input modalities: what can the model “see”?
The supported input types define the feasible domain of a use case. Common tiers are:
| Input capability | Typical business scenarios |
|---|---|
| Text only | Code generation, copywriting, structured extraction |
| Text + images | Document recognition, screenshot understanding, chart reading |
| Text + images + video | Long-video summarization, surveillance footage understanding, screen-recording analysis |
One important distinction is that “supporting images” and “understanding images well” are not the same thing. The former is an API capability; the latter depends on OCR quality, layout analysis, and reasoning depth for complex charts. You should also verify limits such as maximum resolution per image, maximum number of images per request, video duration limits, and frame extraction strategy.
2.2 Context length: look at the total budget and the input/output split
Million-token context windows have become a common marketing point, but there are three important details:
- The context window is shared between input and output. It is not extra free space. For example, if the total window is 1M tokens and the maximum single output is 128K tokens, the practical input limit is about 896K tokens.
- Effective context is not the same as nominal context. The widely observed “lost in the middle” phenomenon means that recall can degrade when critical information is placed in the middle of a very long context. As a result, there is a cost-performance sweet spot for the number of retrieved passages in retrieval-augmented generation (RAG). Simply stuffing every document into the context increases both cost and noise.
- The output limit can be dynamically constrained by the remaining context. Some models describe the output limit as a default value that cannot exceed the remaining context. This kind of rule should be included in capacity planning.
2.3 Output budget: an invisible ceiling for long-form tasks
Output limits are one of the most easily overlooked specifications, yet they are also a common source of production incidents. Typical tiers are:
- About 16K–64K: suitable for code snippets, structured JSON, and regular copywriting.
- About 128K: suitable for single-file refactoring and long analytical reports.
- About 256K–384K: suitable for multi-file engineering changes and book-level content generation.
If the expected output is close to the limit, implement segmented generation plus result stitching on the business side instead of relying on one long output. Practical techniques include splitting tasks by chapter or file, maintaining a continuation summary with the current state, and using a template to fix the output skeleton before filling it in section by section.
2.4 Thinking mode: both a capability switch and a cost switch
Most mainstream models offer a standard mode and a thinking mode, also called reasoning mode. Thinking mode generates an internal reasoning process before producing the final answer, which can significantly improve accuracy on math, complex logic, and multi-step planning. However, it also brings trade-offs:
- Tokens generated for the thinking process are usually billed at output prices, even if they are not returned to the user.
- Thinking latency is hard to control, and end-to-end latency can increase by several times.
- Some services support thinking token budgets or reasoning-effort parameters, which can be used to cap cost.
Engineering recommendation: make “whether to enable thinking” configurable per task type rather than a global constant. Disable it for extraction, classification, and summarization tasks. Enable it for math, complex retrieval planning, and cross-file refactoring, and set token budgets plus timeout circuit breakers.
2.5 Billing rules: the prerequisite for comparable pricing
Different vendors use different pricing units, cache discounts, batch discounts, and thinking-token billing rules. They must be normalized to a blended cost per million tokens before comparison. Items to confirm include:
- Whether input and output are priced separately, which is usually the case.
- Whether prompt caching or prefix caching is supported, the discount rate, and how long the cache remains valid.
- Whether asynchronous batch endpoints receive a discount.
- Whether thinking tokens are billed separately and at what price.
- Whether there are minimum billing lengths, tiered pricing, or free quotas.
3. A Unified Cost Estimation Model
Once the pricing is normalized, the discussion can move from intuition to arithmetic.
Define:
- (N_{in}): total input tokens
- (N_{cache}): input tokens that hit the cache
- (N_{out}): total output tokens
- (N_{think}): thinking tokens
- (p{in}, p{out}): input and output unit prices, in CNY per million tokens
- (\alpha): cache discount factor, between 0 and 1
The per-call cost is:
[
C = \frac{(N{in}-N{cache})\cdot p{in} + N{cache}\cdot \alpha \cdot p{in} + (N{out}+N{think})\cdot p{out}}{10^6}
]
A more realistic version introduces a rework factor (r), which represents the average number of retries:
[
C_{eff} = r \cdot C
]
A model with a lower unit price but lower accuracy may end up with a higher total cost because (r) becomes larger. Example code:
def estimate_cost(tokens_in, tokens_out, thinking_tokens=0,cached_in=0, price_in=1.0, price_out=3.0,cache_discount=0.5, retry_factor=1.0):"""Cost estimation with a unified billing model.Prices are in CNY per million tokens.cached_in must be <= tokens_in."""assert 0 <= cached_in <= tokens_inbilled_in = (tokens_in - cached_in) + cached_in * cache_discountbilled_all = billed_in + tokens_out + thinking_tokensunit = billed_in * price_in + (tokens_out + thinking_tokens) * price_outreturn unit / 1_000_000 * retry_factor
Combining this model with the expected business volume makes it easier to see where cost reduction should be focused:
- When input tokens dominate, the prefix-cache hit rate can save more money than switching models.
- When output tokens dominate, output unit price and the rework factor carry the highest weight.
4. Additional Evaluation Dimensions for AI Agent Scenarios
Agents, especially tool-calling applications, differ from traditional question answering because they are not a single call. They are multi-turn loops with external side effects. The evaluation dimensions must be extended accordingly.
4.1 Additional metrics
- Tool selection accuracy: the proportion of cases where the correct tool is selected from multiple candidate tools.
- Argument filling accuracy: whether the correct tool name is used but arguments are missing, have the wrong type, or are fabricated. These failures are especially hard to debug.
- Multi-turn convergence rounds: the average number of interaction turns required to complete a task. More rounds increase both cost and latency.
- End-to-end task success rate: whether the final answer is correct, without considering the intermediate process.
- Failure recoverability: whether the agent can correct itself based on error feedback instead of falling into a loop.
4.2 Cost control for agent workflows
- Model tiering: split the task into four stages: intent recognition, planning, execution, and verification. Use lightweight models for intent recognition and format validation, and use flagship models for complex planning. This is usually the most effective cost-reduction technique.
- Context compression: at each turn, summarize historical messages and keep only task state, completed actions, and key intermediate results. This prevents history from growing without limit and causing exponential cost increases.
- Strict output constraints: use structured outputs such as JSON Schema or function-calling protocols, combined with server-side validation and a limited number of automatic retries. This significantly reduces hidden rework caused by parsing failures.
- Observability: record input and output tokens, latency, cache hits, and tool-call results for every call. Connect these records to logging and alerting services, and build a cost dashboard that can be split by model and business line. Without this data, any selection conclusion is only a guess.
4.3 A routing skeleton example
ROUTING_RULES = [# Prefer low-cost models; escalate when a call fails or confidence is low.{"stage": "intent", "tier": "light", "max_retry": 1, "enable_thinking": False},{"stage": "extract", "tier": "light", "max_retry": 2, "enable_thinking": False},{"stage": "plan", "tier": "heavy", "max_retry": 1, "enable_thinking": True,"thinking_budget": 4096},{"stage": "verify", "tier": "light", "max_retry": 1, "enable_thinking": False},]def route(stage, payload, fallback=True):rule = next(r for r in ROUTING_RULES if r["stage"] == stage)for attempt in range(rule["max_retry"] + 1):tier = "heavy" if (attempt > 0 and fallback) else rule["tier"]resp = call_model(tier, payload, thinking=rule["enable_thinking"],thinking_budget=rule.get("thinking_budget"))if validate(resp): # server-side schema validationreturn resppayload = append_error_feedback(payload, resp) # feed the error back to the modelraise TaskFailed(stage)
5. A Six-Step Process for a Rigorous Selection
- Define acceptance criteria: translate “good results” into quantifiable metrics, such as field-extraction F1 score, tool-call success rate, unit-test pass rate, and average human rating.
- Build an evaluation set: sample 200–500 cases from real traffic, covering long-tail and boundary cases, and stratify them by difficulty. Label the answers and version-controlled the dataset. Avoid evaluating only with official sample data.
- Run a small-traffic trial: run the same evaluation set for each candidate model while recording token consumption, P50/P95 latency, and the distribution of error types.
- Calculate effective cost: use the formula in Section 3 to compute (C_{eff}), rather than comparing unit prices directly.
- Use shadow traffic and canary release: run candidate models in parallel on the real workflow in shadow mode, recording results without affecting production. After confirming there is no regression, release traffic gradually by percentage.
- Establish periodic retesting: model services continue to iterate, and specifications and prices change. Make the evaluation set part of a CI pipeline and run automatic regression weekly or per version, so that selection conclusions do not become outdated.
6. Common Mistakes
- Treating naming suffixes as capability tiers: suffixes such as Flash, Pro, and Max are internal product-line distinctions. They are not comparable across vendors, and rankings may even reverse between generations from the same vendor.
- Focusing only on context length: the benefits of ultra-long context are often offset by lower effective recall and higher cost.
- Ignoring the output limit: long-document generation being truncated at a 128K output limit is one of the most typical production incidents.
- Enabling thinking mode by default: for extraction and classification tasks, thinking mode mostly adds cost.
- Not using caching and batch processing: if highly repetitive prefixes, such as system prompts, tool definitions, and knowledge snippets, do not use prefix caching, costs can be several times higher. If offline tasks do not use asynchronous batch endpoints, available discounts are wasted.
- Binding to a single model: hard-wiring the business to one model leaves no fallback path if specifications change or rate limits are tightened. Abstracting a unified model gateway with multi-vendor adaptation, unified authentication, and unified billing telemetry is the more sustainable approach.
7. Conclusion
LLM API selection is a three-stage funnel: feasibility, effectiveness, and cost. First, use modality support and output budgets to eliminate infeasible candidates. Second, use business evaluation sets to remove candidates that do not meet quality requirements. Finally, rank the remaining candidates by effective cost. For agent scenarios, two additional dimensions should be added: tool-call accuracy and multi-turn convergence efficiency.
For most teams, the best solution is usually not a single model. It is a combination of a lightweight model as the main workhorse, a flagship model for difficult tasks, and a unified gateway for routing and fallback. The foundation supporting this approach is a curated business evaluation set and a cost dashboard. They make every selection decision evidence-based and prevent teams from starting from scratch every time vendors iterate their services. If an organization already uses a cloud platform with unified model access, logging, and monitoring capabilities, it can directly put these evaluation and cost-observability workflows into engineering practice.
