Model Selection and Inference Cost Optimization for AI Agents

    AI agents place greater demands on language models than traditional question-answering systems. This article explains how to evaluate models based on latency, context growth, caching, call frequency, and cost. It also covers prefix caching, cost measurement, provider dependency, multi-model routing, fallback mechanisms, and task-specific benchmarking.

    1. New Model Requirements in Agent Workflows

    In a traditional question-answering scenario, each request is usually an independent question, and the interaction ends after the model returns a response. AI agents work differently. An agent often runs on a local or edge gateway. The gateway intercepts a user’s request, breaks the task into smaller steps, sends them to a cloud-based model, and converts the results into concrete actions.

    This architecture introduces three major pressures:

    1. High sensitivity to interaction latency: After issuing a command in a terminal or editor, users expect almost immediate feedback. When time to first token (TTFT) exceeds a certain threshold, the system begins to feel unresponsive.
    2. Continuously growing context: Agents need to include system instructions, tool definitions, previous steps, and user preferences. Most of this content is resent during every model call.
    3. High call frequency: A complex task may trigger dozens of model calls. Even a small difference in per-call cost can become significant at scale.

    As a result, model selection should not rely solely on general-purpose benchmark scores. Performance under these three pressures is equally important.

    2. Latency: From First-Token Response to Total Completion Time

    Latency can be divided into network round-trip time, queueing time, time to first token, and the output speed of subsequent tokens. For interactive agents, TTFT is especially important because it determines whether users feel that the system is responding. Total completion time determines whether a task finishes within an acceptable timeframe.

    Sparse activation architectures, commonly known as Mixture of Experts (MoE), have become increasingly popular. Although the model may contain a large number of total parameters, only a subset of expert networks is activated during the forward pass for each token. This decouples model capacity from per-request computation, allowing the model to provide greater knowledge capacity at a similar inference cost.

    However, sparse activation does not automatically guarantee low latency. Actual latency also depends on server-side batching strategies, hardware resources, and routing overhead. Measurements from the target serving environment should therefore be used for evaluation.

    The following script performs a simple TTFT measurement:

    1. import time
    2. def measure_ttft(stream_call, prompt: str) -> float:
    3. """Measure the time from request submission to the first token, in seconds."""
    4. start = time.perf_counter()
    5. for _chunk in stream_call(prompt): # stream_call wraps a streaming interface
    6. return time.perf_counter() - start
    7. raise RuntimeError("No output received")

    For the same set of representative tasks, repeat the measurement at different times at least 20 times. Record the median and P95 values instead of relying on a single result. A single measurement can be heavily affected by network fluctuations and server load, while aggregate statistics provide a more realistic view of user experience.

    3. Context Length and Cache Reuse

    Long contexts allow agents to preserve more state, but the longer the context, the higher the input cost and computation time for every call. Prefix caching is a key technique for reducing this trade-off.

    Most services that support prefix caching cache the common prefix of a request. When the prefix is exactly the same, the computation for the cached portion can be reused. This creates a clear engineering requirement: place stable content first and changing content later.

    A recommended prompt structure has three layers:

    1. Fixed content: System roles, tool definitions, and output format requirements.
    2. Semi-fixed content: Project information and long-term user preferences.
    3. Dynamic content: The current task and the latest execution results.
    1. def build_messages(system_rules, tool_schema, project_notes, history, task):
    2. # Place stable content first to improve prefix-cache hit rates
    3. prefix = [
    4. {"role": "system", "content": system_rules},
    5. {"role": "system", "content": tool_schema},
    6. {"role": "system", "content": project_notes},
    7. ]
    8. # Place dynamic content last to preserve prefix consistency
    9. dynamic = history[-10:] + [{"role": "user", "content": task}]
    10. return prefix + dynamic

    Several implementation details are easy to overlook:

    • Even a minor change can invalidate the prefix. For example, adding a current timestamp to the system prompt makes the prefix different on every call and prevents cache reuse.
    • Conversation history should be truncated or summarized rather than appended indefinitely.
    • Summarization itself requires stable generation rules. If the wording changes substantially each time, it can also break prefix consistency.

    4. How to Calculate Costs Correctly

    Agent costs typically consist of three components: uncached input tokens, cached input tokens, and output tokens. Pricing models vary across services, so models should not be compared using only a single “price per million tokens” figure. Costs should instead be estimated according to the actual request structure.

    The cost of a single task can be estimated with the following formula:

    Single-task cost = Number of calls × (uncached input tokens × uncached input price + cached input tokens × cached input price + output tokens × output price)

    The number of calls and the quantities of each token category should be collected from real logs rather than estimated from experience. A common mistake is to count only the final output while ignoring the large amount of input generated by intermediate tool calls.

    At a minimum, track the following metrics:

    • Number of calls and average number of rounds per task;
    • Input tokens, output tokens, and cached tokens;
    • End-to-end time for each task;
    • Task success rate, which is needed to calculate the cost per successful task.

    Cost data is meaningful only when evaluated together with success rate. A model with a lower unit price may not have a lower total cost if it requires repeated retries.

    5. Free Quotas and Vendor Dependency

    Some providers offer free usage quotas during promotional or ecosystem-building phases. These quotas reduce experimentation costs, but they should not become a prerequisite for the system architecture.

    Free quotas usually have the following characteristics:

    • They are limited and may be restricted by time, account, or project;
    • Service terms may change, including rate limits, available models, and pricing rules;
    • Availability and response quality may fluctuate with system load.

    A more reliable approach is to abstract model calls behind a unified interface and maintain alternative providers or endpoints. The following section presents an example of routing and fallback logic.

    6. Multi-Model Routing and Fallbacks

    The core idea of multi-model routing is to assign different tasks to models with different capabilities and costs, while automatically switching to an alternative model when the primary model is unavailable.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class ModelEndpoint:
    4. name: str
    5. max_context: int
    6. cost_per_1k_tokens: float
    7. healthy: bool = True
    8. def select_model(endpoints, required_context: int, budget_tier: str):
    9. candidates = [
    10. e for e in endpoints
    11. if e.healthy and e.max_context >= required_context
    12. ]
    13. if not candidates:
    14. raise RuntimeError("No available model meets the context requirement")
    15. if budget_tier == "low":
    16. return min(candidates, key=lambda e: e.cost_per_1k_tokens)
    17. return max(candidates, key=lambda e: e.max_context)

    The example above demonstrates only the selection logic. A production system should also include the following mechanisms:

    • Health checks: Periodically probe each endpoint, mark it unavailable after consecutive failures, and re-enable it after recovery;
    • Timeouts and retries: Set explicit timeouts and use exponential backoff for retryable errors;
    • Output validation: Validate tool-call parameters structurally, and switch models for a retry when the output is invalid;
    • Log redaction: Remove secrets and personal information from request content before writing it to storage.

    7. Evaluation: Benchmark Your Own Tasks

    General-purpose benchmarks measure broad model capabilities, while agent performance depends heavily on the specific business or engineering tasks involved. It is therefore useful to build an internal evaluation set.

    Recommended steps include:

    1. Collect 50 to 200 representative tasks from real workflows;
    2. Define automatically verifiable success criteria for each task, such as passing tests, producing the expected file contents, or returning the correct command execution result;
    3. Run the evaluation against candidate models and record success rate, latency, and cost;
    4. Use cost per successful task and the maximum user-acceptable latency as model-selection constraints.

    The evaluation set should be updated regularly as the business or workflow changes. Whenever a model version is updated, run the evaluation again to prevent behavioral changes from going unnoticed.