Multi-Agent Token Cost Control: A Practical Guide to Fixing Runaway Token Usage in Production

    Multi-agent AI systems can trigger non-linear token growth that leads to runaway costs. This article examines the root causes—context bloat, over-decomposition, lack of model routing, and poor observability—and presents a practical, five-dimension governance framework covering architecture, context, model routing, caching, and observability. Readers will find actionable strategies, sample orchestration and compression code, a model-tier routing table, and an engineering checklist for building token budgets, summaries, caches, and cost dashboards into their agent platforms early.

    1. Why Token Usage Explodes After Agents Scale Up

    Single-turn conversational calls are increasingly being replaced by agents capable of autonomous planning, tool use, and multi-step execution. When multiple agents collaborate on complex business tasks—code generation, document writing, data analysis, ticket processing—the call chain evolves from “question and answer” into a long pipeline of “plan → decompose → parallel execute → aggregate results → reflect and retry.”

    From an engineering standpoint, this architectural upgrade introduces an immediate and serious problem: token consumption grows non-linearly.

    Third-party consumer transaction analysts observing anonymized US credit card transaction data have noted that one leading LLM provider’s high-tier subscription scale has doubled in a short period, with new users heavily concentrated in low- and mid-priced tiers. This suggests that a large number of developers and enterprise users are using agent capabilities in high-frequency, long-context ways. Public industry discussions have even surfaced extreme cases of “a single heavy user or a single workflow consuming hundreds of thousands of dollars worth of tokens per month.” Whether or not the specific numbers are exaggerated, the underlying trend is clear:

    1. The more complex the task, the more “verbose” the agent. To help the model understand the task, developers often stuff large amounts of background material, tool descriptions, and historical conversation into the context.
    2. The more agents, the more call counts snowball. When a single task is distributed to a planning agent, an execution agent, a review agent, and a tool-calling agent, the number of calls goes from 1 to 10, 50, or even hundreds.
    3. Failure-retry costs are underestimated. Many frameworks default to “retry on failure” with no retry ceiling and no fallback strategy—one infinite loop can burn tens of thousands of dollars.
    4. The context window is treated as “free memory.” Many developers habitually stuff entire knowledge bases or entire code repositories into the context, ignoring the fact that tokens are a core metered resource.

    This article presents a practical multi-agent token cost governance plan built around the above issues, covering five dimensions: architecture, context, routing, caching, and observability.


    2. Root Cause Analysis: Four Technical Causes of Runaway Token Consumption

    2.1 Context Bloat: Treating “Long Context” as Capability While Ignoring On-Demand Loading

    In multi-agent systems, context bloat typically comes from three sources:

    • Overly long system prompts: To give an agent sufficient role definition and behavioral constraints, prompts are packed with background descriptions, output-format constraints, and safety rules. A single agent’s system prompt can easily run into thousands of tokens.
    • Full-history passthrough: In multi-turn agent interactions, each turn re-concatenates the complete inputs, outputs, and tool-call results of previous turns. The context of turn 10 may already be 5–10 times that of turn 1.
    • Full injection of knowledge bases/documents: In RAG (retrieval-augmented generation) scenarios, some implementations inject dozens or even hundreds of document fragments directly to maximize recall, easily pushing a single call’s context past tens of thousands of tokens.

    Core misconception: Many developers treat the context window as “free high-speed cache” and believe “if it fits, stuff it in.” But under a billing model, every tool call and every sub-agent launch requires paying for every token in the context.

    2.2 Runaway Task Decomposition: The Multiplicative Effect of Agent Count on Call Volume

    The core value of a multi-agent architecture lies in “division of labor,” but division of labor does not always improve efficiency. Common failure patterns include:

    • Over-decomposition: Breaking “write a piece of code” into “requirements analysis agent → code-writing agent → unit test agent → code review agent → documentation agent,” where every step re-invokes the model and every step carries the full context.
    • Serial waiting: Sub-tasks that could run in parallel are executed serially, with each sub-task independently consuming a full round of context.
    • Redundant inter-agent communication: Agent A’s output is passed in full to Agent B, whose output is then passed in full to Agent C, with no compression or filtering in between.

    If each agent call consumes an average of 5,000 tokens, decomposing into 10 agents totals 50,000 tokens. Add failure retries, and costs can double again.

    2.3 Lack of Model Routing: Using the “Most Expensive Model” for Everything

    In the early stages of multi-agent adoption, many teams habitually have all agents use the same flagship LLM. In reality, different sub-tasks vary enormously in their model-capability requirements:

    • Intent recognition, text classification, format conversion: Lightweight models or even rule engines are sufficient.
    • Code generation, complex reasoning: Require models with stronger reasoning ability.
    • Creative writing, solution design: Require long context and strong generation ability.

    Routing every stage through the flagship model is like “using a sports car to deliver food.”

    2.4 Missing Observability: Not Knowing Where the Tokens Go

    Most teams look at their bill for the first time only when costs spiral out of control. The following observability capabilities are lacking:

    • Token consumption details per agent, per task, and per user.
    • Input tokens, output tokens, and cache-hit status for each call.
    • Failure-retry counts, timeout counts, and number of times exception branches are triggered.

    Without data, you cannot pinpoint “which agent is burning money,” “which task types are most expensive,” or “which prompts need optimization.”


    3. Architecture-Level Governance: From “All-in-One” to “On-Demand Collaboration”

    3.1 Control the Number of Agents: Prefer Single Agent + Tool Calls

    Multi-agent is not a silver bullet. For most business scenarios, a single agent + structured tool calls + workflow orchestration is sufficient. Consider multi-agent only in the following cases:

    • The task can naturally split into multiple independent sub-goals (e.g., “research + writing + review”).
    • Isolation of different roles/permissions/knowledge domains is needed.
    • Multiple similar sub-tasks need to be processed in parallel.

    Recommendation: Start with a single agent + workflow to get the main path working, observe token consumption and task-completion rate, then gradually introduce sub-agents.

    3.2 Task Decomposition Principles: Minimally Complete + Result Convergence

    Decomposition should follow these principles:

    • Minimally complete: Each sub-task contains only the information required to complete that step, carrying no irrelevant context.
    • Result convergence: Sub-agent outputs should be compressed and structured before being passed on, rather than dumping raw long text to the next agent.
    • Parallelizable: Parallelize sub-tasks where possible to reduce the number of serial calls.
    • Terminable: Set a maximum number of sub-tasks and a maximum number of call rounds to avoid infinite decomposition.

    Sample orchestration logic:

    1. # Pseudocode: task orchestration with max rounds and result convergence
    2. def run_multi_agent_task(task, max_steps=6, max_subtasks=4):
    3. context = build_minimal_context(task) # Load only information required for the task
    4. subtasks = planner_agent(task, context, max_subtasks=max_subtasks)
    5. results = []
    6. for step, subtask in enumerate(subtasks):
    7. if step >= max_steps:
    8. break
    9. # Execute in parallel and structurally converge results
    10. sub_result = executor_agent(subtask, context=compress_context(context))
    11. results.append(summarize(sub_result)) # Keep only the summary, not the full text
    12. final = reviewer_agent(task, compressed_results=results)
    13. return final

    3.3 Separate Planning from Execution

    The planning agent is responsible for decomposing tasks; the execution agent is responsible for specific calls. Planning results should be structured (e.g., JSON) rather than long natural-language prose. This reduces context length and enables downstream agents to precisely read the fields they need.


    4. Context-Level Governance: Compression, Filtering, and On-Demand Loading

    4.1 Context Budget

    Set a context budget for each agent and each call. For example:

    • No more than 8,000 tokens for a single agent call.
    • No more than 50,000 tokens for a single task’s full chain.
    • When the budget is exceeded, trigger compression, summarization, or fallback strategies.

    4.2 Sliding Window and Summary Compression

    For multi-turn interactions:

    • Sliding window: Retain the full text of only the most recent N turns.
    • Summary compression: Generate a 200–500 token summary of earlier turns via a summarization model to replace the original text.
    • Key-information retention: For constraints explicitly requested by the user (format, language, must-have points), extract them separately as structured fields so they are not lost as the window slides.
    1. def compress_history(history, keep_turns=3):
    2. recent = history[-keep_turns:]
    3. older = history[:-keep_turns]
    4. summary = summarize_messages(older) if older else ""
    5. return summary + recent

    4.3 RAG Recall Reranking and Truncation

    • Do not “inject on recall.” First do coarse recall, then use a reranking model to select the top K (e.g., 3–5 items).
    • Apply length truncation and deduplication to injected content.
    • Structurally pre-process knowledge base documents, keeping only fragments strongly relevant to the task.

    4.4 Tool Return-Result Compression

    The raw JSON, HTML, and logs returned by tool calls are often lengthy. Before returning them to the model:

    • Field filtering: keep only fields required for the task.
    • Numeric summarization: aggregate statistics for long lists.
    • Error-code normalization: map lengthy error messages to concise error types.

    5. Model Routing Governance: Let the Right Model Do the Right Work

    5.1 Tiered Routing Strategy

    Task type Recommended model tier Notes
    Intent recognition, classification, format conversion Lightweight/small-parameter model Low latency, low cost
    Information extraction, summarization, simple Q&A Mid-tier model Balances cost and quality
    Code generation, complex reasoning, solution design Flagship/large-parameter model Quality first
    Long-document analysis, cross-document reasoning Long-context model Enable as needed

    5.2 Dynamic Fallback

    When a flagship-model call fails, times out, or exceeds its cost limit, automatically fall back to a mid-tier model and annotate the fallback status in the result so the business side can decide whether manual intervention is needed.

    5.3 Batch Processing and Cache-Hit Priority

    • For tasks with high determinism (e.g., text classification, entity extraction), prefer the batch-processing API.
    • For repeated queries, prefer the semantic cache to avoid redundant model calls.

    6. Caching and Reuse: Drive Repeated Costs to Zero

    6.1 Exact Cache

    Use “model name + full prompt + parameters” as the key and return directly on a hit. Suited to FAQs and fixed-template tasks.

    6.2 Semantic Cache

    Vectorize the input and reuse historical results when similarity exceeds a threshold. Suited to knowledge Q&A and customer service scenarios.

    Caveats:

    • Set a reasonable similarity threshold to avoid false hits.
    • Disable caching or set an extremely short TTL for highly time-sensitive data (e.g., real-time quotes, inventory).
    • Do not include user-sensitive information in cache keys.

    6.3 Prompt Prefix Caching

    Many LLM services support “prefix caching”: if the system prompt and knowledge-base prefix are identical across multiple calls, the platform can cache the KV of that prefix, and subsequent calls only charge for the newly added portion or reduce compute overhead. In engineering practice, place fixed instructions, tool descriptions, and knowledge-base content at the front of the prompt and dynamic content at the back.

    1. [Fixed prefix] System role, safety rules, tool list, domain knowledge base
    2. [Dynamic part] User's current question, conversation history, tool return results

    6.4 Result Reuse and Incremental Updates

    For long tasks, persist intermediate results (e.g., already-generated code, already-summarized documents) so the next call processes only the incremental portion instead of regenerating from scratch.


    7. Observability and Cost Operations

    7.1 Build a Token Metering System

    The following metrics must be collected:

    • Input/output token counts per agent, per task, per user, and per model.
    • Cache hit rate, retry counts, failure rate, and average latency.
    • Total cost per task and daily average cost per user.

    7.2 Budget Alerts and Circuit Breaking

    • Set daily/monthly token budgets by user/tenant/task type.
    • Issue tiered alerts at 70% and 90% thresholds.
    • Automatically trigger circuit breaking or fall back to a lower-cost model when exceeded.

    7.3 Continuous Optimization Loop

    • Weekly review of top token-consuming tasks to identify high-consumption agents and prompts.
    • Run targeted optimizations for high-consumption scenarios: compress context, adjust decomposition granularity, change routing strategy.
    • Build a dual-metric “cost–quality” dashboard to avoid sacrificing task-completion rate for cost reduction.

    8. Engineering Implementation Checklist

    1. Map the call chain: Draw the agent call graph for each business scenario, annotating the input source and token magnitude of each call.
    2. Set context budgets: Define maximum input and output tokens for each agent type.
    3. Introduce summary compression: Summarize or field-filter conversation history and tool return results.
    4. Implement model routing: Assign different model tiers by task type and support dynamic fallback.
    5. Connect a caching layer: Combine exact cache + semantic cache + prefix cache.
    6. Build a monitoring dashboard: Make token consumption, cache hits, failure retries, and cost trends visible at a glance.
    7. Define circuit-breaking rules: Auto-fallback or pause when budgets are exceeded to prevent single-point runaway.
    8. Review and optimize periodically: Continuously refine decomposition granularity and prompt structure on a weekly/monthly cycle.

    9. Conclusion

    The multi-agent architecture has evolved LLMs from “Q&A tools” into “digital workers that can execute tasks,” but token cost is an unavoidable threshold for large-scale deployment. The core of cost governance is not “using fewer models” but ensuring every call produces necessary value:

    • Architecturally, do not decompose if you can avoid it; if you must decompose, converge results.
    • Context-wise, compress wherever possible and load on demand.
    • Routing-wise, let the right model do the right work.
    • Caching-wise, reuse rather than repeat calls.
    • Operationally, make it visible, measurable, and controllable.

    For teams building agent platforms or enterprise AI applications, it is advisable to incorporate token metering, budget alerts, and caching capabilities into the infrastructure early, rather than scrambling to fix things after the bill spirals out of control. In engineering practice on cloud platforms such as Baidu AI Cloud, combining general-purpose LLM services, object storage, message queues, logging services, and monitoring/alerting capabilities can already support a complete agent cost governance system; the key is whether the team has established a design mindset of “cost as architecture.”