How to Cut Token Costs in the Agent Era
As AI agents take on multi-step office tasks, token consumption can balloon from thousands to hundreds of thousands per run. This article breaks down where the cost actually goes—system prompts, tool schemas, accumulated context, and verbose model output—and presents a five-layer optimization framework: measurable output constraints, context engineering that keeps conclusions rather than process, model tiering and routing, caching and reuse, and observability with governance. By applying all five layers, teams can turn unpredictable agent bills into a controllable, sustainable cost engineering system without sacrificing quality.
1. The Problem: Smarter Agents, Uglier Bills
In the traditional web chat model, a single session has short context and few turns, so cost is naturally manageable. Office-oriented agents work in a fundamentally different way: they plan autonomously in the background, call tools repeatedly, read files, and verify results. Every step requires repackaging the current state into the context. The first turn may involve only a few thousand tokens, but after multiple rounds of accumulation and compounding, a single task can easily swell to hundreds of thousands of tokens.
Waste on the output side is even more subtle. Models tend to add extensive pleasantries and process narration before the actual answer. This content adds no value to the final deliverable, yet it is billed as output tokens—and output pricing is typically higher than input. The result is an awkward situation: the more capable the agent and the longer it runs, the less predictable the bill becomes.
2. Cost Breakdown: Where the Money Actually Goes
Before optimizing, you need to understand the bill’s composition. Token consumption for a single agent task can be divided into four parts:
- System prompts and role definitions: carried repeatedly in every turn.
- Tool and skill descriptions: the more skills mounted, the longer the schemas and descriptions.
- Conversation history and intermediate artifacts: files read, command outputs, and failure stack traces all settle into the context.
- Model output: includes the final answer plus a large amount of redundant reasoning and explanatory text.
The first three are input-side costs, characterized by “repeated billing.” The fourth is output-side, characterized by “higher unit price.” Optimization must address both sides simultaneously; compressing prompts alone while ignoring context management will quickly hit diminishing returns.
3. Layer 1: Output Constraints—Turn Verbosity into a Measurable Metric
Concise expression cannot rely on vague instructions like “be brief.” It requires verifiable hard constraints. Three things should be stated explicitly in the prompt: no process narration by default; conclusions first; errors report only key information.
Output rules:1. Output only the final result; no opening pleasantries or closing boilerplate;2. On failure, output only: failed step, error code, minimal reproduction input;3. Keep each response under N lines; if exceeded, switch to a structured summary.
The key point is that constraints must be measurable and regression-testable. Turn “response line count” and “presence of filler sentences” into automated checks and include them in the evaluation set, so that saving tokens does not come at the expense of information completeness. Some communities have experimented with minimal syntax or high-density written language to compress expression, and the idea is worth borrowing. However, the more robust engineering approach is structured output (such as a result object with fixed fields), because its compression ratio is stable and parseable.
4. Layer 2: Context Engineering—The Biggest Payoff
The real bulk of cost is on the input side. The core principle: do not keep “process” in the context; keep only “conclusions.”
- Segmented loading: retrieve and locate relevant sections of long documents first, then read fragments on demand instead of stuffing entire files in.
- Externalize intermediate results: write large logs and file contents to external storage or workspace files, keeping only paths and summaries in the context.
- Subtask isolation: open a new session context for independent subtasks, and return only structured conclusions when done.
- Failure context compression: on retry, do not carry the full stack trace; carry only the error code and minimal reproduction.
- On-demand skill mounting: skill descriptions themselves consume tokens, so load them dynamically by task type rather than keeping them all resident.
Illustrative context-trimming logic:
def build_context(task, history, budget):# 1. System prompt and skill descriptions are fixed and kept as short as possiblectx = [system_prompt, load_skills(task.type)]# 2. Keep only conclusions from history, not the processctx += [compress(h) for h in history if h.kind == "conclusion"]# 3. Convert large objects into referencesfor art in task.artifacts:ctx.append({"type": "ref", "path": art.path, "digest": art.summary})# 4. When over budget, drop low-value fragments by priorityreturn trim_by_priority(ctx, budget)
5. Layer 3: Model Tiering and Routing
Not every step needs the most powerful model. Tasks can be divided into three tiers: intent recognition and formatting use a lightweight model; routine coding and document processing use the main model; complex reasoning and architecture decisions invoke a high-capability model. The routing layer decides the tier based on task labels, input length, and historical failure count, and sets a per-task cost cap. When exceeded, it automatically downgrades or escalates to human confirmation. This layer typically delivers the most direct cost reduction without hurting critical-path quality.
6. Layer 4: Caching and Reuse
- Prefix caching: place stable, unchanging system prompts and knowledge fragments at the very front of the context to improve cache hit rates.
- Result caching: for idempotent query calls, cache results keyed by a normalized request fingerprint.
- Semantic caching: reuse historical answers for highly similar repeated questions, with a similarity threshold and invalidation policy.
- Batching: merge requests for non-real-time tasks to reduce repeated system overhead.
7. Layer 5: Observability and Governance
Without measurement, there is no optimization. Collect input/output tokens, cache hit rate, tool call count, and per-task cost for every task, and aggregate them into dashboards by business line, scenario, and model tier, with budget alerts and quotas. Also maintain an offline evaluation set: any change to prompts or routing strategy must run both quality and cost metrics to prevent “saving money but losing quality.”
For the deployment environment, you can use a general-purpose container platform in the cloud to host the agent runtime, object storage to hold intermediate artifacts, a message queue to decouple long-running tasks, logging and monitoring services for cost attribution, and a key management service to centrally manage credentials. These are all common capability categories in the industry; evaluate specific choices based on your own scale and compliance requirements.
8. Conclusion
The root cause of runaway token costs is not unit price, but the context expansion and output redundancy introduced by the agent architecture. Making output constraints measurable, shifting context to “conclusions first,” tiering models by difficulty, caching repeated requests, and turning cost into an observable dashboard—only by stacking all five layers can per-task cost be pressed into a predictable range. For teams, real cost reduction is not about finding cheaper channels, but about building a sustainable cost engineering system.
