AI Agent Cost Reduction: Multi-Model Routing for Production Deployment
This article is for backend and architecture engineers who need to put AI agents into production. It explains how to estimate inference costs, route requests across lightweight, balanced, and flagship models, calibrate routing thresholds with real logs, and manage the cost boundaries of no-quota billing so that cost reduction does not hide ownership or abuse problems.
This article is for backend and architecture engineers who need to put AI agents into production. The two main levers for cost reduction are sending simple requests to cheaper models and serving repeated requests from cache. The sections below cover cost sources, routing implementation, billing rules, cache hit rate, asynchronous queues, and pre-launch checks.
1. Understand Where Costs Come From
Large models bill by input and output tokens, so an agent’s inference cost can be estimated in two parts.
Single-call cost ≈ input token count × input unit price + output token count × output unit price
Monthly model cost ≈ monthly requests × (1 − cache hit rate) × single-call cost
This formula points to three optimization directions. First, reduce the number of tokens per call, for example by truncating overly long multi-turn conversation history. Second, choose a model with an appropriate unit price for each call. Third, increase the cache hit rate so that fewer requests miss the cache. The cache hit rate must be calculated from real logs, not assumed from experience.
In multi-turn conversations, historical context is often longer than the current question. If all history is sent to the model on every turn, input tokens grow linearly with the number of turns. A common approach is to keep only the most recent turns verbatim and compress earlier content into a summary.
2. Multi-Model Tiering and Routing
Not every task needs a flagship model with a large parameter count. Tasks such as casual chat and intent recognition do not need a high-end model; using one increases latency and wastes compute. Therefore, place a routing layer between business logic and the underlying models, and let it decide which model tier should handle each request.
Models are usually divided into three tiers:
| Tier | Typical tasks | Response latency | Cost per call | Escalation condition |
|---|---|---|---|---|
| Lightweight | Intent classification, slot extraction, simple chat | Low | Low | Low confidence, or output format validation fails |
| Balanced | Knowledge Q&A, text summarization, moderately complex code generation | Medium | Medium | Quality validation fails, or timeout |
| Flagship | Complex reasoning, deep analysis of long text, multi-step planning | High | High | After timeout, enter the asynchronous queue |
Below is a simplified implementation of the routing layer. Thresholds, model versions, and call permissions should be managed in a configuration center and must not be hard-coded. In the example, llm_client is a unified client wrapped by the team; the actual interface needs to be adjusted for the SDK in use.
import loggingimport timelogger = logging.getLogger("model_router")LITE, PRO, FLAGSHIP = "lite", "pro", "flagship"# Model names should be read from the configuration center; these are placeholders onlyMODEL_NAMES = {LITE: "lite-engine-v1", PRO: "pro-engine-v1", FLAGSHIP: "flagship-engine-v1"}# Escalation path after failure; no further escalation after the flagship modelESCALATION = {LITE: PRO, PRO: FLAGSHIP, FLAGSHIP: None}TIMEOUT_SECONDS = {LITE: 3, PRO: 8, FLAGSHIP: 30}MAX_RETRY_PER_TIER = 1# The thresholds below are starting points and need calibration with labeled samplesSIMPLE_MAX_INPUT_TOKENS = 30SIMPLE_MAX_CONTEXT_TOKENS = 50SIMPLE_MIN_INTENT_CONFIDENCE = 0.9COMPLEX_CONTEXT_TOKENS = 4000COMPLEX_INTENTS = {"code_generation", "multi_step_planning", "deep_analysis"}def is_simple_chat(query_tokens, context_tokens, intent_confidence):"""Treat as simple chat when input is short, context is short, and intent confidence is high."""return (query_tokens < SIMPLE_MAX_INPUT_TOKENSand context_tokens < SIMPLE_MAX_CONTEXT_TOKENSand intent_confidence >= SIMPLE_MIN_INTENT_CONFIDENCE)def is_complex_reasoning(intent, context_tokens):"""Treat as complex when the intent is code generation, planning, or deep analysis, or when context is long."""return intent in COMPLEX_INTENTS or context_tokens >= COMPLEX_CONTEXT_TOKENSclass ModelRouter:def __init__(self, llm_client):self.llm_client = llm_clientdef pick_tier(self, intent, intent_confidence, query_tokens, context_tokens):if is_simple_chat(query_tokens, context_tokens, intent_confidence):return LITE, "simple_chat"if is_complex_reasoning(intent, context_tokens):return FLAGSHIP, "complex_reasoning"return PRO, "default"def _call_with_retry(self, tier, query, reason):for attempt in range(MAX_RETRY_PER_TIER + 1):start = time.monotonic()try:reply = self.llm_client.chat(model=MODEL_NAMES[tier],prompt=query,timeout=TIMEOUT_SECONDS[tier],)logger.info("route ok tier=%s reason=%s attempt=%d latency=%.2fs",tier, reason, attempt, time.monotonic() - start)return replyexcept TimeoutError:logger.warning("timeout tier=%s attempt=%d", tier, attempt)except Exception:logger.exception("model error tier=%s attempt=%d", tier, attempt)return Nonedef handle(self, query, intent, intent_confidence, query_tokens, context_tokens):tier, reason = self.pick_tier(intent, intent_confidence,query_tokens, context_tokens)while tier is not None:reply = self._call_with_retry(tier, query, reason)if reply is not None:return replytier = ESCALATION[tier]reason = "fallback_escalation"logger.error("all tiers failed, request goes to async queue")return None
There are several points to note in this code.
First, responses from the lightweight model need format and content validation. If the output does not match the expected format, escalate to the balanced model and regenerate rather than returning it directly to the user.
Second, every routing decision should log the tier, decision reason, latency, and fallback failures. These logs are the basis for adjusting thresholds later. It is recommended to calculate the request share of each tier daily and compare it with manual sampling results to judge whether the thresholds are reasonable.
Third, routing thresholds can only be calibrated with samples. Before launch, prepare a batch of labeled real requests, calculate the misclassification rate of each tier, and then set the thresholds. Without data support, do not claim that a certain percentage of requests can be handled by the lightweight model.
Fourth, the routing strategy should be rolled out gradually. First let a small portion of traffic use the new router while comparing answer quality and total cost. After confirming that there is no obvious quality drop, gradually increase traffic.
3. Cost Boundaries of No-Quota Billing
Some platforms do not deduct user quota for simple conversations or low-consumption tasks, or they set a very low consumption multiplier. Commercially, this is a concession, but for engineering teams it changes who bears the cost, not whether the cost exists. Requests that do not deduct quota still incur inference costs, and someone must be responsible for that cost.
Before implementing this type of billing rule, answer three questions.
First, who bears this cost? It may come from a marketing budget, a platform subsidy, or allocation by business line. If the cost bearer is unclear, the rule will be difficult to sustain.
Second, what is the budget cap? Set a daily or monthly budget for no-quota tasks. When approaching the cap, automatically tighten the rules, for example by pausing no-quota billing or switching to a low-multiplier charge.
Third, how do you prevent abuse? No-quota rules are easy for scripts to exploit. Apply rate limits by account, device, and IP, and identify abnormal patterns.
The system can use the following conditions to determine whether a request is a low-consumption task:
- The input token count is very small, for example fewer than 30 tokens.
- The request hits the cache, and the cached answer is a fixed reply or content that can be reused directly.
- The expected output is very short, such as a confirmation, a rejection, or fixed-format field extraction.
These three conditions need to be met together, or at least combined in an explicit rule. Short input alone does not mean the answer requires no model computation.
