Agent Inference Cost Control: Low-Cost Model Selection in Practice

    This article explains why Agent applications are especially sensitive to inference costs and how to break down and estimate those costs. It covers four practical cost-reduction approaches—tiered routing by task difficulty, context-size control, on-demand multimodal processing, and caching/reuse—and shows how to use cost per successful task for model selection. It also discusses engineering governance for cost visibility and control, plus common pitfalls.

    1. Why Agent Applications Are Especially Sensitive to Inference Costs

    The difference between an Agent and single-turn Q&A is that an Agent calls models continuously around a goal: it first plans steps, then calls tools, reads results, revises judgments, and moves to the next round. A single user request may trigger dozens of model calls, and each call carries a growing context. Cost accumulates with the number of steps and context length, far exceeding the linear growth of a single Q&A interaction.

    This creates three direct problems for developers. First, the cost of a single task is hard to estimate; for the same type of requirement, different inputs may lead to very different numbers of calls. Second, cost grows with user scale, and free or low-priced features can become a burden after scaling. Third, cost optimization and quality assurance constrain each other; switching to a smaller model may reduce task success rates, so a method is needed to quantify this trade-off.

    2. Breaking Down Inference Costs

    Inference cost can usually be broken down into the following items:

    • Number of calls: Planning, tool selection, result summarization, and other steps each call the model once. The more steps, the more calls. Retries after failures also count.
    • Input length: System prompts, historical conversations, and tool return results are all inputs. In Agent scenarios, input is usually much larger than output, and the input portion is often the main source of cost.
    • Output length: The number of tokens in reasoning processes and structured outputs differs significantly; verbose explanations directly increase cost.
    • Input modality: Image, audio, video, and other multimodal inputs are converted to tokens differently from text. The higher the resolution or number of sampled frames, the greater the consumption.

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

    Cost per task ≈ Σ (input tokens of the i-th call × input unit price + output tokens of the i-th call × output unit price)

    Assume a task makes 5 model calls in total, each with 4,000 input tokens and 600 output tokens, the input price is CNY 0.002 per thousand tokens, and the output price is CNY 0.008 per thousand tokens. The cost per task is approximately 5 × (4 × 0.002 + 0.6 × 0.008) = CNY 0.064. The numbers above are only for demonstrating the calculation method and do not represent any actual price.

    The corresponding estimation function is as follows:

    1. def estimate_task_cost(calls, in_price, out_price):
    2. """
    3. calls: list, each element is (input token count, output token count)
    4. in_price / out_price: price per thousand tokens
    5. """
    6. total = 0.0
    7. for in_tok, out_tok in calls:
    8. total += in_tok / 1000 * in_price + out_tok / 1000 * out_price
    9. return total

    3. Four Ways to Reduce Costs

    3.1 Route by Task Difficulty

    Not every step needs the largest model. Steps with strong determinism, such as intent classification, field extraction, and format conversion, can be handled by smaller models; complex planning and final result validation can remain with larger models. Routing rules can be written as configuration, making them easy to adjust and test:

    1. ROUTE_RULES = {
    2. "classify": "small",
    3. "extract": "small",
    4. "plan": "large",
    5. "final_check": "large",
    6. }
    7. def choose_model(step_type: str) -> str:
    8. # Step types not configured default to the large model to ensure a quality floor
    9. return ROUTE_RULES.get(step_type, "large")

    Routing rules must be validated against an evaluation set. Before launch, confirm whether the accuracy of the smaller model on each type of step meets requirements, and record changes in task success rate before and after degradation.

    3.2 Control Context Size

    Context bloat is a common cause of runaway Agent costs. It can be governed from three aspects:

    • Keep only historical messages relevant to the current step; compress earlier conversations into summaries.
    • Trim fields from tool return results first, keeping only the fields the model actually needs.
    • Modularize system prompts and inject them on demand for the current task, avoiding carrying all instructions on every call.
    1. def build_context(history, summary="", max_turns=6):
    2. recent = history[-max_turns:]
    3. messages = []
    4. if summary:
    5. messages.append({"role": "system", "content": f"History summary: {summary}"})
    6. messages.extend(recent)
    7. return messages

    3.3 Process Multimodal Input on Demand

    The cost elasticity of multimodal input is high, and processing should follow the principle of minimum necessity:

    • Determine whether the task really needs high resolution. If only large titles need to be recognized, reducing the image size can significantly reduce consumption.
    • Sample videos by key frames rather than sending every frame to the model. The sampling interval should be determined by how quickly the scene changes.
    • For text that can be obtained through text recognition or structured parsing, extract it as text input first to reduce image token usage.

    3.4 Cache and Reuse Results

    The inputs of many steps are deterministic, such as the summary of the same document or a tool call with the same set of parameters. Caching results for these steps can directly avoid repeated calls. The cache key should include the model name, prompt, and parameters to prevent different configurations from contaminating each other:

    1. import hashlib
    2. import json
    3. def cache_key(model_name: str, prompt: str, params: dict) -> str:
    4. raw = json.dumps(
    5. {"model": model_name, "prompt": prompt, "params": params},
    6. sort_keys=True,
    7. ensure_ascii=False,
    8. )
    9. return hashlib.sha256(raw.encode("utf-8")).hexdigest()

    Tool call results should have an expiration time to avoid using stale data. For queries with similar semantics but different wording, vector similarity can be used to decide whether to reuse historical results. The similarity threshold must be determined through evaluation and cannot be set directly based on experience.

    4. Use Cost per Successful Task for Model Selection Decisions

    When comparing models, looking only at unit price can easily lead to wrong conclusions. If a lower-priced model has a higher failure rate and requires more retries and manual correction, the final total cost may be higher. A more reasonable metric is cost per successful task:

    Cost per successful task = total cost ÷ number of successful tasks

    The selection process can follow these steps:

    1. Collect representative tasks covering common paths and edge cases to form a fixed evaluation set.
    2. Define quantifiable success criteria, such as structured output passing validation, tool call parameters being correct, and the final answer being judged acceptable by humans.
    3. Run the same evaluation set for each candidate model or model combination, recording success rate, average number of calls, and average token consumption.
    4. Calculate the cost per successful task for each option.
    5. On the premise that the success rate meets the business bottom line, choose the option with the lowest cost per successful task.
    1. def cost_per_success(results: list[dict]) -> float:
    2. """Each element in results contains cost (float) and success (bool) fields"""
    3. total_cost = sum(r["cost"] for r in results)
    4. successes = sum(1 for r in results if r["success"])
    5. if successes == 0:
    6. return float("inf")
    7. return total_cost / successes

    5. Engineering Governance: Make Costs Visible and Controllable

    Cost optimization needs supporting engineering mechanisms; otherwise, it is difficult to sustain:

    • Metering: Record token usage and call counts by task type, user, and model, and write them to a logging service for dimensional analysis.
    • Budgeting: Set step limits and token limits for individual tasks; when exceeded, degrade processing or terminate early to avoid abnormal loops exhausting resources.
    • Alerting: When the average number of calls or cost per successful task exceeds the baseline, notify the owner through monitoring alerts so that prompt changes, tool anomalies, and other causes can be investigated promptly.
    1. class TaskBudget:
    2. def __init__(self, max_calls: int = 20, max_tokens: int = 50000):
    3. self.max_calls = max_calls
    4. self.max_tokens = max_tokens
    5. self.calls = 0
    6. self.tokens = 0
    7. def check(self, tokens_used: int) -> bool:
    8. """Call after each model invocation; returns False if the budget is exceeded"""
    9. self.calls += 1
    10. self.tokens += tokens_used
    11. return self.calls <= self.max_calls and self.tokens <= self.max_tokens

    6. Common Pitfalls

    • Looking only at unit price: Ignoring the number of calls and retries often distorts conclusions.
    • One-size-fits-all downgrading: Replacing all steps with smaller models can make repair costs after failures offset the savings.
    • Ignoring context bloat: The longer an Agent runs, the longer the input becomes, and the cost of later steps is usually much higher than that of earlier steps.
    • Lacking regression testing: If the evaluation set is not run after model or prompt changes, quality degradation can only be discovered by users in production.

    7. Summary

    Whether Agent applications can scale largely depends on whether inference costs can be estimated and reduced. A practical sequence is to first quantify cost composition, then implement tiered routing and context governance, and then evaluate model selection using cost per successful task.