Agent Token Costs Rising Too Fast? Govern Usage Before Choosing a Model

    Many teams find that agent token consumption grows much faster than expected, while task completion rates do not improve at the same pace. This article explains why model price per token is only one part of total cost and presents a practical sequence: audit token usage, optimize session lifecycle and heartbeats, govern memory and tool outputs, then build model routing and evaluation based on real task metrics. Readers get an actionable framework for measuring cost per completed task, setting context budgets, reducing background polling, compressing tool results, and evaluating models after governance.

    Agent Token Costs Rising Too Fast? Govern Usage Before Choosing a Model

    Many teams encounter the same problem after running agents for a while: token consumption grows far beyond expectations, bills rise quickly, but task completion rates do not improve in parallel. The most common mistake at this point is to immediately compare model prices per token and try to solve the problem by switching to a cheaper model. In reality, model price per token is only one part of total cost. If session lifecycle, heartbeat tasks, memory injection, and tool outputs are not governed, switching models often just moves waste from one billing model to another.

    A more reasonable order is: first audit where tokens go, then optimize sessions and heartbeats, then govern memory and tool outputs, and finally establish tiered model routing and an evaluation system. This article follows that order and provides a practical technical approach.

    1. Understand the Real Sources of Token Consumption

    A single agent call does not contain only the user question. Common input-side consumption includes:

    1. System prompts and role settings;
    2. Long-term memory, project facts, and user preferences;
    3. Tool definitions and function descriptions;
    4. Historical conversation messages;
    5. Tool call results;
    6. Background sessions such as heartbeats, scheduled tasks, and state checks;
    7. Repeated calls caused by failed retries, format repairs, and second confirmations.

    Output-side consumption includes model replies, tool parameters, structured results, and intermediate outputs during retries. Many systems count only tokens from “user conversations” while ignoring heartbeat tasks and memory injection, which makes bills diverge sharply from intuition.

    Therefore, when evaluating cost-effectiveness, do not look only at “price per million tokens.” Look at cost per completed task:

    1. Cost per task =
    2. (input tokens × input price + output tokens × output price)
    3. + retry and failure cost
    4. + manual maintenance cost
    5. + business cost caused by latency
    6. Cost-effectiveness ≈ task success rate / cost per task

    Model selection only becomes meaningful when retry rates, tool-call accuracy, structured-output validity rates, and manual intervention costs are included.

    2. Step One: Establish a Token Audit Baseline

    Before optimizing, answer three questions: Which tasks consume tokens? Which sessions are the longest? Which types of calls are retried most often?

    Record common audit fields for every model call, not just the total bill:

    1. audit_record {
    2. session_id
    3. task_type
    4. turn_index
    5. input_tokens
    6. output_tokens
    7. memory_tokens
    8. tool_schema_tokens
    9. tool_result_tokens
    10. is_heartbeat
    11. retry_count
    12. success
    13. latency_ms
    14. }

    Based on audit data, establish at least the following baseline metrics:

    • Average input/output tokens per task;
    • Share of heartbeat tasks;
    • Share of memory injection;
    • Share of tool result content;
    • Retry rate and structured-output failure rate;
    • Cost per successful task and end-to-end latency.

    Model comparisons without a baseline are meaningless. A model with a lower unit price may have unstable tool calls and frequent field drift; after two retries, its total cost may be higher.

    3. Step Two: Govern Session Lifecycle and Avoid Unlimited Context Accumulation

    The longer a single session runs, the more historical messages it contains. Each subsequent turn must carry a longer context, so token consumption grows cumulatively. More seriously, irrelevant history can interfere with model judgment and increase tool-call errors and repeated confirmations.

    Governance strategies include:

    1. Split sessions by task: one task per session, and reset context when the task is complete. Do not use one long-running session to carry multiple unrelated goals.
    2. Create new sessions with handoff summaries: when work must continue across tasks, do not carry the full history. Generate a structured handoff summary that keeps only the goal, constraints, completed items, and todos.
    3. Set context budgets: set token limits for historical messages, memory, and tool results separately. When limits are exceeded, trigger summarization or truncation.
    4. Separate short-term state from long-term facts: keep temporary state inside the session and stable preferences in long-term memory. Avoid injecting all content again on every turn.

    Illustrative pseudocode:

    1. function prepare_context(session, user_input):
    2. if session.task_changed or session.turn_count > MAX_TURNS:
    3. summary = summarize(session, fields=[goal, constraints, done, todo])
    4. session = reset_session(handoff=summary)
    5. context = build_context(
    6. system_prompt = compact_system_prompt(),
    7. memory = retrieve_memory(user_input, budget=MEMORY_BUDGET),
    8. history = summarize_if_needed(session.history, budget=HISTORY_BUDGET),
    9. tool_schema = load_tools_for_task(session.task_type),
    10. user_input = user_input
    11. )
    12. return context

    The key is not mechanical resetting. The key is making handoff information structured and short enough.

    4. Step Three: Reduce Heartbeat Costs, Because Background Polling Is a Hidden Cost Driver

    Heartbeat tasks, scheduled checks, and state polling are easy to underestimate. Each heartbeat may trigger a complete session that injects role settings, memory, and tool definitions. If heartbeat frequency is high and tasks are complex, it will continuously consume tokens even without user interaction.

    Optimization directions:

    1. Slow down when possible: reduce non-critical heartbeat frequency and classify heartbeats by business timeliness.
    2. Merge when possible: combine multiple checks into one batch check to reduce session startup次数.
    3. Use event-driven triggers when possible: replace fixed polling with state changes, message arrival, and threshold triggers.
    4. Use scripts when possible: run deterministic checks, field comparisons, and threshold judgments with scripts, and send only the parts that require semantic judgment to the model.
    5. Load only necessary context for heartbeats: do not inject full persona memory and all tool descriptions on every heartbeat.

    Illustrative pseudocode:

    1. function heartbeat():
    2. state = run_script_check() // deterministic check, no model call
    3. if state.requires_reasoning:
    4. context = {
    5. role: "checker",
    6. memory: retrieve_memory("heartbeat_policy", budget=SMALL_BUDGET),
    7. tools: load_tools(["alert", "ticket"])
    8. }
    9. model_call(context, state.summary)
    10. else:
    11. log(state)

    The goal of heartbeat design is to “detect anomalies and trigger follow-up actions,” not to make the model think through everything again every time. Moving deterministic logic into scripts can significantly reduce invalid calls.

    5. Step Four: Memory Management Needs Budgets and Cleanup Mechanisms

    More memory is not always better. Long-term memory that is too long creates three problems: higher token cost, more retrieval noise, and diluted model attention. Recommended memory categories:

    • Long-term preferences: stable, low-frequency changes, such as output format preferences;
    • Project facts: related to the current project and requiring version management;
    • Temporary state: should exist only in the current session and should not be written into long-term memory;
    • Operation logs: used for auditing and should not be injected into model context by default.

    Governance measures:

    1. Regularly clean up memory, merge duplicates, and delete expired items;
    2. Set token budgets for memory injection and retrieve by task type instead of injecting everything;
    3. Manage workspace memory files manually or semi-automatically, keeping indexes and summaries;
    4. Deduplicate and check sensitivity before writing memory;
    5. Use structured fields for content that “must be remembered” to reduce natural-language redundancy.

    The core of memory governance is: retrieve on demand, inject summaries, compress regularly, and keep it auditable and rollback-capable.

    6. Step Five: Compress Tool Outputs and Context Materials

    Tool results are often a hidden token sink. If logs, web content, database query results, and configuration file diffs enter context as-is, they quickly consume the budget. Recommendations:

    • Structure tool results first, then summarize them;
    • Store large files in object storage and pass only summaries, references, and key fields to the model;
    • Filter logs by level and keep only errors and critical context;
    • Deduplicate repeated content;
    • Use a “summary + expandable reference on demand” pattern for long text;
    • Validate structured outputs against schemas to reduce format-repair retries.

    For example, on Baidu AI Cloud, large archives, log auditing, and monitoring alerts can be handled by object storage, log services, and monitoring and alerting capabilities respectively, while the model context keeps only summaries and pointers. This avoids repeatedly injecting raw large text.

    7. Step Six: Place Model Selection After Governance

    After the governance steps above are complete, model selection compares “real task cost.” Build a multi-dimensional evaluation matrix:

    Dimension Focus
    Task success rate End-to-end completion rate, manual takeover rate
    Tool-call accuracy Parameter validity rate, correct tool selection rate
    Structured output JSON/field validity rate, field drift rate
    Context capability Ability to retain key information in long contexts
    Multimodal capability Whether image and other inputs are supported as required by the business
    Stability Behavior under configuration changes, long tasks, and exception recovery
    Quotas and cost Subscription quotas, rate limits, peak availability
    Compatibility Fit with runtime, tool protocols, and retry strategies

    For model selection, use tiered routing:

    • For highly deterministic tasks such as classification, extraction, and format conversion, use lower-cost, faster models;
    • For complex reasoning, cross-tool planning, and multimodal understanding, use stronger models;
    • For structured configuration modification tasks, add schema validation, diff preview, sandbox execution, and rollback;
    • For issues such as output field drift, invalid parameters, and process exceptions, evaluate stability first, then discuss unit price.

    Some models perform well on speed or long context but may show field drift, invalid output, or even runtime exceptions in structured configuration modification scenarios. Other models may have good capabilities but tight subscription quotas. These should be quantified through the evaluation matrix rather than judged from a single experience.

    8. Step Seven: Configuration Changes Must Be Engineered

    An agent modifying its own configuration is a high-risk management operation. Do not let the model directly change production configuration. Recommended flow:

    1. Generate candidate configuration
    2. -> schema validation
    3. -> field allowlist validation
    4. -> diff preview
    5. -> sandbox load test
    6. -> manual or automatic approval
    7. -> canary release
    8. -> monitoring and rollback

    At the same time, require configuration changes to be idempotent, versioned, and rollback-capable. When model output fields are unstable, use strict schemas and retry limits to avoid making configuration increasingly chaotic.

    9. Implementation Roadmap

    A recommended pace:

    1. Day 1: Add audit fields and measure the share of heartbeats, memory, tool results, and retries;
    2. Day 3: Split sessions by task, set context budgets, and add handoff summaries;
    3. Week 1: Reduce heartbeat frequency, merge checks, and move deterministic logic into scripts;
    4. Week 2: Establish memory budgets, cleanup mechanisms, and tool-output compression strategies;
    5. Week 3: Build a model evaluation matrix and tiered routing, starting with small traffic canary releases;
    6. Ongoing: Monitor cost per task, success rate, and retry rate, and review weekly.

    Conclusion

    Rapid token consumption is usually not a single-model problem. It is the combined result of task structure, session lifecycle, heartbeat scheduling, memory injection, and tool outputs. The right order is: audit first, then govern sessions and heartbeats, then compress memory and tool results, and finally use real task metrics for tiered model selection. Only by making “cost per completed task” the core metric can teams achieve a sustainable balance among cost, stability, and user experience.