Agent Loops' O(N²) Cost: Why Bills Explode
Naive AI agent loops re-bill the entire conversation history on every call, causing input token costs to grow quadratically (O(N²)) with each step, leading to a 20-step agent run consuming over 10x the tokens a simple per-step estimate suggests.
The top 3
- O(N²) vs. Linear: Agent Costs Explode Faster: Quadratic (O(N²)) cost growth in AI agent loops means expenses increase by the square of the interaction steps, significantly outpacing linear (O(N)) or log-linear (O(N log N)) scaling seen in more efficient algorithms.
- Core Drivers of Agent Loop's Quadratic Cost: The 'N' in O(N²) for AI agent loops primarily represents the number of turns, agents, or the accumulating context window size. Each large language model (LLM) call often rebills the entire conversation history, including previous tool outputs and reasoning traces, leading to exponential token consumption.
- Top 3 Strategies to Tame O(N²) Agent Costs: Effective strategies to mitigate O(N²) costs include context optimization (e.g., sliding-window memory, summarization, or trajectory reduction like AgentDiet, which cut input tokens by 39.9%–59.7%), dynamic model routing (using smaller models for simpler tasks), and implementing aggressive retry limits and circuit breakers to prevent runaway loops.
Sources
Open the full topic