LLM Selection and Inference Cost Optimization for Agent Workloads
Agent workloads consume far more tokens than single-turn chat because models plan, call tools, read results, revise plans, and generate structured outputs across multiple turns. This article presents a task-level approach to model selection and cost control for agents: building reproducible evaluation sets, measuring task success and retry behavior, decomposing input/output/retry/tool costs, evaluating pay-as-you-go and quota-based pricing, and applying engineering optimizations such as context compression, structured output, caching, batching, and routing. It also outlines a staged rollout from offline evaluation to production canarying.
1. Agent Workloads Are Changing Model Selection Logic
In traditional chat scenarios, users often enter a question and the model returns an answer, so input and output token volumes are relatively controllable. In agent scenarios, however, the model must plan across multiple turns, call tools, read tool results, revise plans, and generate a final response. Token consumption for a single task can therefore be significantly amplified. This is especially true for tasks such as browser operation, document processing, and front-end page generation, where the model must not only understand long contexts but also output structured instructions, code snippets, or operation steps. The more output tokens are required, the more visible the amplification effects of cost differences, latency differences, and failure retries become.
Model selection therefore cannot rely only on composite benchmark scores or single-demo performance. It should return to task-level metrics: task success rate, average number of turns, average input tokens, average output tokens, number of tool calls, retry rate, end-to-end latency, and cost per task. Composite evaluation indices can be used for initial screening, but the gap between leading models on composite scores is narrowing. What often determines production viability is stability and cost structure on specific tasks. For agent tasks, output token cost and failure retry cost should be tracked as separate observation items rather than simply converted into a per-million-token unit price.
2. Capability Evaluation: From Composite Scores to Task-Level Success Rates
Building a reproducible evaluation set is the first step in model selection. The evaluation set should cover typical tasks in real business scenarios rather than only collecting favorable examples. For example, front-end tasks can include component generation, style correction, and interaction logic completion; document tasks can include layout understanding, table extraction, and cross-paragraph question answering; browser tasks can include page element localization, form filling, multi-step navigation, and exception recovery. Each task should record fixed input, expected output, judging rules, and failure types. Judging rules can combine automated validation with manual spot checks to avoid relying only on subjective impressions.
Recommended evaluation metrics should include at least: first-pass success rate, final success rate, average number of interaction turns, average output tokens, retry count, timeout rate, tool call error rate, and human takeover rate. A high first-pass success rate indicates more stable model planning; a high final success rate with many turns may mean costs are amplified by multi-turn context; high output token volume with limited success improvement indicates over-generation. For tasks that require multimodal capabilities, screenshot understanding, document layout understanding, page element localization, and consistency between visual information and text instructions should be evaluated separately. Once multimodal capabilities are added, the coverage of front-end, document, and browser tasks can expand, but evaluation must be based on real screenshots, real documents, and real page states to avoid overly optimistic conclusions from idealized samples.
3. Cost Modeling: Separate Input, Output, Retry, and Tool Overhead
Agent costs cannot be roughly estimated using only input unit price plus output unit price. A more reasonable model is: total cost = input token cost + output token cost + retry amplification cost + tool and context overhead. Output tokens usually need to be priced separately and may account for a high proportion of agent tasks; multi-turn conversations also cause historical context to be repeatedly input. If a task fails and is retried, both input and output are generated again. Tool return results, page snapshots, and document fragments also enter the context, creating additional input overhead.
The following is a generic pseudocode example for estimating cost by task:
function estimate_task_cost(input_tokens, output_tokens, price_input, price_output,retry_rate, tool_input_tokens, tool_output_tokens):effective_input = input_tokens * (1 + retry_rate) + tool_input_tokenseffective_output = output_tokens * (1 + retry_rate) + tool_output_tokensreturn effective_input * price_input + effective_output * price_output
In practice, retry_rate should be calculated separately by task type rather than using a global average. Browser and document tasks have more tool return content, so tool_input_tokens may become a major cost item; code generation tasks should focus on output tokens and subsequent repair turns. It is recommended to log input tokens, output tokens, retry reason, task type, and final result for each call, and aggregate cost per successful task daily. Only by attributing costs to task types can teams determine whether optimization should focus on prompt compression, output constraints, caching, or model routing.
4. Billing Strategies: Combining Pay-as-You-Go, Packages, and Limited-Time Quota Windows
Pay-as-you-go billing is suitable for stages with unstable traffic, many task types, and a need for rapid experimentation; packages or quota plans are suitable for teams with predictable load and stable task volume. When evaluating packages, do not look only at the nominal price. Calculate the effective unit price and quota utilization. The effective unit price equals the package fee divided by the actual usable quota, while quota utilization depends on whether business peaks fall within the quota coverage, whether quotas are split by period and expire, and whether concurrency and rate limits meet requirements. If the quota cannot be used up within the period, the nominal discount may not be worthwhile; if peaks exceed the quota, the overflow portion still falls back to pay-as-you-go billing, and both parts must be accounted for together.
Limited-time quota windows are a way to exchange time for cost. Activities that increase available quotas at night or during off-peak hours are suitable for delayable tasks such as batch processing, offline evaluation, document batch parsing, and regression testing. For agent tasks, non-real-time evaluation, data cleaning, and batch generation can be scheduled within quota windows, while real-time interaction remains on a stable channel. However, supply continuity risk must be considered: a single package may be unavailable, quotas may be adjusted, and production systems should prepare a backup pay-as-you-go channel and degradation strategy. Individual, team, and heavy-load scenarios should also be segmented by scale: individuals focus on low barriers and flexibility, teams focus on seat quotas, concurrency, and management capabilities, and heavy-load scenarios require calculating usable quota per seat and overflow costs.
5. Engineering Optimization: Context, Structured Output, Caching, and Routing
Cost optimization should not rely only on price reductions or packages. There are at least five engineering approaches. First, context compression: use summary-style memory for multi-turn history, retaining only tool results and constraints relevant to the current subtask; use segmented retrieval for documents and page snapshots to avoid repeatedly inputting entire documents. Second, structured output: constrain output formats with explicit fields to reduce explanatory text and unnecessary repetition; for code generation tasks, require only changed snippets and necessary explanations. Third, caching: cache stable prompts, fixed tool descriptions, and public knowledge fragments; cache intermediate results for repeated subtasks, while paying attention to invalidation strategies. Fourth, batching and streaming: merge delayable tasks into batches, and use streaming responses for real-time tasks to improve experience. However, streaming does not directly reduce cost, and output length still needs to be controlled. Fifth, routing and degradation: select different capability tiers based on task difficulty, route simple extraction to low-cost channels and complex planning to high-quality channels; when the primary channel times out or is rate-limited, automatically degrade to a backup channel and log the reason.
Routing logic should be observable and rollback-capable. The following is generic pseudocode:
function route(task):if task.needs_multimodal and not candidate.supports_multimodal:return fallback_channelif task.estimated_output_tokens > threshold and task.is_batch:return low_peak_channelif task.complexity == "high":return high_quality_channelreturn cost_effective_channel
Recommended monitoring metrics include: cost per successful task, input/output token distribution, retry rate, timeout rate, quota remaining, rate-limit count, route hit rate, and degradation rate. General cloud capabilities such as logging, monitoring alerts, and object storage can be used to build cost observability, but logs themselves should not become a new cost sink. Sampling and retention periods should be set according to troubleshooting needs.
6. Implementation Path: From Small-Traffic Evaluation to Production Canarying
Implementation is recommended in three steps. First, use an offline evaluation set to compare candidate models, fixing the task set, judging rules, and cost parameters, and output task-level success rates and cost per task. Second, select low-risk business scenarios for small-traffic canarying, integrate monitoring alerts and cost dashboards, and observe retry rates, latency, and quota consumption under real traffic. Third, adjust routing ratios, output constraints, and package combinations based on canary results, and set budget thresholds and rollback conditions. For limited-time quota windows, start with offline batch processing and regression testing, then gradually expand to non-core real-time tasks. The ultimate goal is not to pursue a single lowest unit price, but to achieve an acceptable balance among task success rate, latency, cost, and supply stability. LLM selection in the agent era is essentially engineering cost governance: measure first, decompose second, optimize third, and finally validate through canarying.
