Choosing an LLM for AI Agents: Cost and Latency Considerations

    AI agents call a model dozens of times per task, so per-call latency and cost add up quickly. This article explains how to evaluate models for agent workloads. It covers time to first token, prefix caching for long contexts, the limits of free quotas, and the role of a model abstraction layer. It also outlines a repeatable evaluation process.

    From Single Exchanges to Continuous Execution

    Until recently, most LLM applications followed a simple pattern. A user sent a text prompt, and the model returned a text response. Users could generally tolerate a bit of extra latency or a higher price per call.

    AI agents change this pattern. An agent calls the model repeatedly in the background. It reads the context, decides on the next action, calls external tools, and feeds the tool results back to the model for further reasoning. A single task may trigger dozens of model calls, so the latency and cost of each call are multiplied.

    As a result, model selection shifts from “Which model has the strongest capabilities?” to “Which model fits this calling pattern best?” This article covers three areas: how time to first token (TTFT) affects the interactive experience, how caching changes the cost of long contexts, and how free or time-limited quotas should factor into architecture decisions.

    Time to First Token Determines Whether Interaction Feels Responsive

    Time to First Token (TTFT) is the time from sending a request to receiving the first output token. For applications that need immediate feedback, such as intercepting a user’s terminal operations or making quick decisions in a local gateway, TTFT matters more than overall throughput. A wait of more than two seconds is noticeable to users as lag. Total generation time mainly affects the reading pace after the result starts to appear.

    Sparse Mixture of Experts (MoE) architectures are a common design for reducing inference cost. A model can have a large total parameter count, but each token passes through only a subset of expert networks. The number of parameters active in computation is therefore much smaller than the total. This design keeps high parameter capacity while limiting the computation required for each inference.

    Fewer active parameters do not guarantee low latency. Actual TTFT also depends on queuing time, network round trips, the server’s batching strategy, and input length. Longer inputs require more computation in the prefill stage, so the first token arrives later. Figures in marketing materials are only a reference. Measure TTFT on your own workload before making a selection.

    The following sketch shows how to measure TTFT. stream_fn is a streaming interface wrapper that you implement yourself. It returns an iterator that yields text chunks one at a time.

    1. import time
    2. from statistics import quantiles
    3. def measure_ttft(stream_fn, prompt: str) -> float:
    4. """Return the number of seconds from sending the request to receiving the first data chunk."""
    5. start = time.perf_counter()
    6. for _chunk in stream_fn(prompt):
    7. return time.perf_counter() - start
    8. return float("nan")
    9. def summarize_ttft(stream_fn, prompts: list[str]) -> dict:
    10. """Compute P50 and P95 over a batch of samples so the result does not rely only on the average."""
    11. samples = [measure_ttft(stream_fn, p) for p in prompts]
    12. samples = [s for s in samples if s == s] # Filter out NaN values
    13. cuts = quantiles(samples, n=20)
    14. return {"p50": cuts[9], "p95": cuts[18], "count": len(samples)}

    Evaluate both P50 and P95. Averages can hide tail latency, and tail latency is the main source of perceived lag.

    Long Context and Caching: Making Repeated Input Cheaper

    Agents need to maintain system settings, tool descriptions, user preferences, and history summaries over long sessions. This content mostly stays the same across calls, forming a stable prefix. If every call recomputes that prefix at full price, the cost of long contexts adds up quickly.

    Prefix caching works like this: the server stores intermediate results for input prefixes it has already computed. When a later request has a prefix that matches the cache, the server reuses that computation and usually bills those tokens at a lower price. The benefit depends on the implementation. Three practices matter most:

    1. Place stable content at the beginning of the prompt and dynamic content at the end. Once a prefix differs, nothing after it can be reused from the cache.
    2. Keep timestamps, random request IDs, and other values that change on every call out of the system prompt. These fields invalidate the cache.
    3. Manage request intervals. Caches usually expire after a time-to-live period, so hot prefixes need requests often enough to keep the cache valid.

    Cache hit rate deserves more ongoing monitoring than unit price. For the same model, the cost per task can differ several times over depending on whether the hit rate is low or high.

    The following code estimates the cost of a single task. Prices are in currency units per million tokens. Use the pricing rules published by the provider as the authoritative source.

    1. def estimate_task_cost(
    2. input_tokens: int,
    3. cached_tokens: int,
    4. output_tokens: int,
    5. price_input: float,
    6. price_cached: float,
    7. price_output: float,
    8. calls: int = 1,
    9. ) -> float:
    10. """Estimate the total cost of a multi-step task. Prices are per million tokens."""
    11. uncached = max(input_tokens - cached_tokens, 0)
    12. per_call = (
    13. uncached * price_input
    14. + cached_tokens * price_cached
    15. + output_tokens * price_output
    16. ) / 1_000_000
    17. return per_call * calls

    Agent input usually grows at each step, because every step appends earlier results to the context. When you estimate the cost of a task, add up the cost of each step instead of multiplying the cost of one call by the number of steps.

    Free Quotas Are Not a Long-Term Cost Assumption

    Free quotas are usually promotions with time windows, usage caps, or conditions attached. They suit prototyping, stress testing, and feature exploration, but they should not be the cost basis for a production system. When a promotion ends, the quota runs out, or the conditions change, the cost of running the system changes too.

    To decide whether a promotional resource is safe to depend on, answer these four questions:

    • What is the standard unit price after the quota is used up, and can the business afford it?
    • Is the quota measured by request count, token count, or duration? The metric has a large effect on agents. A multi-step task can exhaust a token-based quota within minutes.
    • When the quota is exceeded, does the service degrade, queue requests, or reject them outright? Degraded responses can change output quality, so tests should cover this case.
    • How much code must change to switch to another model? If prompts, tool-call formats, and output parsing are tightly coupled to one provider, migration will be costly.

    A practical approach is to record two cost figures for each model in the design document: the cost during the promotion and the cost at standard prices. Architecture decisions should be based on standard-price costs. Promotional savings count only as a bonus.

    Provider Dependency and the Model Abstraction Layer

    When a model becomes the default option in a tool or platform, it can drive significant user growth, but it also creates dependency. Defaults can change because of partnership arrangements, price adjustments, or service changes that developers cannot control.

    The engineering response is to introduce a model abstraction layer that separates the choice of model from business logic. An abstraction layer typically includes the following components:

    • A unified request and response structure, so business code targets internal interfaces only;
    • Task-based routing, for example, using a smaller model for simple tasks such as classification and extraction, and a stronger model for complex tasks such as planning and code generation;
    • Retries and fallback routing, which switch models automatically when one times out or returns an error;
    • A shared evaluation set, so all candidate models are compared on the same samples.

    The following is an example routing configuration. Model names are placeholders. Replace them with the model identifiers you deploy or purchase.

    1. routing:
    2. default: model_large
    3. rules:
    4. - task: classify
    5. model: model_small
    6. max_latency_ms: 800
    7. - task: plan
    8. model: model_large
    9. fallback: model_medium
    10. - task: code_edit
    11. model: model_medium
    12. fallback: model_large
    13. retry:
    14. max_attempts: 2
    15. on_status: [429, 500, 503]

    The value of the abstraction layer is that when a model’s price, latency, or availability changes, you only update the configuration. Business code stays the same.

    Steps for Evaluating Model Selection

    A repeatable evaluation process is worth more than a one-time comparison. Follow these steps:

    1. Collect real task samples. Samples should cover four categories: successful cases, failure cases, long inputs, and tasks that require tool calls. Keep the anonymized raw data.
    2. Define metrics. At minimum, include the P50 and P95 of TTFT, task completion rate, cost per task, and the number of manual corrections.
    3. Fix test conditions. Use the same prompts, temperature setting, and tool definitions so the comparison reflects differences between the models themselves.
    4. Calculate the cost per task. Accumulate costs step by step using the cost function above, and record cache hit rates.
    5. Roll out gradually. Keep a fallback path, observe performance under real traffic, and then decide whether to expand the share of traffic.

    Save evaluation results in a table so you can reuse them when models are updated. Whenever a provider changes prices or releases a new version, rerun the same evaluation suite.

    Conclusion

    Agent applications turn model calls from occasional events into continuous ones, which changes the criteria for selecting a model. Time to first token determines whether interaction feels responsive. Prefix caching determines whether long contexts are affordable. Free quotas only show short-term feasibility.

    Use this checklist to test whether a design will hold up over time:

    • Have you measured the P50 and P95 of TTFT on your own workload?
    • Have you calculated the cost per task at standard prices, rather than the cost of a single call?
    • Does the system prompt place stable content first and leave out fields that change on every call?
    • Do you have a model abstraction layer, so that switching models requires no changes to business code?
    • Do you have a shared evaluation set, and do you rerun it whenever a model or price changes?

    If your design meets these points, your team can use short-term resource benefits while keeping control over cost, quality, and availability.