LLM Selection for Agent Scenarios: Evaluating Capability and Cost

    A practical guide to choosing large language models for AI agent workloads. It explains why the cheapest per-token price rarely means the lowest business cost: agent tasks run as multi-turn loops where retries, tool outputs, and reasoning tokens drive real spend. The article walks through building measurable task profiles, reading the five most misread capability specs (context window, output budget, shared input/output window, video input and billing, and tool calling), standardizing cost accounting before comparing vendors, and ranking candidates by cost per successful task using a reproducible evaluation set. It also covers task decomposition, budget caps, routing and fallback, caching, and common selection pitfalls.

    Why Per-Call Price Doesn’t Equal Business Cost

    For the same “read files, write code, call tools” job, different models can differ by tens of times in the cost of a single round. One model may cost a few cents per round, another a few dollars, and one that fails and retries three times can end up several times its initial quote. So selection is not about “which model is cheaper per million tokens.” It is about “which model combination makes each successfully completed business task cost less, with less rework.”

    1. Cost is driven by the task, not the unit price

    An agent’s business request is usually not a single model call but a multi-turn loop of “plan, call a tool, read the result, decide again.” Every round carries three kinds of tokens:

    • System prompts, tool descriptions, and conversation history;
    • Tool-returned content such as code files, logs, and retrieval snippets;
    • The model’s reasoning and its final answer.

    System prompts and tool descriptions are resent every round, and historical tool results accumulate round over round. As a result, the actual input volume often far exceeds “how long the user’s question was.”

    2. Success rate determines the real cost

    Let the per-round success rate be p, with a retry on failure. The average number of rounds is then 1/p, and the expected cost per task is roughly 1/p times the cost of a single call. Within the common success-rate band (0.7–0.95), this multiplier is about 1.05–1.43. For example, Model A has a low unit price but a 70% success rate, giving a cost factor of about 1.43; Model B has a higher unit price but a 90% success rate, giving a factor of about 1.11. The gap between them shrinks considerably.

    So when you wrap a loop around a fixed code block or prompt, the hidden cost of retries must be made explicit in the budget. The metric worth comparing is “cost per successful task,” not the unit price.

    Before You Start: Turn Workloads into Measurable Task Profiles

    The table below organizes common workloads along five dimensions—modality, length, tools, latency, and version—and lists the evaluation focus for each.

    Task Dimension Typical Scenario Evaluation Focus
    Plain text, medium length Ticket classification, summarization, information extraction Whether output is stable and parseable
    Mixed text and image Invoice recognition, product-image moderation, chart understanding Accuracy on small text, tables, and cross-references across multiple images
    Ultra-long text Contract review, codebase Q&A, long-report generation Effectiveness of long-text retrieval and the single-output limit
    Direct video input Monitoring-event review, teaching-video key-point extraction, meeting-recording summaries Video support, frame-extraction strategy, and per-duration billing
    Multi-turn tool calls Coding agents, ops troubleshooting, data queries Tool-selection accuracy, parameter accuracy, average rounds
    High-concurrency online Customer service, search Q&A First-token latency, throughput, and rate limiting

    It is worth stressing that these dimensions stack. A “video customer-service moderation agent,” for instance, has video input, multi-turn tool use, and online-latency requirements all at once. It must be validated as a whole, not scored as isolated single-point capabilities.

    Capability Dimensions: Five Specs That Are Easy to Misread

    At the time of writing, mainstream LLMs share several traits: context is generally at the million-token level, most support image input and tool calling, and some support video input. But shared traits do not mean interchangeability. The following five specs are the most commonly misread.

    1. Context length: window size is not effective capacity

    First, vendors write and convert K and M differently. Some use 1,000,000, some write 1,048,576 directly, and some set a separate cap on maximum input below the total window. These conventions should not be treated as exactly equal for comparison.

    Second, recall of key information varies with position. The so-called “lost in the middle” effect shows up to differing degrees across models, so long-context evaluation should cover the beginning, middle, and end.

    Third, for agents, long context is mostly the capacity to load more tool returns per call. The fuller the input, the higher the per-round cost, so a “retrieval recall + long context” combination is usually more economical than “stuff the whole store in.”

    2. Single-output budget: not the length of the final answer

    The single-output limit determines whether a model can generate a complete result in one round, which matters a lot for tasks that must produce large code blocks or long documents at once.

    More important, the reasoning process also consumes generated tokens. Some models’ thinking modes put the chain of thought and the final answer into the same shared budget: the longer the thinking, the less room left for the answer. Differences in K/M conversion get amplified further at the hundreds-of-thousands-of-tokens scale.

    In practice, measure the P95 of single-output length in your workload, then reserve a 30%–50% margin. If a certain task type’s expected output chronically approaches the limit, split it into subtasks, or favor candidates with a larger output budget.

    3. Whether input and output share the total window

    For some models, the total window is shared between input and generation. If the input is near the limit, the space available for output is compressed. Do not read “million-token context” and “super-long output” as two independent quotas. Build an extreme test case—“input near the limit while requiring a long output”—and watch for truncation or quality degradation.

    4. Input modality and billing: video input is often the most expensive

    Native video support directly determines whether video tasks can go through at all. If a model does not support it, you must first extract frames into an image sequence, then feed them in frame by frame or in batches.

    Vendors bill video differently: some charge by the image tokens after frame extraction, others convert from duration. One minute of video at 1 frame per second, with a few hundred tokens per frame, easily reaches tens of thousands of input tokens. So the primary question for video tasks is not which model is stronger, but the “processing cost per unit of video duration.”

    5. Tool calling and structured output: the key to agent success

    Models with Max, Pro, or Flash in their names all have tool-calling ability; the suffix only reflects product positioning and does not prove agent success rates. What actually needs verifying is:

    • Tool-description adherence: whether it can pick the correct one from a dozen-plus candidate tools;
    • Parameter correctness: whether required fields are complete and types and enum values are valid;
    • Parallel calls: whether it can issue multiple independent calls in a single response;
    • Error correction: whether it can read an error message after a tool failure and fix it;
    • Structured output: whether it can reliably produce JSON matching an agreed structure;
    • Multi-turn convergence: whether it can finish within a reasonable number of rounds instead of repeatedly calling the same tool.

    In addition, some models offer both thinking and non-thinking modes. When this surfaces at the call layer as a toggleable “reasoning intensity” or “reasoning budget” parameter, you can turn off deep thinking for simple tasks to reduce cost and latency.

    Cost Dimensions: Compare Only After Standardizing

    1. Factors that affect billing

    Vendors’ pricing pages differ a lot in the details. Before comparing side by side, unify these conventions:

    • Whether input and output are priced separately, and whether the output unit price is significantly higher than the input;
    • Whether reasoning tokens are billed as output tokens;
    • How images, videos, and other inputs are converted;
    • Whether there are context-caching or prefix-caching discounts;
    • Whether there are tiered prices, free quotas, or batch/async task discounts;
    • The billing rounding method and the minimum billing unit.

    A single price is momentary information that can change at any time, so this article cites no specific numbers. A good practice is to organize prices into a unified configuration table that a program reads. Unified model-access platforms such as Baidu AI Cloud’s Qianfan platform let you view different models’ billing standards in one interface, which makes centralized maintenance easier.

    2. A per-task cost accounting script

    A practical approach is to depend on no SDK at all: read the input, output, and reasoning token counts straight from the call response, then combine them with a price table to compute cost. The same script then applies across different access methods.

    1. """
    2. Per-task cost accounting and model ranking example (standard library only)
    3. Usage:
    4. python cost_model.py price.json usage_a.json
    5. python cost_model.py price.json usage_a.json usage_b.json
    6. price.json format:
    7. {"low_cost": {"input": 0.8, "output": 2.0},
    8. "large_output": {"input": 4.0, "output": 16.0}}
    9. usage.json is written by the call gateway, one record per call:
    10. {"model": "large_output", "task_id": "T-017",
    11. "input_tokens": 98000, "output_tokens": 12000, "reasoning_tokens": 5000}
    12. """
    13. import json
    14. import statistics
    15. import sys
    16. from collections import defaultdict
    17. THINK_RATIO = 1.5 # reasoning tokens billed at 1.5x output; adjust to the actual convention
    18. def load_prices(path):
    19. # normalize unit price to "$ / 1K tokens" so it multiplies directly with token counts
    20. with open(path, encoding="utf-8") as f:
    21. raw = json.load(f)
    22. return {k: {"input": v["input"] / 1000,
    23. "output": v["output"] / 1000} for k, v in raw.items()}
    24. def load_usage(paths):
    25. records = []
    26. for path in paths:
    27. with open(path, encoding="utf-8") as f:
    28. records.extend(json.load(f))
    29. return records
    30. def call_cost(model, rec, prices):
    31. p = prices[model]
    32. billed_output = rec.get("output_tokens", 0) + \
    33. THINK_RATIO * rec.get("reasoning_tokens", 0)
    34. return rec["input_tokens"] * p["input"] + billed_output * p["output"]
    35. def evaluate(records, prices):
    36. # 1. aggregate per-call cost by model
    37. costs = defaultdict(list)
    38. for rec in records:
    39. costs[rec["model"]].append(call_cost(rec["model"], rec, prices))
    40. # 2. per task, count rounds and accumulated cost
    41. # rounds = total calls of the task / number of tasks
    42. # cost = sum of all call costs / number of tasks
    43. tasks = defaultdict(lambda: {"calls": 0, "cost": 0.0})
    44. for rec in records:
    45. t = tasks[rec["task_id"]]
    46. t["calls"] += 1
    47. t["cost"] += call_cost(rec["model"], rec, prices)
    48. n = max(len(tasks), 1)
    49. avg_turns = sum(t["calls"] for t in tasks.values()) / n
    50. task_cost = sum(t["cost"] for t in tasks.values()) / n
    51. # 3. if the access layer marks whether each task passed, cost per success can be computed
    52. # when unmarked, assume all completed; the conclusion is conservative
    53. passed = [t for t in tasks.values() if t.get("passed", True)]
    54. cost_per_pass = (sum(t["cost"] for t in passed) / len(passed)) if passed else None
    55. print(f"{'model':<14}{'success':>8}{'avg_rounds':>10}"
    56. f"{'avg_cost':>12}{'P95_cost':>12}")
    57. for m in sorted(costs):
    58. mc = [c for r, c in zip(records, [call_cost(x["model"], x, prices)
    59. for x in records]) if r["model"] == m]
    60. ts = [t for r, t in zip(records, [tasks[x["task_id"]]
    61. for x in records]) if r["model"] == m]
    62. sr = sum(t.get("passed", True) for t in ts) / len(ts)
    63. print(f"{m:<14}{sr:>8.0%}"
    64. f"{sum(t['calls'] for t in ts) / len(ts):>10.2f}"
    65. f"{statistics.mean(mc):>12.4f}"
    66. f"{sorted(mc)[int(0.95 * (len(mc) - 1))]:>12.4f}")
    67. print(f"overall avg rounds {avg_turns:.2f}, avg cost per task "
    68. f"{task_cost:.4f}$, cost per success "
    69. f"{cost_per_pass if cost_per_pass else float('nan'):.4f}$")
    70. if __name__ == "__main__":
    71. evaluate(load_usage(sys.argv[2:]), load_prices(sys.argv[1]))

    The script embodies three principles:

    • Correct weighting: the billing multiplier for reasoning tokens is configured separately, since conventions differ across vendors;
    • Unified units: prices are normalized to “$ / 1K tokens,” avoiding the mental-math errors of million-scale units;
    • Complete metrics: besides the mean, it also outputs P95 cost, so long-tail tasks cannot silently inflate the overall budget.

    If a workload has a lot of repeated input—for example, a fixed, unchanging code-repository context—favor models or services that offer context caching, and have the gateway record cache hits in the billing log.

    Agent Scenarios: Set Candidate Order by Workload

    For each new workload type, build candidates in the order “eliminate first, baseline, then optimize”:

    1. Eliminate: for tasks with video input or a demand for super-long single output, filter out candidates that fail these hard constraints;
    2. Baseline: for high-frequency text-and-image and structured tasks, first run a low-cost model end to end and compute the baseline cost, while leaving some traffic for low-cost real-time OCR-type services to do preprocessing;
    3. Optimize: add large-output and strong-reasoning candidates to the same evaluation set, and use success rate and rounds to decide the final routing weights.
    Workload Type Candidate Order Key Acceptance Items Cost-Control Levers
    High-frequency text-and-image and structured Low-cost tier → mainstream tier Field-level accuracy, JSON parse success rate Fixed JSON structure; OCR preprocessing; prefix caching
    Long-context generation Large-output-budget tier → long-context tier Key-information recall, output completeness Retrieval-based pre-trimming; generate in segments, then merge
    Direct video input Native-video-input tier → frame-extraction approach Key-event detection rate, cost per minute Scene-change frame extraction; low-resolution first pass
    Complex multi-step agent Strong-tool-calling tier → large-output tier Task success rate, average rounds Subtask decomposition; retry limit; small model executes + large model reviews

    The table above gives candidate order, not an effectiveness ranking. The final order must be settled by the business evaluation in Section 7.

    Task Decomposition and Budget Control: Design Sets the Agent’s Cost Ceiling

    1. Avoid three typical cost amplifiers

    • Full history backfill every round: long tool-returned text repeatedly enters the context, and input tokens grow quickly with the number of rounds;
    • Retry storms after failure: without a maximum number of rounds and a timeout cap, an agent can fall into an ineffective loop;
    • Generating super-long content in one shot: once the output limit is hit, content is truncated, and then “continue writing” bills you again.

    The corresponding constraints and budget pseudocode look like this:

    1. # Hard constraints for the agent loop (pseudocode, adjust per framework)
    2. MAX_TURNS = 12 # max number of turns
    3. MAX_RETRIES = 2 # max retries for a single tool
    4. TASK_BUDGET = 0.50 # cost cap per task, in $
    5. msgs = [system_prompt, user_input]
    6. total_cost = 0.0
    7. for turn in range(MAX_TURNS):
    8. resp = chat(model, msgs, tools=tool_specs)
    9. total_cost += resp.usage.input * P_IN + resp.usage.output * P_OUT
    10. if total_cost > TASK_BUDGET:
    11. return fallback(resp) # degrade: hand off to a human or return a partial result
    12. if resp.tool_calls:
    13. msgs += tool_results(resp.tool_calls, max_retry=MAX_RETRIES)
    14. else:
    15. return validate(resp.text) # if structured validation fails, ask the model to fix it
    16. raise BudgetExceeded(total_cost)

    For long-file scenarios, an “outline → generate in segments → consistency check” flow can replace generating the entire file in one shot.

    2. Routing and fallback

    1. # Task routing sketch (model names are placeholders; functions return a unified response object)
    2. def route(task):
    3. if task.need_video or task.need_deep_reasoning:
    4. return strong_model(task) # video understanding / complex planning
    5. if task.has_tool and task.turns_hint > 5:
    6. return agent_model(task) # long-chain tool orchestration
    7. if task.need_long_output:
    8. return large_output_model(task) # larger single-output budget
    9. return cheap_model(task) # high-frequency, simple, cost-sensitive
    10. def run_with_fallback(task):
    11. try:
    12. return route(task)
    13. except (TimeoutError, RateLimitError):
    14. return strong_model(task) # switch to a backup model when the primary path fails

    The router can live in a self-built gateway or in the unified access layer of platforms such as Baidu AI Cloud’s Qianfan platform. When switching models, keep tool descriptions and output structures consistent so downstream parsing logic does not have to change.

    3. Make good use of caching

    • Context caching: stable prefixes such as system prompts, tool definitions, and long documents can be cached and reused, lowering input cost on repeated calls;
    • Semantic caching: return historical answers directly for high-frequency repeated questions;
    • Result caching: reuse results for the same file or the same code snippet, keyed by a content hash.

    Business Re-testing: The Same Task Set Decides the Final Choice

    1. Building the evaluation set

    • Sample 50–200 desensitized tasks from real business traffic;
    • Cover high-frequency scenarios (~60%), long-tail scenarios (~30%), and boundary scenarios (~10%, e.g., super-long input, blurry images, tool errors, ambiguous requirements);
    • Attach an expected result or an acceptance script to each task, and label its difficulty level.

    2. Execution and metrics

    Have all candidates use the same prompts, tool definitions, maximum number of rounds, and temperature parameters, and repeat each task 3–5 times. The metrics below can serve directly as the output columns of the Section 4 script; it is worth writing them to object storage and a logging service to make version-to-version comparison easy:

    Metric Calculation How to Read It
    Task success rate Tasks that pass acceptance / total tasks View by difficulty tier, so easy cases do not mask weaknesses on hard ones
    Average rounds Total calls / number of tasks Reflects convergence ability; positively correlated with cost
    Average and P95 cost Mean and 95th percentile of per-task cost P95 sets the budget ceiling
    Cost per success Total cost / number of successful tasks The core ranking metric for selection
    Tool-call accuracy Correct calls / total calls Includes both tool selection and parameter correctness
    Output completeness Non-truncated outputs / total outputs Directly related to the single-output budget

    3. Producing the conclusion

    1. First eliminate candidates that fail hard constraints (e.g., video input, output limit);
    2. Rank the remaining candidates by “cost per success,” and reference P95 cost;
    3. When the quality gap is within the noise range, prefer the model with the lower unit price and more stable latency.

    Common Pitfalls

    • Looking only at the unit price: ignoring the output share, reasoning tokens, and retry rounds; the actual bill can deviate from expectations by a multiple.
    • Treating context length as capability: no matter how large the window, it does not mean key information can be found reliably.
    • Inferring answer quality from the output limit: the output budget only constrains “how long it can write,” not “whether it writes correctly.”
    • Using general leaderboards in place of business evaluation: the question distribution of public leaderboards differs greatly from real business, so conclusions do not transfer directly.
    • Concluding after a single test: model versions and prices both get updated; integrate evaluation into a CI process, and pin model snapshot versions at the gateway layer.
    • Ignoring tail latency: batch tasks care about throughput, online interactions care about P95 latency; the two metric sets should not be mixed.

    Conclusion

    Facing mainstream models whose context is generally at the million-token level, the key to selection is not finding the single “strongest” or “cheapest” one, but building a reproducible evaluation system:

    1. Use task profiles to set hard constraints;
    2. Use unified units to account for cost;
    3. Use a business evaluation set to validate agent performance;
    4. Use routing, budgets, and caching to control long-term spend.

    Letting data—not model names—answer “who to choose” is what lets you strike a balance among effectiveness, cost, and stability.