How to Cut Token Costs in the Agent Era

    As AI agents move from answering questions in a chat window to executing tasks autonomously in the background, their cost model changes fundamentally. A single office task can trigger repeated tool calls, file reads, and intermediate validation, causing a few thousand tokens to snowball into hundreds of thousands. This article abstracts the problem into how to systematically reduce token overhead in agent architectures, covering context engineering, prompt compression, model routing, caching, observability, and budget guardrails, along with a practical rollout order.

    When agents evolve from “one question, one answer in a web page” to “autonomous execution in the background,” the cost model changes fundamentally. In the past, a single conversation consumed only one round of context. Today, a single office task may involve a chain of skill modules that repeatedly call tools, read files, and validate intermediate results, with the context repackaged at every step. The first round may use only a few thousand tokens, but across multiple rounds and failed retries, this can easily snowball into hundreds of thousands of tokens. More critically, many models enable deep thinking mode by default, generating large amounts of intermediate reasoning even for simple tasks and further amplifying consumption. This article does not discuss any specific vendor’s quota policy. Instead, it frames the problem as “how to systematically reduce token overhead in an agent architecture” and presents a set of practical engineering methods.

    1. Understand Where the Cost Comes From

    To optimize cost, you first need an intuition for the cost formula. The cost of a single task can be roughly expressed as: input tokens × input price + output tokens × output price, multiplied by the number of model calls within the task. What makes agent scenarios special is that all three factors are amplified at the same time.

    • Context accumulation: Raw content returned by tools (logs, web pages, spreadsheets) is often huge and enters the next round without trimming.
    • Call count inflation: Planning, execution, reflection, and summarization each invoke the model separately, so a single task can trigger more than ten requests.
    • Output redundancy: Polite phrases, repeated restatement, over-explanation, and unnecessary long-chain reasoning all consume output allowance.

    Therefore, cost reduction is not a single-point trick but a coordinated effort across four dimensions: input trimming, output constraints, call count, and model selection.

    2. Context Engineering: Turn “Reading More” into “Reading Precisely”

    Most waste comes from stuffing entire raw documents into the context. A more reliable approach is layered retrieval: first use a lightweight method to locate candidate fragments, then inject only the necessary fragments into the prompt.

    1. # Example: retrieve to locate first, then read on demand, avoiding loading entire files into context
    2. def build_context(query, index, max_chars=2000):
    3. hits = index.search(query, top_k=5) # lightweight recall
    4. picked = [h for h in hits if h.score > 0.6][:3]
    5. text = "\n".join(h.snippet for h in picked)
    6. return text[:max_chars] # hard limit to prevent unexpected growth

    Supporting practices include: structurally trimming tool return values (keeping only fields rather than the entire JSON), building a summary layer for long documents, and placing stable background knowledge in a reusable system prompt instead of retransmitting it every round. The goal is to increase “effective information density,” not to truncate crudely.

    3. Prompt Compression: Make Expression Shorter Without Losing Meaning

    The idea of “replacing verbose colloquial language with more concise expression” is valid, but it needs engineering constraints rather than relying on the model’s self-discipline. A practical approach is to define an explicit output contract in the system prompt: limit word count or number of key points, prohibit restating user input, prohibit uninformative openings and closings, and require information to be carried in bullet points or tables.

    1. Output constraints:
    2. 1. Output only conclusions and necessary evidence, with a total length of no more than 200 words;
    3. 2. Do not restate the question or write transitional filler;
    4. 3. When enumeration is needed, use short bullet points, each no more than 20 words.

    It is worth noting that compression must not come at the expense of correctness. For scenarios involving computation, compliance, or code generation, necessary reasoning and validation steps should be preserved, and only the “human-facing expression” should be compressed.

    4. Model Tiering and Routing: Don’t Use the Most Expensive Model for Simple Tasks

    Layering tasks by difficulty is one of the most reliable ways to reduce cost. The rules can be simple: intent recognition, format conversion, and field extraction go to a lightweight model; tasks requiring multi-step reasoning and code generation go to a more capable model; ultra-long-context tasks should prioritize the tier with better cost-performance for long context.

    1. def route(task):
    2. if task.type in ("classify", "extract", "format"):
    3. return "light" # lightweight tier
    4. if task.type in ("plan", "code", "review"):
    5. return "strong" # high-capability tier
    6. return "standard"

    Combined with a “small first, then large” strategy: first use a lightweight model to produce a draft or candidate answer, and only upgrade to a stronger model for a retry when confidence is insufficient. This can significantly reduce high-cost calls.

    5. Caching and Reuse: Reduce Repeated Overhead to Zero

    When agents repeatedly read the same file or answer similar questions, caching yields high returns. Cacheable objects include: system prompts and tool descriptions, retrieval results, idempotent results of tool calls, and intermediate artifacts of stages. In engineering, it is recommended to design an explicit version number for cache keys to avoid behavior drift caused by hitting stale cache after prompt changes.

    1. cache = {}
    2. def cached(key, fn):
    3. if key not in cache:
    4. cache[key] = fn()
    5. return cache[key]

    At the same time, split long workflows into “reusable stages” so that the results of stable stages can be directly referenced by subsequent steps instead of being regenerated every round.

    6. Observability and Budget Guardrails

    Without measurement, there is no optimization. It is recommended to record for each task: number of calls, input and output token distribution, time spent per stage, and number of failed retries, and to aggregate “cost per task” by task type. On this basis, set guardrails: a token limit per task, a limit on consecutive failed retries, and automatic downgrade to a lightweight model or termination with a prompt for human intervention when the budget is exceeded.

    1. if used_tokens > BUDGET:
    2. return fallback_answer() # downgrade or escalate to human to avoid cost overrun
    1. First integrate metering and logging to obtain a real cost profile;
    2. Then implement context trimming and output contracts, which are small changes with quick results;
    3. Next introduce model routing and caching to eliminate repeated and high-price calls;
    4. Finally improve budget guardrails and evaluation sets to ensure cost reduction without quality degradation.

    Stacking the above methods together can typically reduce the cost per task by an order of magnitude. Real cost reduction has never been about finding some “nearly free” entry point, but about building a system out of context, prompts, routing, caching, and guardrails. When this mechanism runs stably, agents can be both fast and cost-efficient.