LLM Selection for AI Agents: A Cost-per-Task Framework
How should you choose a large language model for agent workloads? This article explains why cost per task matters more than price per token, covering token cost structure and prompt caching, cost estimation with code examples, the trade-offs of long context windows, self-hosting and quantization, tiered model routing, and how to build your own evaluation set to balance quality, speed, and budget.
1. Background: From Single-Turn Q&A to Agent Workflows
Early LLM applications were mostly single-turn Q&A: one question, one answer, typically a few thousand tokens. Costs were easy to estimate, and model selection was relatively simple.
AI agent applications change this picture entirely. A complete automated task often involves multiple rounds of planning, reading web pages or documents, dozens of tool calls, code execution with self-testing, and structured output generation. Every step re-sends the accumulated history to the model, so token consumption grows with the number of steps. A single task consuming hundreds of thousands or even millions of tokens is now common.
This creates two immediate problems. First, if every subtask runs on a top-tier flagship model, costs quickly blow past the budget. Second, the response speed and stability of the model at high-frequency steps directly affect end-to-end task latency. Model selection therefore has to balance capability, speed, and price—not just leaderboard rankings.
2. Understanding Cost Structure: Input, Output, and Caching
For most pay-as-you-go model services, cost consists of three parts:
- Input tokens that miss the cache;
- Input tokens that hit the cache;
- Output tokens.
Output tokens usually cost more than input tokens, and cached input tokens are far cheaper than uncached ones. This means that in multi-turn interactions, if the system prompt, tool definitions, and conversation history prefix stay stable, the server can reuse the already-computed prefix and significantly reduce cost.
Some providers also vary pricing by time of day, with higher rates at peak hours. When estimating costs, use the rates that apply to your actual calling periods and keep some margin in your estimates.
A few practical principles when designing agent prompts:
- Put immutable content (system instructions, tool descriptions, fixed examples) at the front of the prompt and keep the prefix stable;
- Put variable content (the current user input, the latest tool results) at the end;
- Avoid rewriting the format of historical messages mid-conversation, or the cached prefix becomes invalid;
- Truncate and summarize tool outputs, keeping only the fields later steps actually need.
3. Calculating Cost per Task
When comparing model prices, unit price alone tells you little. A more useful metric is cost per task: the total cost of completing one standard task. It depends on three factors—unit price, tokens consumed per step, and the number of steps required to finish the task.
The following example shows how to estimate the cost of a single task from call logs. Replace the pricing parameters with your provider’s actual rates.
from dataclasses import dataclass@dataclassclass Pricing:input_miss: float # Price per million uncached input tokensinput_hit: float # Price per million cached input tokensoutput: float # Price per million output tokensdef estimate_task_cost(pricing: Pricing, steps: list[dict]) -> float:"""Each item in steps contains: input_tokens (including cached part), cached_tokens, output_tokens"""total = 0.0for s in steps:cached = s["cached_tokens"]miss = s["input_tokens"] - cachedtotal += miss * pricing.input_miss / 1_000_000total += cached * pricing.input_hit / 1_000_000total += s["output_tokens"] * pricing.output / 1_000_000return totaldef estimate_by_model(pricings: dict[str, Pricing], steps: list[dict]) -> dict[str, float]:return {name: estimate_task_cost(p, steps) for name, p in pricings.items()}
The workflow: collect per-step data from a batch of representative tasks in your logs, plug in the pricing for each candidate model, and compare total costs. Note that a cheaper model that needs more steps or more retries to finish a task may end up costing more overall. Cost evaluation must therefore always be paired with success rate.
At minimum, track these metrics:
- Average number of steps and average token consumption per task;
- Task success rate, judged against your business-defined acceptance criteria;
- Cost per successful task, i.e., total cost divided by the number of successful tasks;
- End-to-end latency and the number of failed retries.
4. The Cost and Benefit of Long Context
Long-context capability lets a model process more material at once—an entire codebase, lengthy documents, or large conversation histories. It reduces the engineering complexity of retrieval, chunking, and stitching, but introduces new problems.
First, input token counts increase, and so does cost. Even with cache hits, storing and computing over very long prefixes still carries overhead. Second, key information in extremely long contexts may not be reliably used; a model’s ability to extract information from the middle of the context can degrade. Third, the advertised context window size and the actually usable window are different things—server-side limits, client configuration, and request parameters can all affect the effective length.
In practice, a safer approach is to:
- Compress irrelevant content with retrieval or summarization, putting only highly relevant material into the context;
- Add dedicated long-text retrieval cases to your evaluation set to test the model’s ability to locate key information;
- Use staged summaries for very long tasks, compressing completed steps into structured state rather than endlessly appending history.
5. Self-Hosting and Quantization Considerations
For data-sensitive or offline scenarios, self-hosting is an option. Before deploying, estimate your GPU memory or RAM requirements.
A rough estimate of model weight footprint:
Weight footprint (bytes) ≈ parameter count × bits per parameter ÷ 8
For example, a 100-billion-parameter model stored at 16-bit precision needs roughly 200GB, or about 50GB at 4-bit quantization. Real deployments also need memory for the KV cache, runtime overhead, and concurrent requests. Quantization lowers the hardware barrier but introduces some accuracy loss, particularly visible in mathematical reasoning and long-chain code generation. After quantization, you must rerun your evaluation set—you cannot simply carry over conclusions from the original model.
The cost of self-hosting includes hardware purchase or rental, electricity, operations staffing, and version upgrade overhead. Only when call volume is large enough and data compliance requirements are explicit can total cost of ownership fall below pay-as-you-go pricing.
6. Tiered Routing: Matching Models to Tasks
In an agent system, different stages have very different requirements. Planning, complex reasoning, and hard bug fixes demand strong capability; format conversion, simple classification, keyword extraction, and repetitive tool calls need less capability but are sensitive to latency and cost.
The idea behind tiered routing is to assign requests to different model tiers based on task difficulty and risk. A common tiering scheme:
- High-tier models handle task decomposition, critical decisions, and final quality review;
- Mid-tier models handle routine execution and code writing;
- Lightweight models handle high-frequency, structured, low-risk subtasks.
Routing can be rule-driven (based on task type or fields) or model-driven (a small classifier judges difficulty). Either way, keep an escalation mechanism: when a lightweight model’s output fails validation, automatically retry with a stronger model.
def route(task: dict) -> str:if task["type"] in {"format", "extract", "classify"}:return "light"if task.get("risk") == "high" or task.get("steps", 0) > 20:return "strong"return "standard"def run_with_fallback(task, call_model, validate):tier = route(task)result = call_model(tier, task)if not validate(result) and tier != "strong":result = call_model("strong", task)return result
7. Building Your Own Evaluation Set
Public leaderboards reflect general capability and don’t necessarily match your business scenarios. Teams should build their own evaluation sets and retest regularly.
Recommended steps for building one:
- Extract representative tasks from real logs, covering common paths and edge cases;
- Define automatically checkable acceptance criteria for each task, such as passing test cases, correct field formats, or valid tool-call parameters;
- For tasks that can’t be judged automatically, use manual sampling or an independent model for assisted scoring, and record scoring consistency;
- Fix random seeds and run parameters so comparisons across models are reproducible;
- Rerun the full evaluation after any change to model version, prompts, or tool configuration.
Evaluation results should report both quality and cost metrics, producing a comparison table like this:
| Metric | Model A | Model B |
|---|---|---|
| Task success rate | Fill in from testing | Fill in from testing |
| Average cost per task | Fill in from testing | Fill in from testing |
| Cost per successful task | Total cost ÷ successes | Total cost ÷ successes |
| Average end-to-end latency | Fill in from testing | Fill in from testing |
8. Common Pitfalls
First, comparing unit price only. A cheaper model that needs more steps or retries may cost more in total.
Second, ignoring caching. An unstable prefix invalidates the cache, and the cost advantage disappears.
Third, treating leaderboard scores as business outcomes. Leaderboard tasks and your business tasks usually have different distributions—validate with your own evaluation set.
Fourth, ignoring rate limits and concurrency. If a cheap model queues heavily at peak times, it slows the whole workflow and indirectly raises labor and waiting costs.
Fifth, judging context length from the spec sheet alone. Server-side limits, client configuration, and actual retrieval effectiveness are three separate things—confirm each independently.
Sixth, ignoring data compliance. Before sending sensitive data to an external service, verify the data processing terms and your internal security requirements.
9. Conclusion
When choosing an LLM, unit price is only the starting point. What actually determines cost is the total spend per task, which depends on unit price, tokens per step, number of steps, success rate, and retries. Teams should first build a reproducible evaluation set that tracks both quality and cost metrics, then apply tiered routing based on task difficulty. Long context and self-hosting each have clear conditions for their value, which must be confirmed through real testing. Following this process lets teams replace subjective judgment with concrete data and find a sustainable balance between budget and quality.
