Layered LLM API Selection for Production Systems
Choosing an LLM API for production is less about finding a universally “best” model and more about matching cost, context handling, reasoning reliability, coding performance, language quality, and latency to each request type. This article presents a practical framework for request classification, model routing, cost control, evaluation, observability, fallback design, and staged rollout.
Introduction
When building AI agents, retrieval-augmented generation (RAG), coding assistants, customer service bots, or document analysis systems, API selection can easily become a debate over which model is “stronger.” After launch, the recurring questions are more practical:
- How much input and output does each request consume?
- Can the model handle long context reliably?
- Is complex reasoning stable?
- Can code changes be tested and reverted?
- Does it follow Chinese instructions accurately?
- Will tail latency damage the user experience?
Mature teams treat model selection as a cost-and-quality engineering problem rather than a matter of model preference. Lower-cost models handle high-volume, lightweight tasks. Balanced models support core workflows. Higher-capability models are reserved for critical reasoning and steps that cannot fail.
1. Classify Requests Before Selecting Models
Requests within the same product are not equivalent. A useful starting point is to divide them into four categories.
1.1 Extraction, Classification, Rewriting, Summarization, and Formatting
These tasks usually have clear inputs and outputs that can be validated. Their failure cost is relatively low, making them suitable for high concurrency and low unit cost.
1.2 Retrieval-Based Question Answering and Document Comparison
Quality depends heavily on whether the retrieved passages are sufficient and whether the answer is faithful to the cited material. The model should answer from the provided context rather than relying on unsupported knowledge from its parameters.
1.3 Multi-Step Agents
An agent may need to read logs, inspect diffs, select tools, observe results, and plan again. A single call may appear inexpensive, but a long loop can make total consumption an order of magnitude higher than that of a casual conversation.
1.4 Long-Horizon Coding and Difficult Debugging
These tasks require consistency across files, awareness of tests, and conservative changes. Saving on per-token pricing can easily result in higher costs from rework and manual review.
Layering does not mean routing all traffic to the cheapest tier. Each tier should perform only the tasks it has been validated to handle. Without an evaluation set, model routing is merely intuition-driven traffic splitting.
2. Evaluate the Six Dimensions Together
Price
Compare input pricing, output pricing, and cached-input pricing per million tokens rather than focusing on a single advertised number.
In agent workflows, output is often shorter than input, but tool results and conversation history can make the input very large. Reasoning-oriented calls may also produce longer outputs. Estimate input tokens, output tokens, and cache-hit ratios separately, then multiply them by daily request volume.
Failure retries must also be included. Replaying a timed-out request effectively multiplies its cost by the number of attempts.
Context Window
A large context window does not guarantee that the model will use all of it effectively. Beyond the range where attention remains stable, information in the middle of the context may be overlooked, a common issue known as “lost in the middle.”
In practice, define separate budgets for:
- System prompts
- Tool descriptions
- Retrieved passages
- Conversation history
When the limit is reached, summarize before truncating and preserve the most recent tool observations. Sending an entire codebase or a full contract in one request is usually less effective than chunked retrieval with citations.
Reasoning Capability
The key question is not whether a model can “think for a long time,” but whether it avoids important errors under constraints. Evaluate areas such as:
- Arithmetic and units
- Multi-condition logic
- Refusing conclusions that are unsupported by the provided material
- Validity of tool parameters
For high-risk steps, use a three-stage process: plan, execute, and verify. Verification can be performed with rules or a lower-cost model for consistency checking, rather than using the highest-capability model throughout the entire workflow.
Coding Performance
Offline evaluations should cover realistic small changes from the actual repository:
- Adding tests
- Fixing compilation errors
- Maintaining API compatibility
- Handling null values and concurrency
Do not evaluate only whether a generated change runs once. Also measure whether the patch is minimal, whether it modifies unrelated files, and whether the model can converge after receiving an error.
Allowing the model to call read-only retrieval and testing tools is generally more controllable than asking it to output an entire file in one attempt.
Chinese-Language Quality
Chinese tasks should have their own evaluation samples, covering:
- Conversational instructions
- Formal business writing
- Technical terminology
- Mixed Chinese and English
- Date and currency formatting
Common failures include over-translation, incorrect honorifics, and altered numbers in tables. If the business is primarily Chinese-speaking, compare fluency, faithfulness, and format compliance under identical prompts instead of relying only on English benchmarks.
Response Speed
Interactive products should track time to first token and end-to-end latency percentiles. Batch workloads should focus on throughput and queueing time.
Timeout policies should distinguish between tasks that can be degraded and tasks that must wait. Long reasoning processes can be made asynchronous, with progress updates returned to the user so that synchronous request threads are not held unnecessarily.
3. Cost Engineering: Pricing, Caching, and Call Structure
The most expensive part of a system is often not the highest-priced tier. It is repeated uncached prefixes, excessive history, and loops without limits.
Reusable system prompts, tool definitions, and static policies should be placed in a cacheable prefix, with business-specific variables appended afterward. If a provider supports prefix caching or an equivalent mechanism, cache-hit rate should be treated as a production metric rather than something discovered only after an unexpected bill.
Conversation history should be compressed continuously. Keep the most recent several turns in their original form, convert older content into a structured summary, and note that the summary may lose details. Tool outputs should also be truncated to retain only conclusions, error codes, and diagnostic locations.
Every loop needs a budget:
- Maximum number of steps
- Maximum token usage
- Maximum number of tool failures
When a limit is reached, the system should ask a human for help or switch to a more conservative workflow instead of retrying indefinitely.
A Simple Routing Strategy
A basic routing flow can work well:
- Classify the request using rules.
- If it is an extraction or rewriting task and the input is below a defined threshold, route it to the economy tier.
- If retrieval confidence is low or the user explicitly requests rigorous verification, promote it to the balanced tier.
- If the request involves funds, permissions, cross-module refactoring, or two consecutive verification failures, promote it to the high-capability tier.
- Record the reason for every promotion.
The routing decision and actual consumption should be written to the same trace. This makes it possible to calculate unit cost by task type after deployment.
4. Make Evaluation More Representative Than Public Benchmarks
Public leaderboards are useful references, but they cannot replace evaluation against your own traffic distribution. Consider building three types of datasets.
Capability Set
Start with 50 to 200 samples for each task category, including normal, boundary, and adversarial cases. Label the expected structured fields rather than requiring one exact wording.
Regression Set
Rerun the regression set whenever prompts, temperature, or routing rules change. Track not only accuracy, but also average token usage and timeout rate.
An improvement in quality that doubles cost is not automatically a success. Likewise, lower cost with more critical errors should not pass.
Online Shadow Traffic
Run a new routing strategy in parallel without allowing it to affect users directly. Compare it with the existing strategy using metrics such as refusal rate, human handoff rate, and complaint categories. Move to a gradual rollout only after the results remain stable.
Evaluation prompts should also be versioned. Changing a prompt changes the product and should be reversible in the same way as a code change.
5. Engineering Foundations: Observability, Fallbacks, and Security
At minimum, observability should include:
- Task type
- Routing tier
- Input and output tokens
- Cache-hit status
- Number of steps
- Tool errors
- End-to-end latency
- Business-level success
Without these fields, teams can argue about the total bill but cannot identify which request categories are consuming the budget.
Fallback behavior must be defined in advance. If the high-capability tier is unavailable, the balanced tier should be able to respond that the material is insufficient while preserving citations. It should not fill missing information with generic generation.
If the economy tier is unavailable, rules and templates should still provide the minimum deliverable for extraction tasks.
For security:
- Treat untrusted documents and web pages as data, not instructions.
- Grant tools the minimum permissions required.
- Scan external outputs for sensitive information.
These controls are independent of model branding, but they determine the potential radius of an incident.
6. A Practical Rollout Order
- Use two weeks of traffic to build a task profile and calculate token usage and failure costs for each category.
- Replace the model used for the most frequent lightweight tasks with an economy-tier option, while using the regression set to protect format accuracy.
- Add step and token budgets to agent workflows.
- Only then consider expanding context or raising the default routing tier.
Reversing this order makes it easy to tie the entire product to the most expensive API before understanding where waste actually occurs.
The goal of model selection is not to declare one API the overall winner. It is to ensure that every request type has an explainable tier, repeatable evaluation, and reversible controls. Model capabilities will change over time, but routing, budgets, and observability remain durable engineering practices.
