Why Agent Token Costs Spike: Memory Assembly, Not Model Price

    High agent token spend is often driven by how context is assembled—system prompts, history, tool traces, and recalled memory—not by how often users type. This article explains why session state grows, how keyword-style recall distorts what gets injected, and how layered memory, extraction, compression, and budgets keep cost and reliability under control.

    High token consumption is rarely just “heavy usage.” Break an agent task into billed context and you usually find more than the user’s latest message: system prompts, history, tool calls and returns, and memory snippets stuffed back in so the model “knows you.” When usage ranks high, interaction density and context assembly already outweigh unit-price differences between models. Switching models while keeping the same architecture still lets the bill climb.

    Why state grows without bound

    Long-running agents persist sessions locally or on the server. A session is more than Q&A text: session IDs, channel, user IDs, titles, model and parameter snapshots, system-prompt snapshots, full message history, tool names, arguments, returns, and errors. The intent is clear: reuse past evidence on similar problems and avoid cold starts.

    Saving is not the same as being usable. If almost every interaction is appended as-is, state grows linearly or worse. Disk and indexes are the visible part; the expensive part is stuffing a slice of that store back into context before each inference. The model does not see the rest of the library—only the current window. A fuller window shrinks useful reasoning space and makes repeated explanations and repeated tool calls more likely.

    Self-improvement that only means “store more history” is not memory. Memory must answer four questions: what to extract, what to compress it into, under what conditions to recall it, and how many tokens recall may occupy. Miss any of those and the system oscillates between rambling and amnesia.

    Bias in keyword-style recall

    A common pattern is retrieval: chunk history, match with keywords or embeddings, splice hits into the prompt. That covers repeats such as “how we set that parameter last time,” but the criterion is surface similarity, not task importance.

    Constraints the user cares about may appear once, in plain language—for example “no automatic writes in production” or “amounts are in cents, not dollars.” If frequency, recency, or similarity thresholds drop them, they never re-enter context. Long debug logs, rich in overlapping terms, get recalled again and again. The typical illusion is that the agent is “not smart enough.” The usual root is inconsistent extract, compress, retain, and refill policies—not that the base model cannot understand the domain.

    A more stable design is layered memory, not one unbounded transcript:

    • Working memory: current goals, constraints, unfinished steps; short-lived; first claim on the window.
    • Episodic memory: conclusions and pointers to evidence from an episode; keep “what happened,” not every raw output.
    • Semantic memory: stable preferences, environment facts, prohibitions; short entries with source and update time.
    • Tool traces: intent, key parameters, success or failure; large payloads live in external storage and are excerpted on demand.

    Extraction and compression

    Extract at write time, not by truncating after the window explodes. After a turn, record in a fixed structure: user goal, confirmed facts, open questions, decisions, failure reasons, next steps. Archive raw messages; do not inject them by default next time.

    Compression should be reversible enough to verify, not to replay the full text. For tool returns, keep status, rows affected, error type, and one representative message. For long documents, keep title, version, a conclusion sentence, and storage location. Summaries must mark confidence: user-stated versus model-inferred. Inferred items in long-term memory get treated as facts and amplified.

    Refill needs a budget. Allocate the window by priority: system constraints and safety bounds reserved; then current goal; then relevant semantic memory; episodic and tool traces last, with caps on count and tokens. Overflow is not forced in; it becomes an index that can be looked up again. History still exists, but you do not buy the entire past on every inference.

    Illustrative flow (boundaries, not a specific stack):

    1. on_turn_end(session):
    2. facts = extract(goal, constraints, decisions, errors)
    3. upsert_semantic(facts.stable, source=turn_id, time=now)
    4. append_episodic(summary(facts), pointers_only=true)
    5. archive_raw(messages, tool_payloads)
    6. on_turn_start(query, budget):
    7. pack = [system_policy, current_goal]
    8. pack += semantic.top(query, limit=k1)
    9. pack += episodic.top(query, limit=k2)
    10. stop when tokens(pack) >= budget
    11. return pack

    Why repeated tool calls are especially expensive

    Tool loops amplify cost. If the model cannot see the last full return, it queries the same API again. Oversized returns stay in message history and you pay again next turn. Without a record that “this round already called with the same args and the result is still valid,” retries stack extra calls on failure.

    Control points are concrete: cache identical read operations inside a short window; writes need idempotency keys so a natural-language “try again” does not repeat side effects; trim tool results before they enter messages; after consecutive failures hit a threshold, stop auto-retry and write error type plus needed human input into working memory. Otherwise spend and forgetfulness rise together: money goes to duplicate evidence while key constraints are never kept.

    Cost control is about assembly, not total word count

    Monthly token totals do not locate the layer. Per request, log shares for system prompt, history, memory recall, tool results, and model output. A sudden spike in one class means that policy failed. Rising memory share usually means recall count or summary length has no cap; rising tool-result share usually means trimming failed or loops were not broken.

    Session- and user-level budgets help: near a threshold, force-compress working memory, defer non-critical tools, or ask whether to keep digging. Retention by time and purpose: debug raw text short-lived; stable facts long-lived but revisable; sensitive raw text off the recall index by default. These are general engineering practices, not product-specific APIs.

    From a demo that runs to a workflow that holds

    Demos have short context, few tools, and no multi-day constraints, so the problems stay hidden. In real work, state lengthens, recall gets noisy, tools multiply, and forgetfulness and duplicate calls show up together. What matters first is not “another agent project” but the same underlying issues: which memory layer stores what, how context is compressed, how history is recalled under a budget, and which segment the tokens go to. Measure those four, then talk about model capability—debugging has layers, and cost stays governable.