Selecting and Optimizing Mid-Tier Models for AI Agents: A Cost Control Guide
This article explains why mid-tier large language models often suit day-to-day AI agent tasks. It covers how costs add up across multi-turn tool calls, how to measure cost per successful task, how to build an internal evaluation set, how to route tasks by complexity, and how to reduce token usage. It also addresses prompt injection risks and the governance of automatic execution permissions.
1. Why Mid-Tier Models Have Become the Main Choice for Enterprises
After enterprises deploy AI agents, the main question is rarely whether a model can complete the task. The harder questions are how much each task costs, how long it takes, and whether the result can be reproduced consistently. Flagship models are highly capable but expensive per token. Agents often run multiple rounds of reasoning and tool calls, which multiplies that cost. Mid-tier models offer a compromise between capability and price. They handle most routine execution work, so they have become the default choice for many enterprises.
When selecting a model, avoid two extremes. One is chasing the strongest model regardless of cost. The other is looking only at unit price and ignoring task success rate. A better approach treats the model as a replaceable component and measures its performance on your own business tasks with a shared evaluation standard.
2. Breaking Down the Cost of an Agent
2.1 How to Calculate the Cost of a Single Task
Most pay-as-you-go model services charge separately for input tokens and output tokens. The cost of a single call can be expressed as:
Cost per call = input tokens × input price + output tokens × output price
Agent tasks usually involve multiple rounds. The model plans, calls a tool, reads the result, and reasons again. Each round resends the full conversation history to the model, so input tokens grow quickly with every round. Because each round carries all previous content, the total input tokens across ten calls often far exceed ten times the input of a single call.
2.2 Hidden Overhead from Tokenizer Differences
Different models use different tokenizers, so the same text can split into noticeably different numbers of tokens. If a newer tokenizer splits Chinese text, code, or special symbols into smaller pieces, token consumption for the same content rises even when the unit price stays the same. When you upgrade a model, compare the average token count per task on real samples, not just the unit prices.
2.3 Retries and Manual Review
Failed tasks also cost money. A retry caused by malformed output can double the cost of that task. The labor cost of manual review and error correction should also count toward total cost. The right metric for model economics is therefore the average cost per successful task, not the cost per call.
Average cost per successful task = total spending ÷ number of successfully completed tasks
3. Building an Internal Evaluation System
Public benchmark scores only show how a model performs on general tasks. Enterprises need to know how a model performs on their own tasks, so they should build an internal evaluation set.
3.1 Principles for Designing an Evaluation Set
- Cover real business scenarios: Sample representative requests from production logs. Include common cases, edge cases, and abnormal cases.
- Label criteria that can be checked automatically: Give each sample a clear acceptance condition, such as output that matches a JSON structure, passing test cases, or matching key fields.
- Separate tuning data from evaluation data: Samples used for prompt tuning should not also be used for final evaluation. Otherwise the results will look better than real performance.
- Control size and quality: Several hundred high-quality samples are usually more useful than thousands of rough ones.
3.2 Evaluation Dimensions
Table 1. Evaluation dimensions
| Dimension | How it is measured |
|---|---|
| Task success rate | Share of samples that pass automated checks |
| Hallucination rate | Share of statements in the output that conflict with facts or the context |
| Instruction following | Whether the output follows the required format, length, and steps |
| Safety | Share of injection samples the model resists |
| Unit cost | Average token usage and cost per successful task |
| Latency | Quantiles of time to first token and full response time |
3.3 Example Evaluation Script
The code below shows the basic structure of an evaluation framework. model_client is a unified wrapper for any model service. Replace it with the interface your team uses.
import jsonfrom dataclasses import dataclass@dataclassclass Case:prompt: strexpected_keys: list[str]def run_eval(model_client, cases: list[Case]) -> dict:success, total_in, total_out = 0, 0, 0for case in cases:resp = model_client.chat(case.prompt) # Returns the text and token usagetotal_in += resp.input_tokenstotal_out += resp.output_tokenstry:data = json.loads(resp.text)if all(k in data for k in case.expected_keys):success += 1except json.JSONDecodeError:pass # Count malformed output as a failuren = len(cases)return {"success_rate": success / n,"avg_input_tokens": total_in / n,"avg_output_tokens": total_out / n,}
The script returns the success rate and average token counts. You can plug these values into the cost per successful task formula above to compare models.
4. Model Tiering and Routing
Not every task needs the same model. You can sort tasks into three tiers by complexity:
- Simple tasks: Classification, information extraction, and format conversion. Use small or low-cost models.
- Standard tasks: Standard agent execution steps, code changes, and document generation. Use mid-tier models.
- Complex tasks: Multi-step planning, high-risk decisions, and difficult problems. Escalate to a stronger model or hand the task to a person.
Routing rules can be based on task type, input length, and the number of past failures. For example, if a task fails twice in a row on a mid-tier model, it can automatically escalate to a stronger model. This approach keeps average cost under control and protects success rates on hard tasks.
5. Engineering Methods to Reduce Token Usage
- Context trimming: Keep only the history relevant to the current step. Compress older tool results into summaries.
- Prefix caching: Enable caching for fixed system prompts and tool definitions to avoid paying for the same tokens repeatedly. The prefix must stay byte-for-byte identical. Any dynamic field, such as a timestamp, will invalidate the cache.
- Output constraints: Explicitly require an output structure and a length limit to avoid long explanatory text.
- Tool result truncation: Return only key excerpts from logs and web pages, and provide a way to fetch more on demand.
- Batch processing: Combine requests for offline tasks to reduce scheduling overhead.
Each optimization affects quality, so validate it on your evaluation set. Once the success rate shows no significant drop, merge the optimization into the production version.
6. Prompt Injection and Security Defenses
Agents read web pages, documents, emails, and other external content. That content may contain malicious instructions that trick the model into leaking information or performing unauthorized actions. This risk is called prompt injection.
Defenses should be layered:
- Separate data from instructions: State clearly in the prompt that external content is data, not instructions, and instruct the model not to execute any commands within it.
- Least privilege: Give the agent only the tools it needs for the task. Write, delete, and send operations require separate authorization.
- Parameter validation: Validate tool call parameters against an allowlist before execution, for example by restricting accessible paths and domains.
- Output filtering: Scan content that will go to users or external systems for sensitive information.
- Injection testing: Include typical injection samples in the evaluation set and track the resistance rate over time.
System prompts should also not contain secrets or internal addresses. Even if a model is told to keep something confidential, it cannot be guaranteed never to leak it. Inject sensitive information into the tool layer through environment variables or a key management service, not into the prompt.
7. Governing Automatic Execution Permissions
When an agent can modify code, run commands, or operate business systems directly, the permission policy defines the risk boundary. Manage permissions by operation risk level:
- Read-only operations: Can run automatically.
- Reversible local changes: Can run automatically in a sandbox or under version control, with a rollback point preserved.
- Irreversible or externally impactful operations: Require user confirmation.
If the default permission mode changes, notify users in advance and provide a fallback option. In team environments, manage permission settings through a shared policy file rather than relying on each member’s personal settings.
8. Launch and Operations
Roll out model changes gradually. Start with a small share of traffic or an internal team, compare success rate, cost, and user feedback, and expand only after confirming no significant regression.
After launch, monitor these metrics continuously:
- Success rate and the distribution of failure types
- Token usage and cost per task over time
- Latency quantiles
- User complaints and records of manual corrections
When metrics become abnormal, you should be able to roll back quickly to the previous model or prompt version. Record the model version, prompt version, and evaluation results together so you can trace the source of problems later.
9. Conclusion
The key to choosing a mid-tier model lies in building an evaluation system that can be verified.
