Tiered LLM Selection and Cost Optimization for Agent Tasks
This article explains how to choose LLM tiers for agent workloads by estimating true per-task cost, classifying tasks by complexity, risk, and context size, building an in-house evaluation set, and controlling multi-step agent costs. It also outlines routing and fallback patterns, key monitoring metrics, and rollout practices for balancing quality and cost.
1. Why Tiered Selection Is Needed
LLM services typically provide multiple tiers. The high-performance tier targets complex reasoning, long-context, and multi-step tasks. The economy tier targets high-frequency, relatively structured daily tasks. The two tiers differ in unit price, response speed, and capability boundaries, so it is difficult for a team to cover all scenarios with one model.
Using only the strongest tier drives up cost, while using only the economy tier can lead to rework and increased manual review. The goal of tiered selection is to match each task type with the appropriate tier, keep total cost within an acceptable range, and ensure results meet business requirements.
2. Understanding the True Cost of a Single Task
Many teams focus only on the price per million tokens, but this is not enough to reflect real overhead. The cost of a single task consists of at least three parts:
- Input tokens: This includes the system prompt, user input, retrieved context, and tool definitions. The more tool definitions there are, the larger the input per call.
- Cached input tokens: When multiple requests share the same prefix, such as a fixed system prompt and template, the server can reuse computation results. The unit price for cached input is usually significantly lower than that for regular input.
- Output tokens: The length of generated content directly affects cost. Requiring structured output and limiting length can reduce redundant text.
The combined estimate is:
Cost per task ≈ input volume × input unit price + cache hit volume × cache unit price + output volume × output unit price, multiplied by the average number of call rounds, including retries and tool turns.
The last term is often overlooked. A lower-priced tier may need multiple retries to produce an acceptable result, making its actual cost higher than a higher-priced tier that succeeds on the first pass. Prices change frequently, so selection should be based on the provider’s official pricing page.
3. Matching Tiers to Task Characteristics
Tasks can be graded along three dimensions: reasoning complexity, output risk, and context size.
| Task type | Main characteristics | Recommended tier |
|---|---|---|
| Multi-file code refactoring, long-chain reasoning, professional document generation | High complexity, high cost of errors | High-performance tier |
| Daily Q&A, summarization, format conversion, classification | Clear rules, high-volume calls | Economy tier |
| Compliance review, financial data processing | High output risk | High-performance tier plus human review |
| Simple execution steps after subtask decomposition | Simple single step, many calls | Economy tier |
The key to classification is avoiding two extremes. Assigning all tasks to the high-performance tier wastes budget, while assigning high-risk tasks to the economy tier accumulates quality problems.
4. Building an Evaluation Set with Your Own Data
Public leaderboards can indicate the general capability range of models, but their ranking may not align with a specific business. Teams should build their own evaluation set as follows:
- Collect samples: Extract 50 to 200 typical inputs from real business scenarios, covering common cases and edge cases.
- Define scoring dimensions: Include correctness, completeness, format compliance, response time, and token consumption.
- Fix scoring rules: Determine the scoring criteria before testing. Preferably, two or more people score independently to reduce subjective bias.
- Record core metrics: Track the pass rate, average token consumption, and average latency of each tier.
- Calculate cost per successful task: Divide total cost by the number of passed samples. This metric directly compares the value of different tiers.
The evaluation set should be updated regularly because the distribution of business inputs changes over time.
5. Cost Control in Agent Workflows
The cost of multi-step agent tasks often grows faster than that of single calls for several reasons:
- Too many tool turns: The agent repeatedly calls tools without meaningful progress. This can be addressed by optimizing tool descriptions and limiting the maximum number of steps.
- Continuously expanding context: Each turn brings the full history of messages, so input volume grows linearly. Periodically summarize the history and keep only information relevant to the current goal.
- Lack of budget constraints: Tasks without limits may fall into loops. Set a maximum token count, maximum step count, and timeout for each task.
- Coarse tier usage: All steps use the same tier. A better approach is to use the high-performance tier for planning and key decisions, and the economy tier for execution and formatting steps.
6. Reference Implementation for Routing and Fallback
The following example shows an approach that selects a tier based on the task profile and escalates the tier when validation fails. The model identifiers are placeholders and should be replaced with the model names of the selected service. The call function and validation function are injected by business code.
from dataclasses import dataclass@dataclassclass TaskProfile:complexity: int # Complexity, value from 1 to 5risk: str # Risk level: "low", "medium", or "high"context_tokens: int # Estimated input token countTIERS = {"flagship": "<high-performance tier model identifier>","economy": "<economy tier model identifier>",}CONTEXT_LIMIT_FOR_ECONOMY = 100_000def choose_tier(task: TaskProfile) -> str:"""Choose the initial tier based on the task profile."""if task.risk == "high" or task.complexity >= 4:return "flagship"if task.context_tokens > CONTEXT_LIMIT_FOR_ECONOMY:return "flagship"return "economy"def run_with_fallback(task, prompt, call_model, validate,max_attempts=2, max_budget_tokens=200_000):"""Call the model and escalate the tier on validation failure, within budget."""tier = choose_tier(task)spent = 0for _ in range(max_attempts):result, used_tokens = call_model(TIERS[tier], prompt)spent += used_tokensif validate(result):return resultif spent >= max_budget_tokens:breaktier = "flagship" # Escalate to the high-performance tier on validation failureraise RuntimeError("Output failed validation and requires manual handling")
This code has three design points. First, the initial tier is determined by task attributes rather than the developer’s subjective impression. Second, the validation function should check structured format, required fields, and business rules, not just whether the model returned text. Third, the budget cap prevents the escalation strategy from consuming resources indefinitely.
7. Key Monitoring Metrics
After launch, continuously track the following metrics and connect them to logging and alerting:
- Cost per successful task: The core metric for measuring value.
- First-pass rate: Reflects whether tier selection is reasonable. A persistently low first-pass rate indicates that the initial routing rules need adjustment.
- Average number of tool turns: An abnormal increase usually means the agent is stuck in a loop.
- Cache hit rate: Reflects whether prompt templates are stable and whether there is a reusable fixed prefix.
- Percentile latency: Pay attention to high-percentile latency to avoid a small number of long-tail requests affecting user experience.
8. Rollout Recommendations
- Canary rollout: Run the new routing strategy on a small amount of traffic first, compare cost per successful task and pass rate with the original strategy, and switch fully only after confirming there is no regression.
- Regular review: Rerun the evaluation set every quarter or when the provider changes pricing or launches new tiers.
- Set budget alerts: Define cost thresholds by project and by day, and automatically notify and rate-limit when they are exceeded.
- Keep fallback paths: When a tier experiences service fluctuations, switch to a backup tier to keep core business running.
Summary
Tiered selection is not about finding a single “best” model. It is about finding the lowest-cost combination that meets quality requirements for each task type. Teams can classify tasks, evaluate with their own data, and use cost per successful task for decisions. By adding budget and validation constraints to agent workflows, they can use LLM capabilities reliably at controllable cost.
