Cutting AI Agent Token Costs: Heartbeat Tasks, Memory Management, and Model Selection

    Token consumption is a common pain point when building AI agent applications, and running costs climb in lockstep with call volume. This article explains how to identify the three main sources of token waste—repeated context injection in heartbeat tasks, unmanaged memory growth, and overly long sessions—then walks through architecture-level optimizations such as session splitting and scripted heartbeat checks, with a practical Python example. It closes with a framework for choosing models based on both unit price and capability.

    Many teams’ first reaction to rising token costs is switching to a cheaper model. However, if the agent’s operating mechanism itself is wasteful, even low-priced models will be drained by unnecessary calls. The right order is to fix the runtime mechanism first, then select models based on unit price and capability. This article follows that sequence: locate the root causes, optimize the architecture, and apply a consistent method for model selection.

    1. Three Main Sources of Token Consumption

    1.1 Repeated Context Injection in Heartbeat Tasks

    To stay online and respond proactively, agents typically run heartbeat tasks. Each heartbeat is essentially a full model session: the system re-injects the persona definition, workspace memory, and current environment state. If a heartbeat involves multiple reasoning steps, or fires too frequently, token consumption multiplies with each trigger.

    1.2 Memory Without Lifecycle Management

    Agents continuously accumulate conversation history, intermediate artifacts, and factual records during interactions. Without expiration and compression mechanisms, all of this content is loaded into the context window. The longer the session, the more input tokens per request—and the higher the cost of each interaction.

    1.3 Overly Long Sessions Without Truncation

    In multi-turn conversations, stale history that is never cleaned up forces the model to re-read the entire record on every call. This inflates input tokens and can also dilute the model’s attention, degrading output quality.

    2. Architecture-Level Optimizations

    2.1 Split Sessions by Subtask

    Use context-reset commands like /new to prevent sessions from growing indefinitely. When splitting a session, four things need to be handled explicitly:

    • Trigger conditions: for example, subtask completion, context exceeding a set threshold, or the user explicitly switching topics.
    • Summary handoff: before switching, have the model generate a short summary containing only the goal, completed items, pending tasks, and key constraints, then carry that summary into the new session.
    • State persistence: write task progress to external storage so work is not lost when the session is cut.
    • User notification: inform the user when the session switches, clarifying which information has been retained.

    2.2 Heartbeat Tasks: Lower the Frequency and Script What You Can

    For heartbeat tasks, follow the principle of “slow it down when possible, simplify it when possible.”

    • Adjust frequency: based on the latency your business can tolerate, widen the heartbeat interval from seconds to minutes or hours.
    • Script routine checks: deterministic logic such as status checks and threshold comparisons should run in scripts, consuming no model tokens.
    • Wake the model on demand: call the model only when the script determines that complex reasoning is required.

    The example below illustrates this approach. Before running it, confirm that: the script has permission to read the monitoring endpoint; external calls have timeouts, retry counts, and idempotency keys configured; token usage is logged for every call; and an hourly call cap plus a fallback strategy are in place.

    1. import logging
    2. import time
    3. logger = logging.getLogger("heartbeat")
    4. MAX_LLM_CALLS_PER_HOUR = 6 # Maximum model calls per hour
    5. llm_call_times: list[float] = [] # Timestamps of calls within the last hour
    6. def check_system_status(timeout: float = 5.0) -> dict:
    7. """Deterministic check, no model call. Replace with your actual monitoring API; must return 'level' and 'detail' fields."""
    8. raise NotImplementedError("Replace with your actual status query logic")
    9. def within_budget(now: float) -> bool:
    10. global llm_call_times
    11. llm_call_times = [t for t in llm_call_times if now - t < 3600]
    12. return len(llm_call_times) < MAX_LLM_CALLS_PER_HOUR
    13. def heartbeat_task():
    14. now = time.time()
    15. try:
    16. status = check_system_status(timeout=5.0)
    17. except Exception:
    18. logger.exception("Status check failed; degrading to log-only for this round")
    19. return
    20. if status["level"] != "CRITICAL":
    21. logger.info("Status normal; skipping model call this round")
    22. return
    23. if not within_budget(now):
    24. logger.warning("Hourly call limit reached; escalating to on-call staff")
    25. notify_human(status) # Replace with your actual notification method
    26. return
    27. llm_call_times.append(now)
    28. prompt = f"System is in a critical state: {status['detail']}. Provide remediation suggestions only; do not execute changes directly."
    29. response = call_llm_with_retry(prompt, retries=2, timeout=30) # Replace with your actual client wrapper
    30. logger.info("Model usage this call: tokens=%s", response.usage.total_tokens)
    31. # High-risk operations must go through human approval before execution
    32. queue_for_approval(response.text) # Replace with your actual approval workflow

    Note that the CRITICAL judgment in this example should be based on explicit thresholds—for instance, CPU usage sustained above 90% for five minutes—rather than relying on the model’s subjective characterization of the state. The model’s role is limited to proposing remediation steps;