LLM Inference Cost Optimization for AI Agents
Learn how to manage inference costs in multi-step AI agent workflows through MoE architectures, KV cache optimization, prefix caching, token-based cost modeling, and off-peak scheduling. This article also covers multimodal inputs, model version routing, and retry strategies, with Python examples and an implementation checklist.
1. Why AI Agent Workflows Are Sensitive to Inference Costs
AI agent workflows differ from ordinary question answering in the number of model calls they require. To complete a task, an agent typically cycles through planning, tool calls, reading results, and replanning. Each round sends the conversation history and tool outputs back to the model. Over a dozen or more rounds, cumulative input tokens can far exceed the length of the final output.
The central cost question is therefore not just the price of an individual call. It involves three factors:
- How much input can be reused between rounds.
- How much GPU memory and compute each inference request consumes.
- When requests are submitted.
The following sections examine these factors and their implications for production systems.
2. Mixture of Experts: Total Parameters vs. Active Parameters
A Mixture of Experts (MoE) model consists of multiple expert subnetworks and a router. For each token, the router selects a small subset of experts to perform computation; the remaining experts stay inactive. This separates the model’s total parameter count from the amount of computation performed per token.
- Total parameters determine model capacity and weight file size, as well as the minimum GPU memory needed to load the weights.
- Active parameters determine the floating-point operations required for a token’s forward pass, directly affecting latency and throughput.
The ratio of active to total parameters is important when evaluating MoE costs. A lower ratio can provide a better balance between model capacity and computational cost. However, uneven routing loads and communication between experts can offset some of these gains. In practice, MoE deployment typically requires load-balancing losses and appropriate parallel partitioning.
Prefill and decode also have different computational characteristics. Prefill processes the input sequence at once and is compute-intensive. Decode generates output tokens one at a time and is more constrained by GPU memory bandwidth.
Designing input and output activation paths separately can help match resources to these different workloads. For users, input and output token prices may differ, so cost estimates should account for them separately.
3. KV Cache: Memory Bottlenecks and Compression Options
During decoding, a Transformer stores the keys and values for previous tokens at each layer. This storage is known as the KV cache.
Its size grows in proportion to sequence length and batch size. With long contexts and high concurrency, the KV cache can exhaust GPU memory even when the model weights fit comfortably.
A basic estimate is:
KV cache bytes = 2 × layers × KV heads × head dimension× sequence length × batch size × bytes per element
The factor of two accounts for storing both keys and values. The following example uses a hypothetical configuration for illustration:
def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, batch, dtype_bytes=2):"""Estimate KV cache size in bytes; dtype_bytes=2 represents FP16/BF16."""return 2 * layers * kv_heads * head_dim * seq_len * batch * dtype_bytes# Hypothetical configuration: 60 layers, 8 KV heads, head dimension 128,# 32K context, batch size 8, FP16size = kv_cache_bytes(layers=60, kv_heads=8, head_dim=128, seq_len=32768, batch=8)print(f"{size / 1024**3:.1f} GiB") # Approximately 60.0 GiB
The formula points to several common ways to reduce KV cache memory.
Reduce the Number of KV Heads
Multi-query attention (MQA) shares one set of keys and values across all query heads. Grouped-query attention (GQA) shares a set of keys and values within each group of query heads.
Reducing the number of KV heads from 64 to 8 reduces cache size to one-eighth of its original size. The trade-off is a possible loss of representational capacity, which should be validated through training or evaluation.
Reduce Precision per Element
Quantizing the KV cache from FP16 to FP8 or INT8 halves the bytes required per element. Quantization error should be checked through regression tests on long-context tasks.
Use Low-Rank Compression
High-dimensional keys and values can be projected into a lower-dimensional latent space for storage, then reconstructed when read or used directly in computation.
These methods require architectural support. They cannot be implemented simply by truncating cached representations at inference time.
Use Tiered Storage
Keep hot data in high-bandwidth GPU memory and move cold data to host memory or local SSD storage, swapping it according to access patterns.
Tiered storage adds access latency, making it better suited to offline or batch tasks that are less sensitive to time to first token.
For agent applications, these approaches should be selected according to the task’s access patterns. Recent conversation turns are often more relevant than much older tool outputs. Tiered storage and sliding-window strategies can offer benefits in such workloads, although actual gains depend on how the model accesses and retains context.
4. Prefix Caching: Avoid Recomputing Repeated Inputs
The beginning of an agent request is often unchanged between rounds. It may contain the system prompt, tool definitions, conversation history, and fixed retrieval material.
If the server recognizes an identical prefix, it can reuse the previously computed KV cache and perform prefill only for the newly added content.
The benefit depends on three factors:
- The proportion of each request occupied by the reusable prefix.
- How often the prefix is reused, reflected in the cache hit rate.
- Cache lifetime and eviction policy.
A cache hit requires the prefix to match exactly, token by token. Placing timestamps, random IDs, or changing formatting near the beginning of the system prompt can prevent reuse of the otherwise stable content.
Put stable content first and dynamic content later. Record cache hit rates in logs so that the impact of prompt changes can be measured directly.
Prefix caching also changes the billing structure. Cached and uncached input tokens may have different prices, so they should be calculated separately.
5. Token-Based Billing and Cost Estimation
For a token-billed service, the cost of one request can be expressed as:
Cost = (cached input tokens × cached input price+ uncached input tokens × uncached input price+ output tokens × output price) / 1,000,000
An agent task’s total cost is the sum of the costs across all rounds.
The following code compares costs at different cache hit ratios. The prices are placeholders and should be replaced with the provider’s published rates.
def request_cost(hit, miss, out, p_hit, p_miss, p_out):"""Return cost in the pricing currency; rates are per million tokens."""return (hit * p_hit + miss * p_miss + out * p_out) / 1_000_000def task_cost(rounds, prefix_tokens, new_tokens, out_tokens, hit_ratio, prices):total = 0.0for r in range(rounds):# Historical context grows each round.# Estimate cached tokens using the cache hit ratio.context = prefix_tokens + r * new_tokenshit = int(context * hit_ratio)miss = context - hit + new_tokenstotal += request_cost(hit, miss, out_tokens, *prices)return total# Placeholder rates: (cached input, uncached input, output).# Use the same currency units as the provider's pricing.prices = (0.5, 2.0, 8.0)for ratio in (0.0, 0.5, 0.9):print(ratio, round(task_cost(20, 4000, 800, 300, ratio, prices), 4))
This simulation illustrates how cache reuse affects long-running tasks. Increasing the hit ratio from zero to 0.9 can substantially reduce the cost, though the size of the reduction depends on the token distribution and relative prices.
For capacity planning, use observed cache hit rates and actual token distributions in this type of model before prioritizing architectural optimizations.
6. Native Multimodality and Visual Inputs
Multimodal models commonly handle images through two approaches.
The first uses a separate vision module: an independent vision encoder converts the image into features, which are then incorporated into the language model’s input. The second uses unified multimodal modeling, where images and text are trained and processed within an integrated model rather than requiring a separate encoder service call.
The trade-offs include:
- Separate vision module: Clear component boundaries allow the vision module to be upgraded independently. However, an additional cross-module call increases deployment and version-alignment complexity.
- Unified multimodal model: Fewer pipeline stages can reduce latency and operational overhead. Training data and training processes are more demanding, and upgrades typically require retraining or fine-tuning the integrated model.
In agent workflows, images often appear as tool outputs, including screenshots, forms, and charts. If every round requires a separate vision-module call, the additional latency accumulates across the task.
Evaluate the proportion of image inputs, image resolution, and call frequency together when selecting an approach.
7. Off-Peak Scheduling: Move Non-Real-Time Work to Lower-Cost Windows
Some services offer time-based pricing, with different rates during peak and off-peak periods. This uses price signals to shift demand.
Applications can take advantage of it in two ways.
- Classify tasks by latency requirements. User-facing interactions need immediate responses and should proceed during peak periods when necessary. Bulk summarization, data labeling, and offline evaluation are less time-sensitive and can be queued for off-peak execution.
- Increase the share of batch processing. Combining scattered requests into batches can reduce per-request overhead and make it easier to execute work within lower-cost windows.
The following example determines whether a task should run immediately based on its type and the current time:
from datetime import datetimedef should_run_now(task_type, now: datetime, peak_hours=range(9, 22)):if task_type == "realtime":return True# Run non-real-time tasks only during off-peak hours.return now.hour not in peak_hoursqueue = [("realtime", "User Q&A"), ("batch", "Offline summarization")]now = datetime.now()for task_type, name in queue:action = "Run now" if should_run_now(task_type, now) else "Queue"print(name, action)
Two additional constraints matter.
First, waiting for an off-peak window must not exceed the business’s acceptable delay. Set a maximum wait time where necessary and execute the task once that limit is reached.
Second, account for the cost of rerunning failed batch jobs. Use idempotent processing to avoid unnecessary duplicate work, charges, or result writes.
8. Model Version Migration and Service Routing
Model versions change regularly. A stable service should decouple the model name used by application code from the concrete version, allowing controlled changes through configuration.
Common practices include:
- Alias mapping: Application code references a logical model name, while configuration determines the concrete version.
- Canary rollout: Send a small share of traffic to the new version, compare quality, latency, and error rates, then expand gradually.
- Rollback: Maintain the ability to switch back to the previous version or a backup model within minutes.
- Transition-period routing: After an old model name is retired, temporarily route requests to a replacement version and log those routing decisions to assess their impact.
The following code shows a basic alias-based routing structure with fallback:
ROUTE_TABLE = {"primary-large": ["model-v2", "model-v1"], # Candidates in priority order}def route(logical_name, call_model):last_error = Nonefor model in ROUTE_TABLE.get(logical_name, []):try:return call_model(model)except Exception as e: # Distinguish retryable errors in production.last_error = eraise RuntimeError(f"All candidate versions are unavailable: {last_error}")
9. Reliability: Retries and Backoff
Network instability, rate limiting, and short service interruptions are difficult to avoid at scale.
Fixed-interval retries can cause many clients to hit the server simultaneously during recovery, creating another surge of load. Exponential backoff with random jitter is a more robust approach.
import randomimport timeclass TransientError(Exception):"""A retryable temporary error, such as a timeout or rate limit."""def call_with_retry(fn, max_retries=5, base=0.5, cap=20.0):for attempt in range(max_retries):try:return fn()except TransientError:if attempt == max_retries - 1:raisedelay = min(cap, base * (2 ** attempt))# Add jitter to prevent clients from retrying simultaneously.time.sleep(delay * (0.5 + random.random() / 2))
Complement retries with the following measures:
- Set a timeout for each request to prevent connections from remaining occupied indefinitely.
- Read and prioritize server-provided wait instructions in rate-limit responses.
- Configure a client-side circuit breaker that pauses requests after a threshold of consecutive failures.
- Use idempotency keys for write operations so that retries do not create duplicate side effects.
10. Implementation Checklist
Before applying these techniques to a production service, work through the following checklist:
- Measure input and output token distributions for each task type, along with the average number of rounds in multi-step tasks.
- Estimate KV cache usage at peak concurrency and verify that GPU memory headroom is sufficient.
- Put stable prompt content first and monitor prefix cache hit rates.
- Create an off-peak execution queue for offline tasks, with maximum wait times and idempotent processing.
- Manage model versions through aliases and validate new versions with canary traffic before full rollout.
- Configure timeouts, exponential backoff, circuit breakers, and logging for all external calls.
- Review cost trends monthly, tracking cache hit rate, average round count, and cost per task as core metrics.
Inference cost optimization is an ongoing process. As workloads grow and model versions change, the same strategies need to be recalibrated. Turning cost models, monitoring metrics, and scheduling rules into maintained code and configuration helps teams keep agent inference costs under control across successive releases.
