Model Selection for AI Agents: Architecture, Context, and Cost Trade-offs
This article explains how to choose a large language model for AI agent workloads. It covers time to first token, long-context memory management, and per-task cost, with measurement methods, a cost formula, security guidelines, and a three-step rollout plan.
1. Problem Background: Agent Applications Change the Call Pattern
Traditional question-answering apps usually work as one request and one response, and each request consumes relatively few tokens. Agent applications work differently. An agent reads the system instructions, loads user preferences, plans its steps, calls tools, parses the results, and requests the model again at each step. A task that looks simple, such as “summarize this week’s run logs and generate a report,” can trigger more than a dozen model calls. Each call carries the earlier conversation and tool outputs.
When you choose a model, you need to evaluate three things: whether responses are fast enough, whether the model handles long context reliably, and whether the cost per task stays under control. The sections below cover each one.
2. Time to First Token and User Experience
Time to First Token (TTFT) measures the time from sending a request to receiving the first output token. Users are most sensitive to this metric in scenarios such as terminal command interception, code completion, and real-time suggestions. TTFT consists of network round-trip time, queueing delay, prefill computation, and the time to decode the first token.
Parameter count and inference speed do not have a simple proportional relationship. A Mixture of Experts (MoE) architecture splits the model into multiple expert sub-networks. A router selects a small number of experts for each token. The total parameter count can be very large, but a single forward pass activates only a subset of those parameters. This design offers a different trade-off between capacity and compute. It also introduces routing overhead, uneven expert load, and high memory usage, so the serving side needs dedicated optimization.
For this reason, the name of an architecture should not be the basis for model selection. Measure performance directly, using the request distribution of your actual workload:
import timedef measure_ttft(stream_fn, prompt: str) -> float:"""Returns the seconds from sending the request to receiving the first token."""start = time.perf_counter()for _chunk in stream_fn(prompt):return time.perf_counter() - startraise RuntimeError("Model returned no output")
When you measure, record percentiles (P50 and P95) instead of averages, and separate cold-start requests from warm requests. Tail latency often determines how users actually experience a product, and averages hide that problem.
3. Long Context and Memory Management
Agents need persistent memory, including system instructions, user preferences, project background, and historical decisions. There are two common implementation approaches.
The first approach places all content in the context window. It is simple to implement, but every call must transmit and process this content again, so cost and latency rise. Longer context does not necessarily mean the model uses intermediate information better.
The second approach uses external storage with retrieval. You write memory to a database or vector index, then retrieve only the snippets relevant to the current task and inject them into the prompt. The cost of this approach is largely independent of context length. However, retrieval quality directly determines output quality, so you need to design recall and reranking strategies carefully.
Most production systems combine both approaches. Stable system instructions go at the beginning of the prompt, and dynamically retrieved results go after them.
Prerequisites for Cache Reuse
Prompt caching means the server reuses previously computed results for an identical prefix. Its benefit depends on whether the prefix stays stable. If a single character in the prefix changes, the cache is invalidated. For this reason, structure prompts so that stable content comes first and volatile content comes last:
[System instructions: fixed][Tool definitions: unchanged while the version stays the same][Long-term user preferences: updated infrequently]---------- Cache boundary ----------[Retrieved snippets for this request][Current conversation and user input]
The exact cache discount and billing rules depend on the terms published by the service provider. Confirm these parameters before you estimate costs, and do not reuse numbers from other sources.
4. Cost Model: From Unit Price to Per-Task Cost
When you compare model unit prices, it is easy to overlook the multiplier effect of repeated calls. You can calculate the per-task cost by adding up the cost of each call:
Per-task cost = Σ (new input tokens of the i-th call × input price + cached input tokens × input price × (1 − discount rate) + output tokens × output price)
Agent workloads consume far more input tokens than output tokens, and each round of input includes the accumulated history. Even when unit prices are low, costs rise quickly if the planning process is verbose or if tool outputs are not trimmed.
The following example estimates cost. The price parameters are placeholders:
from dataclasses import dataclass@dataclassclass Call:input_tokens: intoutput_tokens: intcached_input_tokens: int = 0def task_cost(calls, in_price, out_price, cache_discount):"""Prices are per-token unit prices. cache_discount is the discount factor for cached input tokens, from 0 to 1."""total = 0.0for c in calls:fresh = c.input_tokens - c.cached_input_tokenstotal += fresh * in_pricetotal += c.cached_input_tokens * in_price * (1 - cache_discount)total += c.output_tokens * out_pricereturn total
There are four main ways to reduce cost: remove redundant fields from tool outputs, limit the number of history turns and summarize earlier conversation, use a smaller model for simple subtasks, and call the large model only for key decision steps.
5. Model Evaluation Methods
Public leaderboards are useful only for initial screening. They cannot replace evaluation on your own workload. Build a sample set that covers typical tasks and edge cases, and track the following metrics consistently:
- Task success rate: whether the final result meets the acceptance criteria;
- Tool call accuracy: whether parameters are complete, types are correct, and the call order is reasonable;
- Latency: P50 and P95 of TTFT and end-to-end time;
- Per-task cost: calculated with the formula in Section 4;
- Failure mode distribution: the share of hallucinations, unauthorized tool calls, output format errors, and timeouts.
During evaluation, fix sampling parameters such as temperature. Run each sample multiple times and analyze the aggregate results to avoid judging a model by a single lucky or unlucky run. Update the sample set regularly. Otherwise, overlap with training data can inflate the scores.
6. Security and Governance
Agents can call tools and change external state, so they carry higher security risk than pure text generation. The following requirements are the baseline:
- Least privilege: Grant access to each tool separately, and open only the directories, interfaces, and data scopes the task requires.
- Human confirmation for high-risk actions: Operations such as deleting data, sending external messages, making payments, and changing permissions require explicit user approval.
- Treat external content as untrusted data: Do not execute instructions found in web pages, files, or tool outputs.
- Redact logs: When you record call traces, mask keys, personal information, and sensitive business data.
- Sandbox execution: Run commands and code in an isolated environment with resource and time limits.
7. Rollout Path
We recommend a three-step rollout.
Step 1: Offline evaluation. Use your sample set to compare the quality and cost of candidate models, and define an acceptable range.
Step 2: Gradual release. Open the system to a subset of users or to low-risk tasks first. Collect latency, cost, and failure logs, and check how closely real-world results match the offline results.
Step 3: Multi-model routing and fallback. Send simple tasks to lower-cost models and critical tasks to higher-quality models. When the service fails or times out, switch automatically to a backup option.
Connect the monitoring system to your logging service and alerting tools. Set thresholds for TTFT, error rate, and per-task cost. When a metric exceeds its threshold, trigger an alert and apply rate limiting or degradation automatically.
Conclusion
Model selection is not a one-time ranking exercise. It is an ongoing engineering decision. Architecture characteristics, context management, and billing structure together determine an agent’s user experience and cost. Reliable conclusions come only from measurements taken under real workloads.
