Agent Engineering Practices for Near-Zero-Cost Inference
Agent development has shifted from choosing the smartest model to designing cost structure itself. This article argues that sustainable cost reduction comes not from cheaper unit prices but from reengineering the cost model. It explains why agent requests differ fundamentally from chat requests (high input/output ratios, large fixed prefixes, automatic retries), breaks total cost into five optimizable components, and shows how sparse-activation (MoE) architectures, context caching, context tiering, and layered model routing each cut both cost and latency. It also covers portability through abstraction layers to avoid vendor lock-in, and closes with a four-step rollout: measure, eliminate waste, restructure, and establish the norm. Readers will gain a concrete engineering framework for keeping agent workloads economical as inference prices keep falling.
1. The Shift Has Already Happened: From “Saving Tokens” to “Designing Cost Structure”
Over the past two years, the focus of agent application development has clearly migrated. Early discussions centered on “which model is smarter,” then shifted to “which provider’s tokens are cheaper,” and now what truly determines whether a project can run sustainably is the cost structure itself—specifically, how many model calls happen behind each user request, how much context each call carries in, and how much of that context is a reusable fixed prefix.
The external pressure behind this shift is clear: inference prices sit in a sustained downward trend, while some open-source agent frameworks have begun issuing large initial free-call allowances in partnership with model providers. These initiatives are essentially not marketing campaigns but ecosystem positioning—trading compute for developer habits, and cementing default configurations, tool-calling paradigms, and prompt templates into their own technology stacks. For developers, this creates an easily overlooked trap: capacity planning based on subsidy-period data will almost certainly break once the subsidy ends.
So the core argument of this article is: don’t pin cost reduction on unit price; instead, treat cost as a variable that can be restructured through engineering.
2. Understand the Load First: Agent Requests Are Not Chat Requests
Many teams estimate agent costs using their experience with conversational products, and end up off by one to two orders of magnitude. The reason lies in the shape of the load:
| Dimension | Typical chat scenario | Typical agent scenario |
|---|---|---|
| Turns per session | 3–8 turns | Dozens of turns, including tool-call loops |
| Input/output ratio | About 1:1 to 3:1 | Often 20:1 or higher |
| Fixed-prefix proportion | Low | High (system instructions, tool schemas, project context) |
| Failure retries | User manually re-asks | Framework auto-retries, falls back, explores in parallel |
| Latency sensitivity | A fast first token is enough | Every step must feel “like local software” |
Among these, the high input/output ratio is the most critical. Every tool call in an agent must resubmit the full history + full tool descriptions + the current observation, while the output is often just a short piece of decision text or a set of function-call arguments. This means the bulk of the bill is on the input side—and the input side is exactly the part that caching can cover.
3. Break the Bill Down into Optimizable Items
Don’t look only at “price per million tokens.” An actionable cost model should include at least five items:
Total cost ≈ Σ_over_steps ( input_tokens × input_price+ output_tokens × output_price )+ retry_overhead (failed_steps × per_step_cost)+ context_bloat (linear growth from uncompressed history)- cache_discount (hit_prefix_tokens × discount_rate)+ hidden_costs (timeout retries from queueing, manual fallback)
Each line corresponds to a concrete set of tactics:
- Retry overhead: structured-output parsing failures, invalid tool arguments, and timeouts all trigger a full replay of the round. Constraining output format (strict schema, restricted enums) is far cheaper than raising the temperature to “get lucky.”
- Context bloat: in multi-round loops, if you don’t summarize, input length grows roughly linearly with the number of steps, and total cost trends toward quadratic. Staged compression is mandatory.
- Cache discount: this is the highest-leverage item, covered in the next section.
- Hidden costs: high latency induces client-side timeout retries, forming a “the slower it is, the more expensive it gets” positive feedback loop.
4. Why Sparse-Activation Architecture Fits Agent Scenarios Naturally
In recent years, mainstream large models have mostly adopted the Mixture of Experts (MoE) structure: the model has a very large total parameter count, but each forward pass activates only a subset of the expert networks. The difference from traditional dense models lies in decoupling parameter capacity from per-step computation—total parameters determine knowledge capacity, while activated parameters determine the computational cost of a single inference.
For agent scenarios, this characteristic yields two direct benefits:
- Time to first token (TTFT) is easier to keep low. TTFT is mainly determined by the compute volume and queuing of the prefill stage. Smaller activated parameters mean lower per-token matrix operations, making it easier to achieve near-local-tool responsiveness under the same hardware. Since every agent step must wait for the model to return a decision before executing a tool, TTFT gets amplified by the number of steps, so it affects perceived experience more than “overall throughput.”
- Room for capacity-cost mismatch. Without sacrificing breadth of knowledge, you can choose different activation-scale variants for different task tiers (if the provider offers multiple specifications), pushing simple judgments down to a lighter tier.
Two common misconceptions are worth noting. First, smaller activated parameters do not mean lower GPU memory usage: the weights must still fully reside in memory or be efficiently swapped in, so concurrency capability depends more on the provider’s batching and scheduling than on the raw activation size. Second, low TTFT does not mean fast end-to-end: agent per-step time = queueing + prefill + decode + tool execution. The network round trip of the tool itself is often the larger component, so switching tool calls to batched parallel execution, or merging multiple read-only queries, often yields more than switching models.
For evaluation, fix on four metrics for comparison rather than a single composite score:
- TTFT (P50 / P95): determines how “responsive” it feels;
- TPOT (time per output token): determines whether long-text generation is smooth;
- Per-task success rate: determines the retry-overhead multiplier;
- Cost per successful task = total cost / number of successful tasks. This is the metric that should be used for external reporting.
5. Context Caching: A Severely Undervalued Cost Lever
Most inference services implement prompt caching on the same principle: for the byte-for-byte identical common prefix in a request, reuse its attention intermediate state (KV Cache) and skip recomputation. After a hit, that portion of the input is billed at a significant discount, and prefill time drops substantially—cost reduction and latency reduction happen simultaneously.
Its conditions are very strict, and understanding these conditions matters more than knowing the feature exists:
- The prefix must be a stable common prefix. System instructions, tool definitions, few-shot examples, and code repository digests should be placed at the very front of the message array, and their order should not change over the session lifecycle.
- Any byte-level change invalidates everything after it. Common culprits: inserting the current timestamp, a random request ID, a real-time user profile, or an unsorted tool list into the system prompt. These changes turn a few thousand cacheable tokens into full-price tokens.
- Dynamic content must come last. User input, tool return values, and retrieval snippets should all go after the stable prefix.
- Prefix continuity must be maintained across turns. If you reassemble the message array every turn, or route between different nodes causing prefix discontinuity, the hit rate will drop to near zero.
A cache-friendly message organization example:
# Stable prefix: unchanged throughout the session, reusable across requestsSYSTEM_PREFIX = build_system_prompt(tools=SORTED_TOOL_SCHEMAS, # tool list must be sorted before serializationrepo_digest=REPO_DIGEST, # repo/knowledge-base digest, updated periodically, not in real timepolicy=OUTPUT_POLICY, # output format constraints, fixed text)def build_request(user_input: str, observations: list[str]) -> list[dict]:return [{"role": "system", "content": SYSTEM_PREFIX},# conversation history: append only, no reordering, no rewriting*history_messages(),{"role": "user", "content": user_input},# volatile content always goes last{"role": "user", "content": format_observations(observations)},]
A reverse self-check: serialize the SYSTEM_PREFIX above twice and compare hashes; if the hash changes within a single session, you’re paying for cache misses. Also, log the cached_tokens / prompt_tokens ratio of each request at the gateway, and treat it as a core SLI to monitor.
6. Context Budget: A Long Window Is Not a Free Window
Large context windows (hundreds of thousands of tokens) solve the problem of “fitting it in,” not “whether it’s worth it” or “whether it’s seen accurately.” Engineering must manage three things at once:
Context tiering. Classify information into three layers by access frequency: a resident layer (system instructions + tool schemas + core constraints, cache-hit), a working layer (current-task retrieval snippets, relevant files, recent observations), and an archive layer (historical trajectories, compressed and stored to object storage, retrieved back on demand). Only the working layer participates in each request; the resident layer handles reuse.
Proactive compression. When the number of loop steps exceeds a threshold, hand early trajectories to the model for a structured summary, keeping three categories of information—“decisions, ruled-out options, hypotheses to verify”—and discarding raw tool output. In practice, use rules first (discard the body of oversized tool returns, keep only paths and summaries), and limit summary-model calls to low-frequency events.
Retrieval instead of full inclusion. “Stuff the entire codebase into context” is the most easily abused and most easily runaway approach. Switch to retrieval-based supply: targeted recall by symbol, file dependency, and call chain, combined with reranking to control the number of snippets. This usually reduces single-step input by an order of magnitude, and because noise is reduced, task success rate actually rises.
7. Layered Routing: Let Cheap Models Handle Most of the Traffic
The real distribution of agent tasks is long-tailed: format conversion, field extraction, intent classification, and simple rewriting account for the vast majority of calls, while complex planning that requires multi-step reasoning is only a minority. Using one large model for all traffic is the main source of cost waste.
def route(task: Task) -> Model:# Tier 1: rules and lightweight models handle deterministic workif task.type in {"classify", "extract", "format"}:return Model.LIGHTif task.estimated_steps <= 2 and task.risk == "low":return Model.MID# Tier 2: escalate high-risk, long-chain, deep-reasoning tasksif task.risk in {"write_ops", "external_call"} or task.needs_deep_reasoning:return Model.STRONGreturn Model.MID
Routing needs three supporting pieces before it can go to production:
- Escalation path. When a lightweight model has low confidence (structured-output parsing fails, confidence score below threshold, schema validation fails), escalate automatically, so you avoid sacrificing success rate to save money.
- Offline evaluation set. Maintain a labeled golden set for each tier; routing-rule changes must run regression and look at “cost per successful task” rather than just the average call price.
- Shadow traffic. Run new rules in a bypass mode that records decisions without taking effect, compare the dispatch differences and estimated costs between old and new routing, and switch traffic only after confirming nothing is wrong.
8. Portability: Abstraction Layers and Vendor Lock-in Risk
The free allowances of the subsidy period will eventually end, and rate limits, concurrency quotas, context-length caps, and cache-discount policies may all change at any time. Hard-coding business logic directly onto the calling shape of a specific service makes migration so costly that no one dares to switch.
Recommend consolidating at the gateway layer and isolating differences inside adapters:
class LLMBackend(Protocol):def chat(self, messages: list[dict], *, max_tokens: int,tools: list[dict] | None = None) -> ChatResult: ...def stats(self) -> Usage: ... # unified token / cache / latency metrics@dataclassclass Usage:prompt_tokens: intcached_tokens: intcompletion_tokens: intttft_ms: float
Pair this with a few governance rules: keep model identifiers, endpoint addresses, and credentials in a config center and environment variables, never in the code repository; bring key prompts and tool schemas under version control and make them replayable; wire the four metrics—“cost per successful task,” “cache hit rate,” “TTFT P95,” and “task success rate”—into monitoring and alerting, with anomaly thresholds configured.
Data compliance also needs to be solved at the design stage: clarify which data may leave the domain and which must be preprocessed and desensitized locally; for long contexts containing sensitive information, prefer using a small model deployed locally or privately for cleaning and extraction, then submit to the remote model for processing.
For scenarios that need elasticity and supporting capabilities, general cloud platforms typically already offer infrastructure that can be directly composed: use a container platform to host gateways and tool-execution sandboxes for concurrency elasticity, object storage to archive trajectories and evaluation sets, message queues to smooth peaks and handle asynchronous tool tasks, and logging services with monitoring and alerting for cost and latency attribution. Taking Baidu AI Cloud as an example, such general-purpose capabilities can be combined on demand, but the architecture should still keep the abstraction to avoid any single dependency becoming a migration blocker.
9. Implementation Roadmap: Four Steps
Step 1: Measure first. Add instrumentation across the existing pipeline to produce a baseline: average calls per task, input/output ratio, cache hit rate, time breakdown per step, and cost per successful task. Without a baseline, none of the subsequent optimizations can be attributed.
Step 2: Eliminate waste. This step is usually zero-risk with the highest payoff: fix timestamps and random values in the system prompt, sort the tool list, move volatile content to the end, add length truncation to tool return values, and add strict schemas to outputs. Most teams see a significant drop in input-side cost and a latency improvement at this step.
Step 3: Restructure. Introduce context tiering and retrieval-based supply, compress and store historical trajectories; implement layered routing and automatic escalation; parallelize read-only tool calls.
Step 4: Establish the norm. Fold cost metrics into the iteration cadence, running golden-set regression on every prompt or tool change; validate routing strategies with shadow traffic; periodically redo model-specification selection comparisons, because both prices and capabilities keep changing.
10. Conclusion
The decline in inference prices is an irreversible trend, and free allowances are a phased phenomenon within that trend. Building project viability on subsidies is fragile; pinning cost optimization on waiting for cheaper unit prices is passive. The truly robust approach is to treat agent cost as part of system design: stable prefixes to capture cache dividends, tiered context to suppress bloat, layered routing to match the load distribution, and an abstraction layer to preserve migration freedom.
Once these structural optimizations are in place, every drop in model unit price becomes direct profit margin, rather than being quietly eaten by ineffective retries and bloated context. This is what “near-zero cost” truly means for engineering teams.
