Sub topic 4
Why an agent loop costs more than one request
This chapter assumes you can read basic Python and know how input and output tokens are priced. It also assumes you have used a coding agent that calls tools such as file reads and shell commands. Earlier chapters covered tokens, the context window, and per-token prices. Here you will see how those parts combine into the cost of a whole agent session.
One request versus a loop
A single request has one cost: input tokens times the input rate, plus output tokens times the output rate. A coding agent does not make one request. It runs a loop:
- Send the context to the model.
- The model replies with text, or with a tool call such as "read this file" or "run the tests".
- The harness runs the tool and appends the call and its result to the context.
- Send the whole context again.
The loop ends when the model stops calling tools or hits a limit. A task that feels like one request to you may be 20 or 60 model calls.
The API is stateless. The model remembers nothing between calls, so the harness must resend the system prompt, the tool definitions, your messages, every earlier tool call, and every earlier result on each turn. Each turn is billed as a complete request.
The cost formula for a loop
Take these quantities:
sis the tokens in the fixed part of the context (system prompt, tool definitions, your task).tis the tokens each turn adds (the model's tool call plus the tool result).nis the number of turns.
The context on turn i, counting from 0, is s + t*i. Summing over all turns gives the total input tokens billed:
total_input = n*s + t * n*(n-1)/2The first term grows linearly with turns. The second term grows with the square of the number of turns. A long loop is therefore dominated by the second term, which is the history you keep paying to resend.
Computing it
The function below is the loop from the plan, extended with prices so you get a dollar figure. It assumes no caching. The prices are placeholders, not real rates.
def request_cost(usage, price):
"""Cost in USD of one request. Prices are USD per million tokens."""
return (
usage["input_tokens"] * price["input"]
+ usage["output_tokens"] * price["output"]
) / 1_000_000
def loop_input_tokens(system_tokens, step_tokens, turns):
"""Total input tokens billed across an agent loop with no caching."""
total = 0
context = system_tokens
for _ in range(turns):
total += context # the whole context is sent on every turn
context += step_tokens # each turn adds a tool call and its result
return total
def loop_cost(system_tokens, step_tokens, turns, output_per_turn, price):
"""Total USD for the loop. step_tokens already includes the model's output."""
usage = {
"input_tokens": loop_input_tokens(system_tokens, step_tokens, turns),
"output_tokens": output_per_turn * turns,
}
return usage, request_cost(usage, price)
# Placeholder prices, not real rates. Use your provider's current price list.
price = {"input": 3.0, "output": 15.0}
usage, cost = loop_cost(5_000, 2_000, 20, 400, price)
print(usage) # {'input_tokens': 480000, 'output_tokens': 8000}
print(round(cost, 2)) # 1.56The final context in this run is only 45,000 tokens, yet 480,000 input tokens were billed. Output was 8,000 tokens. At these placeholder rates, input costs $1.44 and output costs $0.12, so input is about 92% of the bill. Output tokens cost more per token, but there are far fewer of them. In an agent loop, the resent input usually dominates the bill.
How cost scales with turns
Now vary only the number of turns, keeping s = 5,000 and t = 2,000.
def closed_form(s, t, n):
return n * s + t * n * (n - 1) // 2
for n in (5, 10, 20, 40):
tokens = closed_form(5_000, 2_000, n)
assert tokens == loop_input_tokens(5_000, 2_000, n)
print(n, tokens, round(tokens * 3.0 / 1_000_000, 2))| Turns | Input tokens billed | Input cost at $3 per million |
|---|---|---|
| 5 | 45,000 | $0.14 |
| 10 | 140,000 | $0.42 |
| 20 | 480,000 | $1.44 |
| 40 | 1,760,000 | $5.28 |
Doubling the turns from 20 to 40 multiplies the cost by about 3.7, not 2. A model that wanders for 40 turns costs far more than two focused 20-turn sessions. That is why step limits and early stopping, covered in a later chapter, matter more than they first appear.
Which term do you control?
Each parameter in the formula points at a different lever.
s, the fixed prefix. A large system prompt, many tool definitions, or a long project instruction file is paid for on every turn. Cutting 2,000 tokens fromssaves 2,000 tokens timesn.t, tokens per step. Tool output is usually the biggest part oft. Whole-file reads, long test logs, and verbose build output all inflate it. A token that enters the context early is billed on every remaining turn.n, the number of turns. Every extra turn adds a full context's worth of input, and that context is larger the later the turn happens. Wasted turns late in a session are the most expensive ones.- The price per token. This is the only factor a cheaper model changes. It does not change
s,t, orn, and a weaker model may need more turns.
A useful consequence: a token's cost depends on when it enters the context. A 4,000-token tool result on turn 3 of a 20-turn loop is billed 17 more times after it first appears. The same result on turn 19 is billed only once more.
What caching changes
Most providers can bill a repeated, unchanged prefix at a fraction of the normal input rate. Later chapters cover the details, but you can already see its effect on the loop. This variation assumes each turn's context shares everything with the previous turn's context except the new step. It also uses a placeholder multiplier of 0.1 for cached reads and ignores any extra charge for writing the cache.
def loop_effective_input_tokens(system_tokens, step_tokens, turns, cache_read_multiplier):
"""Input tokens weighted by price, counting cached reads at a fraction."""
total = system_tokens # turn 0: nothing cached yet
context = system_tokens + step_tokens
for _ in range(1, turns):
cached = context - step_tokens # everything from the previous turn
total += step_tokens + cached * cache_read_multiplier
context += step_tokens
return total
effective = loop_effective_input_tokens(5_000, 2_000, 20, 0.1)
print(effective) # 86700.0
print(round(effective * 3.0 / 1_000_000, 2)) # 0.26The effective input falls from 480,000 to 86,700 tokens, and the input cost from $1.44 to $0.26. The loop is still growing. Caching only lowers the rate paid on the part that repeats. Caching also depends on the prefix staying byte-for-byte identical, so anything that edits earlier context breaks it.
Common mistakes when estimating
- Pricing the final context once. The 45,000-token final context suggests about $0.14 of input. The real figure is $1.44. Always sum over turns.
- Counting only output tokens. Output is the visible text, so it feels like the cost. In a loop, it is the smaller part.
- Ignoring parallel tool calls. A model that issues several tool calls in one turn adds several results to the context but pays for only one resend. Turns, not tool calls, drive the quadratic term.
- Forgetting hidden prefix tokens. Tool definitions and harness instructions count toward
seven though you never typed them. - Using the average turn count. Loop length has a long tail. A few runaway sessions can account for most of your spend, because cost grows faster than linearly with turns.
Reading the formula as a diagnosis
When a session costs more than expected, work through the terms in order:
- Check
n. Look for repeated failing commands or the model re-reading the same file. - Check the largest items in
t. Find the tool results that were biggest and ask whether a scoped read or a truncated log would have worked. - Check
s. Measure the prefix before any work starts. - Only then compare per-token prices across models.
The order reflects leverage. Turns and tool output usually offer larger savings than a price change, and they apply on any model.
Exercise
An agent session has a fixed prefix of 8,000 tokens. Each turn adds 1,500 tokens. The loop runs 30 turns with no caching. How many input tokens are billed in total, and what is the input cost at a placeholder rate of $3 per million input tokens?
Show answer
Use total_input = ns + tn(n-1)/2 with n=30, s=8,000, t=1,500. The first term is 308,000 = 240,000. The second term is 1,500 (3029/2) = 1,500 435 = 652,500. The total is 892,500 input tokens. The cost is 892,500 3 / 1,000,000 = $2.6775, about $2.68. Note that the history term (652,500) is larger than the fixed-prefix term (240,000), even though the final context is only 8,000 + 30*1,500 = 53,000 tokens.
Exercise
Two sessions solve the same task. Session A takes 20 turns with 2,000 tokens added per turn. Session B takes 40 turns with 1,000 tokens added per turn. Both use a 5,000-token prefix. Which session bills more input tokens, and why is the answer not obvious from the final context size?
Show answer
Both end with a final context of 45,000 tokens (5,000 + 202,000 and 5,000 + 401,000). Session A bills 205,000 + 2,000190 = 480,000 input tokens. Session B bills 405,000 + 1,000780 = 980,000 input tokens. Session B costs about twice as much because it resends the context on twice as many turns. The number of turns matters as much as the size of each step.