Low-Cost Inference in the Agent Era: Architecture Selection and Cost Optimization
Inference costs are becoming a core variable for agent-based applications. This article breaks down three characteristics of agent workloads—growing multi-turn context, sensitivity to time-to-first-token, and highly repetitive prefixes—and explains how to measure latency metrics (TTFT, output speed, total time), why Mixture-of-Experts architecture decouples total parameters from per-token compute, and how prefix caching and controlled loop counts can reduce costs. Sample code for latency measurement and top-k routing is included.
1. Background: Inference Cost Is Becoming a Core Variable for Agent Products
Over the past two years, large language models have improved rapidly, but agent-based applications have pushed call volumes to a new magnitude. A single code-fixing or file-organizing task often requires the model to loop through multiple steps: planning, calling tools, reading results, and planning again. Each step resubmits the full context, so token consumption grows with the number of steps.
Model providers are competing for developers through limited-time free quotas, tiered pricing, and caching discounts. For engineering teams, model selection cannot rely on leaderboard scores alone; latency, per-task cost, and service stability must all be evaluated. This article breaks these factors into measurable, computable metrics so teams can verify them independently.
2. Three Characteristics of Agent Workloads
Before discussing optimization, it is important to understand how agent workloads differ from ordinary Q&A.
2.1 Multi-Turn Loops with Continuously Growing Context
After each step, the agent appends tool outputs to the context. Suppose each step adds d tokens; after n steps, the input at step i is roughly the base prompt length plus i times d. Summing the inputs across all steps, the total grows approximately quadratically with the number of steps. This means doubling the step count can increase input cost by far more than double, so it is essential to control both the number of loop iterations and the rate of context growth per step.
2.2 Interactive Scenarios Are Sensitive to Time to First Token
When an agent runs in a terminal, editor, or chat window, users judge whether the system is working based on how quickly the first token appears. Excessive TTFT makes users suspect the program has stalled. In contrast, background batch jobs are barely sensitive to TTFT and care more about total duration and throughput. Scheduling strategies for these two scenario types should be designed separately.
2.3 Highly Repetitive Prefixes
The system prompt, tool definitions, project rules, and long-term memory remain essentially unchanged across calls; only the conversation history and user input vary. These repetitive prefixes are exactly where prefix caching can be effective. Later sections will discuss how to leverage this to reduce costs.
3. Latency Metrics: Separating TTFT from Generation Speed
When evaluating latency, it is recommended to track the following three metrics together.
- Time to First Token (TTFT): the time from sending a request to receiving the first output token. It is mainly determined by queuing time and input processing (prefill) time; the longer the input, the slower the prefill.
- Output speed: the number of tokens generated per second during the decoding phase, which determines the reading experience for long responses.
- Total duration: can be approximated as TTFT plus the number of output tokens divided by output speed.
The following code measures TTFT and overall duration for a streaming response. Note that it counts chunks rather than exact tokens.
import timedef measure_stream_latency(stream_iter):"""Measure TTFT and total duration of a streaming output. stream_iter is any iterator yielding text chunks."""start = time.perf_counter()first_token_at = Nonechunks = 0for chunk in stream_iter:if first_token_at is None and chunk:first_token_at = time.perf_counter()chunks += 1end = time.perf_counter()ttft = (first_token_at - start) if first_token_at is not None else Nonereturn {"ttft_s": ttft, "total_s": end - start, "chunks": chunks}
Tests should use prompt lengths matching real workloads, collect at least dozens of samples per group, and record both the median and the P95 percentile. Looking only at averages tends to hide long-tail latency, which is precisely the part users perceive most.
4. Mixture of Experts: Total Parameters Do Not Equal Per-Step Compute
Mixture of Experts (MoE) is a common architecture in current large models. The model contains multiple expert sub-networks, and for each incoming token, a router selects only a small number of experts to participate in computation.
This design leads to two direct conclusions.
First, the compute per token is determined by the activated parameters, not the model’s total parameter count. At the same total parameter scale, sparse activation generally reduces per-token compute, which benefits both TTFT and unit cost.
Second, all parameters must still reside in GPU memory or distributed memory. The serving side needs storage for every expert and must handle inter-expert communication. Routing can also cause load imbalance, with some experts called frequently while others sit idle for long periods. Therefore, deployment efficiency depends on the inference framework’s scheduling capability, not just the model architecture itself.
The example below shows the core logic of top-k routing. Real implementations also include load-balancing losses, expert capacity limits, and batch scheduling; only the most basic part is retained here.
```python
import math
def top_k_route(scores, k=2):
“””scores is a list of routing scores per expert. Returns the top-k experts by score with normalized weights.”””
ranked = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)[:k]
exps = [math.exp(scores[i]) for i in ranked]
total = sum(exps)
return [(i, e / total) for i, e in zip(ranked, exps)]
