How to Choose and Cost-Optimize LLMs for Agent Tasks
Agent pipelines involve multiple model and tool calls, each adding latency and cost. This article explains how to evaluate models for agentic workflows using task-level metrics instead of leaderboard scores, how to compute per-task cost with a simple formula, how to sequence selection criteria, and which engineering guardrails and common mistakes to watch for when deploying agents to production.
Evaluate Task Outcomes First, Not Leaderboard Scores
Agent tasks typically involve multiple rounds of model calls and tool calls, each contributing latency and cost. Generic leaderboard scores cannot tell you whether a specific model is cost-effective in your business pipeline. When selecting a model, answer three questions: Can the task be completed? How long does it take? How much does it cost per completed task?
Step 1: Standardize Your Evaluation
Start by preparing a small evaluation set of 50–200 real business samples, and record the following metrics for each sample under the same standard.
| Metric | Meaning | How to Measure |
|---|---|---|
| Task success rate | Whether the final result meets acceptance criteria | Rule-based checks or manual sampling |
| Tool call validity rate | Whether parameters pass JSON Schema validation | Automated programmatic counting |
| Average step count | Number of model calls needed per task | Request log analysis |
| Time to first token (TTFT) | Time from request to first token received | Streaming API timing, record P50 and P95 |
| Cost per task | Cost computed from billed prices | Formula below |
Keep region, concurrency level, and time of day consistent during testing. Otherwise, latency figures across models are not comparable.
Step 2: How to Calculate Cost
The cost of a single call:
Cost per call = input tokens × input price + output tokens × output price
The cost of an entire task is the sum of all calls, plus the tool’s own fees:
Cost per task = Σ(cost of call i) + tool call fees
If your provider offers cache-based billing, cached input tokens are billed at the cache price, so track cache hit rate separately.
The table below uses hypothetical numbers to illustrate the calculation. Always refer to your provider’s official pricing page and effective dates for actual figures.
| Item | Before Price Change | After Price Change |
|---|---|---|
| Input price (per 1M tokens) | 10 | 6 |
| Output price (per 1M tokens) | 40 | 24 |
| Avg. input tokens per call | 3000 | 3000 |
| Avg. output tokens per call | 500 | 500 |
| Cost per call | 0.05 | 0.03 |
In this example, the per-call cost drops by 40%. If a task averages 6 calls, the per-task cost falls from 0.30 to 0.18.
A price cut is not the same as a task-level cost reduction. If the new model needs 8 calls to complete the same task, the per-task cost becomes 0.24—still lower than before, but the savings shrink. When measuring cost reduction, track unit price, input/output ratio, and average step count together.
Step 3: Model Selection Order
- Filter by task success rate first. Exclude any model below your acceptance threshold.
- Check whether P95 latency meets your interaction requirements. Real-time conversations and background batch jobs have different latency standards.
- Compare per-task cost last.
The cheapest model per token is not necessarily the cheapest overall. If its tool call validity rate is low and retries are frequent, total cost may be higher.
Within a single pipeline, you can mix models by step: route simple intent classification and formatting to fast, low-priced models, and reserve complex planning for stronger reasoning models. Validate this routing strategy against your evaluation set—don’t set it based on intuition alone.
Engineering Implementation Notes
Below is a sketch of a constrained execution framework. call_with_retry and price_fn need to be implemented yourself: call_with_retry should include exponential backoff retries, and price_fn should compute cost from the usage data returned by your provider.
import jsonimport timeALLOWED_TOOLS = {"search_order", "get_weather"} # Tool whitelist; only pre-registered tools allowedMAX_STEPS = 5 # Max rounds to prevent infinite loopsMAX_BUDGET_YUAN = 0.5 # Per-task budget capTIMEOUT_SECONDS = 20 # Total timeout per task (seconds)def run_agent_task(user_query, tools, llm_client, tool_runner, price_fn):started = time.time()spent = 0.0messages = [{"role": "system", "content": "You are a task execution assistant. Choose only necessary tools and keep reasoning brief."},{"role": "user", "content": user_query},]for _ in range(MAX_STEPS):if time.time() - started > TIMEOUT_SECONDS:return {"status": "timeout", "answer": None}resp = call_with_retry(llm_client, messages, tools)spent += price_fn(resp.usage)if spent > MAX_BUDGET_YUAN:return {"status": "budget_exceeded", "answer": None}try:action = json.loads(resp.content)except json.JSONDecodeError:messages.append({"role": "user", "content": "Output is not valid JSON. Please retry."})continueif action.get("type") == "final_answer":return {"status": "ok", "answer": action.get("content")}name = action.get("tool_name")if name not in ALLOWED_TOOLS:return {"status": "tool_denied", "answer": None}try:result = tool_runner(name, action.get("parameters", {}))except Exception as exc:result = {"error": str(exc)}# Keep only necessary fields in tool results to prevent context bloatmessages.append({"role": "assistant", "content": resp.content})messages.append({"role": "tool","name": name,"content": json.dumps(result, ensure_ascii=False),})return {"status": "max_steps", "answer": None}
A few points to note in the code:
- Tool parameters must be validated against a JSON Schema before execution—never pass them directly to tool functions.
- Providers differ in how they format
toolrole messages; adjust according to their documentation. - Tool outputs are data, not instructions. Treating them as commands risks prompt injection, where malicious text embedded in web pages or documents could trick the model into calling tools it shouldn’t.
- If you use a cloud platform’s container and autoscaling capabilities, set minimum and maximum instance counts and monitor request queue time. When scaling lags behind traffic, queue time rises before error rates do.
Pre-Launch Checklist
- Set daily and per-task budgets for each user or tenant.
- Apply least-privilege tool permissions; write operations such as deletion, payment, and sending must require human confirmation.
- Semantic caches need a similarity threshold and expiration time, plus logging of false-hit samples.
- Monitor per-task cost, P95 latency, and failure rate, with alerts for abnormal fluctuations.
- Use separate queues for real-time requests and background batch jobs so batch work doesn’t exhaust your quota.
- Mask sensitive user data before sending it to the model, and review the provider’s data retention and training policies.
- Document fallback logic for rate limiting, timeouts, and model unavailability.
Common Mistakes
The first mistake is looking only at unit price. Retries, multi-turn calls, and context bloat all increase total cost.
The second is caches with no invalidation mechanism. When model outputs or business rules change, stale cached answers are still served.
The third is unbounded context accumulation. Appending full tool results every round causes input tokens—and costs—to grow continuously.
The fourth is equating a price cut with cost reduction. Price cuts only change unit prices; final cost also depends on the task’s call structure.
Conclusion
Models and prices change constantly, so fixed selection conclusions expire quickly. Maintaining a reusable evaluation set and re-measuring with the same metrics on a regular schedule is more reliable than trusting any single leaderboard or vendor claim.
