Model Selection in the Agent Era: From Inference Latency to Cache Cost

    This article provides a practical framework for selecting LLM models in AI agent systems. It analyzes the unique pressure agents place on model services—multi-step tool calls, high input token volume, and strict latency requirements—and explains how to evaluate models across three key dimensions: response speed, long-context reuse, and real cost. It covers measuring time-to-first-token (TTFT), designing stable prefix caches, estimating monthly spend under caching assumptions, avoiding misleading promotional pricing, and building a provider-agnostic adapter layer. A five-step evaluation checklist for production deployment is also included.

    1. Background: What Agent Workloads Demand from Models

    In traditional conversational applications, a single request typically follows a simple pattern: the user asks a question, and the model responds. An AI agent operates differently. It resides persistently on a user’s device or server, continuously receiving instructions, decomposing tasks, invoking tools such as terminal commands, file I/O, and log retrieval, and feeding the results back to the model for the next decision. A single task can involve a dozen or more model calls.

    This interaction pattern places two types of pressure on model serving infrastructure. The first is interactive latency. When a user types a command into a terminal, a wait of several seconds before the first character appears makes the system feel sluggish. The second is cost per call. Each agent turn carries the system prompt, user preferences, conversation summaries, and tool descriptions, meaning the total input token count far exceeds that of typical Q&A interactions.

    As a result, model selection must consider three factors simultaneously: whether responses are delivered promptly, whether long contexts can be reused at low cost, and whether the actual expenditure stays within acceptable bounds. The following sections examine each in turn.

    2. Architecture Breakdown: Responsibilities of the Local Gateway and Cloud Inference

    A typical agent system is split into two layers.

    The local gateway is responsible for user and system interaction, handling the following duties:

    • Session management: maintaining conversation state and the task queue;
    • Access control: restricting which commands can be executed, requiring confirmation for high-risk operations;
    • Tool orchestration: parsing tool-call requests returned by the model, executing them, and returning results;
    • Context assembly: deciding which historical information enters the current request;
    • Logging and redaction: recording call traces while removing secrets and personally identifiable information.

    The cloud model handles inference—generating plans, replies, or tool-call parameters based on the assembled context. Communication between the two layers typically uses a standardized message format.

    Below is a simplified gateway main loop illustrating the division of responsibilities:

    1. class AgentGateway:
    2. def __init__(self, provider, memory_store, tools):
    3. self.provider = provider
    4. self.memory = memory_store
    5. self.tools = tools
    6. def handle(self, user_input: str) -> str:
    7. messages = self.memory.build_context(user_input)
    8. reply = self.provider.complete(messages)
    9. # Tool calls are executed by the gateway; results are written back
    10. # to memory and read by the model in the next round.
    11. for call in reply.tool_calls:
    12. if not self.tools.is_allowed(call.name):
    13. result = {"error": "tool not permitted"}
    14. else:
    15. result = self.tools.run(call.name, call.arguments)
    16. self.memory.append_tool_result(call.id, result)
    17. self.memory.append_assistant(reply.text)
    18. return reply.text

    The advantage of this separation is that the model can be swapped without changing gateway logic. The model remains responsible for a single duty—inference—while security policies and business rules stay in a controllable layer.

    3. Inference Latency: TTFT Matters More Than Total Time

    When measuring interactive experience, time-to-first-token (TTFT) is more important than the total time required to complete a response. What users notice first is whether the system has begun responding, not when the answer finishes. In agent scenarios, the gateway must also wait for tool calls in the model output, so TTFT directly lengthens the wait time at every step.

    Three factors primarily affect TTFT:

    1. Context length on the request side: the longer the input, the more computation required in the prefill phase.
    2. The model’s compute path: dense models activate all parameters on every inference, while Mixture-of-Experts (MoE) models activate only a subset of expert sub-networks. At the same total parameter count, sparse activation generally reduces per-token forward computation, but routing itself carries overhead, and all expert parameters still consume VRAM. MoE is therefore not automatically faster than a dense model—it must be measured.
    3. Server-side queueing and batching: under high concurrency, queue wait time can exceed inference time.

    The measurement method is straightforward. Use streaming output and record the time from request submission to the arrival of the first chunk:

    1. import time
    2. def measure_ttft(stream) -> float | None:
    3. start = time.perf_counter()
    4. for chunk in stream:
    5. if chunk:
    6. return time.perf_counter() - start
    7. return None

    It is recommended to sample multiple times across different time windows, context lengths, and concurrency levels, then report the median and P95 values. A single measurement is easily misleading due to network jitter.

    4. Long Contexts and Prefix Caching: Quantifying the Cost of Persistent Memory

    Agents must retain long-term information—role definitions, tool descriptions, user preferences, and project background. These typically appear as a fixed prefix at the start of every request. If the serving infrastructure supports prefix caching (also called context caching), previously computed prefix states can be reused, so subsequent requests only need to process the newly added portion.

    The precondition for caching to pay off is a sufficiently stable prefix. The following factors invalidate the cache:

    • Timestamps, random IDs, or other content that changes with every request mixed into the prefix;
    • Frequent modifications to the system prompt;
    • History messages whose ordering or formatting varies from round to round;
    • A cache TTL shorter than the interval between requests.

    A useful engineering principle is to place stable content first and dynamic content last:

    1. [System role and rules] Stable, suitable for caching
    2. [Tool descriptions] Stable, suitable for caching
    3. [Long-term user preference summary] Low-frequency changes, suitable for caching
    4. [Recent conversation history] Dynamic, computed separately
    5. [Current user input] Dynamic, computed separately

    In addition, conversation history should not be appended to the context without limit. Periodically compressing earlier conversation turns into summaries keeps the input length in check and allows the stable prefix to remain reusable for longer.

    Cost estimation can be done with a simple model. The function below assumes pricing per million tokens; the price parameters are placeholders and should be replaced with the provider’s published billing rules:

    1. def monthly_cost(calls_per_day: int,
    2. input_tokens: int,
    3. output_tokens: int,
    4. cached_ratio: float,
    5. price_in: float,
    6. price_cached: float,
    7. price_out: float,
    8. days: int = 30) -> float:
    9. cached = input_tokens * cached_ratio
    10. fresh = input_tokens - cached
    11. per_call = (fresh * price_in
    12. + cached * price_cached
    13. + output_tokens * price_out) / 1_000_000
    14. return per_call * calls_per_day * days

    By adjusting the cached_ratio, the impact of cache hit rate on total cost becomes immediately visible. Many teams focus only on unit price during estimation and overlook the proportion of repeated prefix tokens in the input, leading to significant budget deviations.

    5. Trial Quotas and Real Costs: Don’t Treat Promotional Pricing as Long-Term

    Model providers often attract users with trial credits, limited-time discounts, or developer support programs. These policies lower the barrier to early experimentation but are time-limited and subject to change. Treating them as long-term pricing assumptions introduces three types of risk.

    First, prices and quotas may be adjusted. Once the policy changes, any budget built on that assumption becomes invalid immediately.

    Second, quota is not throughput. Even if call fees are zero, rate limits, concurrency caps, and queueing delays still exist. Production capacity planning must use peak values, not averages.

    Third, migration costs are underestimated. Agent prompts, tool definitions, and evaluation sets are often coupled to a specific provider’s interface behavior. Without an abstraction layer, switching models can require substantial rework.

    A more robust approach is to establish a unified cost evaluation framework that accounts for average token consumption per task, average number of calls, failure retry rate, and peak concurrency. The total cost of a single task can be expressed as:

    Single-task cost = Average number of calls × Cost per call × (1 + Retry rate)

    Only by quantifying all these variables can different solutions be compared on a fair basis for their real expenditure.

    6. Model Swappability: Isolating Provider Differences with an Adapter Layer

    To reduce lock-in risk, it is recommended to add an adapter layer between the gateway and the model, separating business code from the interface details of any specific provider.

    1. from typing import Protocol
    2. class ChatProvider(Protocol):
    3. def complete(self, messages: list[dict]) -> str: ...
    4. class FallbackProvider:
    5. """Fall back to a backup model when the primary is unavailable or times out."""
    6. def __init__(self, primary: ChatProvider, backup: ChatProvider):
    7. self.primary = primary
    8. self.backup = backup
    9. def complete(self, messages: list[dict]) -> str:
    10. try:
    11. return self.primary.complete(messages)
    12. except Exception:
    13. return self.backup.complete(messages)

    The adapter layer can also handle other responsibilities, such as unified retry policies, request logging, cost tracking, and canary switching. When evaluating a new model, the same task set can be run against both versions to compare task completion rate, TTFT, and per-task cost before deciding whether to switch.

    7. Selection Workflow and Deployment Checklist

    Based on the analysis above, a practical model selection process can be broken into five steps:

    1. Define the task set. Select representative tasks from real business scenarios, including short instructions, multi-step tool calls, and long-context Q&A, and set a passing criterion for each type.
    2. Measure latency. Measure TTFT and total duration under target concurrency and context length, recording P50 and P95 values.
    3. Measure cost. Using the framework in Section 5, calculate the monthly cost for the steady state (not the trial period), including a sensitivity analysis for cache hit rate.
    4. Measure stability. Record timeout rates, error code distributions, and rate-limit trigger frequencies to confirm behavior under peak load.
    5. Review compliance. Verify data storage location, log retention policies, and encryption in transit, and identify which information must not be sent to external services.

    At deployment time, standard infrastructure capabilities can support the monitoring and governance needs. For example, a container platform can manage gateway scaling, a message queue can absorb traffic spikes, a log service can record tool-call traces, and monitoring alerts can track TTFT, error rates, and daily spend. If deployed on Baidu AI Cloud, these capabilities are available through its container, messaging, logging, and monitoring products, though the architecture itself is platform-agnostic.

    Model selection in agent systems is fundamentally an engineering trade-off among latency, cost, quality, and swappability. By quantifying metrics, decoupling the architecture, and grounding cost models in stable assumptions, a system can remain maintainable amid the rapid iteration of models.