AI Agents in Practice: From One Model Call to a Production System
Part 2
〇二Why Agents Get Slower the Longer They Run
The input of a single request grows linearly with the number of rounds; the cumulative input of the task grows with its square
The debugging task in the previous article ran for only 4 rounds. Put the same loop on a task that needs 50 rounds and this happens: the model call in round 1 takes about 5.6 seconds, round 30 about 12.8 seconds, round 50 about 17.8 seconds. Every round does the same kind of work, reading one tool result and deciding the next step, yet each is a little slower than the last.
These figures come from the simulation later in this article, and its parameters are assumptions. The exact seconds change with the model and the provider; the trend does not. To explain it, first take the time apart.
Splitting total time into four parts
On a serial execution path, the total time of an Agent task can be approximated as:
T_total ≈ T_LLM + T_tools + T_orchestration + T_waiting
T_LLM: the sum of all model calls;T_tools: the sum of all tool runs, such as reading files, querying databases or calling external HTTP endpoints;T_orchestration: orchestration overhead, the runtime's own time: building the message list, serializing it to JSON, parsing the tool-call arguments the model returned, validating, saving task state;T_waiting: time spent neither computing nor running tools, such as request queueing and backoff after hitting a rate limit (the provider rejecting requests beyond quota, HTTP status 429).
"Serial" means each step finishes before the next starts. When several tools run concurrently their times overlap, so the total follows the critical path (the longest dependency chain, which sets the finish time) rather than a plain sum; that is Article 29.
T_LLM splits further:
T_LLM ≈ T_network + T_queue + T_prefill + T_decode
T_network is the round trip of request and response over the network; T_queue is the time the request waits on the server for a free GPU. The remaining two need their own explanation.
Inside a model call: prefill and decode
A large language model produces an answer in two phases.
In prefill, the model reads the whole input at once, computes for every input token the intermediate results the attention mechanism needs, and keeps them. Those intermediate results are the KV cache (key-value cache): attention (the computation by which the model, while generating each token, looks back over the preceding text and weighs how relevant each position is) needs a "key" and a "value" vector for every existing token, and keeping them avoids recomputing them.
In decode, the model produces output tokens one at a time; each one reads the whole KV cache and then appends its own key and value.
The two phases load the hardware differently. Prefill computes all input tokens in parallel, is limited mainly by compute, and takes longer as the input grows; decode produces one token per step, is limited mainly by memory bandwidth, and its time depends mostly on output length. The papers DistServe and Splitwise both start from this difference and run the two phases on different GPUs.
For an Agent the distinction matters because the output of each round (a tool-call request, a short piece of reasoning) stays about the same length, while the input keeps growing with every round. What changes with the round count is mainly T_prefill.
Prefill time is not strictly proportional to input length. Attention's compute grows with the square of the length and the other layers grow linearly, and batching, hardware and server-side caches bend the curve differently for each service. The simulation below uses a linear approximation and is meant only to show the trend.
How the input grows when the full history is resent
The previous article's loop sends the complete message list on every request. Let:
S: the fixed part every request carries, i.e. the system prompt and tool definitions (each tool's name, description and parameter format), in tokens;G: tokens added per round, i.e. model output plus tool results;- no truncation and no compression.
The input length of request n is:
C_n = S + G·n
It grows linearly with n. But the input of all requests in the task adds up to:
C_total = Σ C_n = S·N + G·N(N+1)/2 (n from 1 to N)
The second term is quadratic in N. The reason is that each round's new content is processed more than once: round 1's tool result appears in all N−1 later requests, round 2's in N−2, and so on.
With S = 3,000 and G = 2,000, a script confirms it:
def simulate(rounds=50, system_tokens=3000, tokens_per_round=2000):
"""Token counts when the full history is resent on every request.
system_tokens: system prompt and tool definitions carried by every request
tokens_per_round: messages added per round (model output + tool results)
"""
cumulative = 0
for n in range(1, rounds + 1):
# request n = fixed part + all messages accumulated over n rounds
context = system_tokens + tokens_per_round * n
cumulative += context
if n % 10 == 0:
print(f"round={n:2d} context={context:>7,} cumulative={cumulative:>10,}")
if __name__ == "__main__":
simulate()
Output:
round=10 context= 23,000 cumulative= 140,000
round=20 context= 43,000 cumulative= 480,000
round=30 context= 63,000 cumulative= 1,020,000
round=40 context= 83,000 cumulative= 1,760,000
round=50 context=103,000 cumulative= 2,700,000
This matches the formula: at N = 50, 3,000 × 50 + 2,000 × 50 × 51 / 2 = 150,000 + 2,550,000 = 2,700,000.
The two curves answer two different questions. Per-request input answers "will this request exceed the context window" (the maximum number of tokens one request may carry). Cumulative input answers "how much did the model read over the whole task". Going from 10 rounds to 20, per-request input rises from 23,000 to 43,000, less than double; cumulative input rises from 140,000 to 480,000, 3.4 times. Monitoring only the size of individual requests hides the second kind of growth.
Turning tokens into seconds
Tokens are not time. The simulation below gives prefill and decode a rate, converts each round's input and output into seconds, and adds them up per phase:
def call_latency(input_tokens, output_tokens, cached_tokens=0,
network=0.15, queue=0.05,
prefill_tps=8000, decode_tps=60):
"""Estimate the time of one model call, in seconds.
prefill_tps: input tokens processed per second (assumed)
decode_tps: output tokens generated per second (assumed)
cached_tokens: input tokens that hit the prefix cache and need no recomputation
"""
prefill = (input_tokens - cached_tokens) / prefill_tps
decode = output_tokens / decode_tps
return {"network": network + queue, "prefill": prefill, "decode": decode}
def run(rounds=50, system_tokens=3000, tool_tokens=1700, output_tokens=300,
tool_seconds=0.4, use_cache=False):
"""Simulate an Agent that calls one tool per round; add up time per phase."""
totals = {"network": 0.0, "prefill": 0.0, "decode": 0.0, "tools": 0.0}
context = system_tokens
for n in range(1, rounds + 1):
# with caching, assume everything before the previous round hits the prefix cache
cached = context - (tool_tokens + output_tokens) if use_cache and n > 1 else 0
t = call_latency(context, output_tokens, cached_tokens=max(cached, 0))
for k, v in t.items():
totals[k] += v
totals["tools"] += tool_seconds
context += output_tokens + tool_tokens # this round's output and tool result enter the next round
if n in (1, 10, 30, 50):
per_call = sum(t.values())
print(f"round={n:2d} context={context - output_tokens - tool_tokens:>7,} "
f"prefill={t['prefill']:.2f}s call={per_call:.2f}s")
total = sum(totals.values())
share = " ".join(f"{k}={v:.1f}s({v / total:.0%})" for k, v in totals.items())
print(f"total={total:.1f}s {share}")
if __name__ == "__main__":
print("--- no cache ---")
run()
print("--- prefix cache ---")
run(use_cache=True)
Each round adds 2,000 tokens (300 output + 1,700 tool result), as in the previous section. Output without cache:
--- no cache ---
round= 1 context= 3,000 prefill=0.38s call=5.58s
round=10 context= 21,000 prefill=2.62s call=7.83s
round=30 context= 61,000 prefill=7.62s call=12.82s
round=50 context=101,000 prefill=12.62s call=17.82s
total=605.0s network=10.0s(2%) prefill=325.0s(54%) decode=250.0s(41%) tools=20.0s(3%)
Decode is fixed at 5 seconds per call (300 tokens ÷ 60 tokens/s), while prefill grows from 0.38 to 12.62 seconds. Over 50 rounds prefill adds up to 325 seconds, 54% of the total; tool execution is only 3%.
The result is sensitive to prefill_tps. Set it to 20,000 (a faster inference service) and the total drops to 410 seconds, prefill's share falls to 32%, and decode becomes the largest item. I did not use measured values for any particular model because rates differ widely between providers and times of day; the only way to know which side your system falls on is to measure it, as the last section of this article shows.
What prefix caching changes
Resending the full history has one property: most of request n is identical to request n−1. Prefix caching (prompt caching) exploits exactly that: the server keeps the KV cache it already computed for an input prefix, and if the next request begins with exactly the same content, that part skips prefill.
Turn on use_cache in the script above and assume only the 2,000 tokens added in the latest round need recomputing:
--- prefix cache ---
round= 1 context= 3,000 prefill=0.38s call=5.58s
round=10 context= 21,000 prefill=0.25s call=5.45s
round=30 context= 61,000 prefill=0.25s call=5.45s
round=50 context=101,000 prefill=0.25s call=5.45s
total=292.6s network=10.0s(3%) prefill=12.6s(4%) decode=250.0s(85%) tools=20.0s(7%)
Per-call time no longer grows with the round count, and the total falls from 605 to 293 seconds. That is the ideal case; real hit rates are bounded by a few conditions:
- The prefix has to match byte for byte. If the system prompt contains the current time, or the tool definitions come in a different order each time, the cache stops working from the first changed position. Article 04 comes back to this when it discusses the order a request is assembled in.
- Caches expire. Anthropic's documentation states a default lifetime of 5 minutes, refreshed on every hit, with a paid 1-hour option. If a tool runs longer than that, the next request recomputes the whole prefix.
- Caching reduces compute and cost, not tokens. The same documentation prices 5-minute cache writes at 1.25 times the base input price and reads at 0.1 times (lower for some models). OpenAI enables caching by default on supported models and likewise bills cache hits at a discount. The 2.7 million cumulative input tokens do not shrink; most of them are simply billed at a lower price.
Three problems caching does not solve
Even if every request hits the cache completely, a growing context brings three more problems.
First, the context window has a limit. At 2,000 tokens per round, a 128K window runs out around round 60. At that point the runtime has to truncate or compress, or requests are rejected.
Second, more information does not mean the model uses it better. The experiments in Lost in the Middle (Liu et al., 2023) show that when the key information sits in the middle of a long input, answer accuracy is clearly lower than when it sits at the beginning or the end. An Agent's early tool results are exactly what gets pushed toward the middle as rounds accumulate.
Third, the history contains stale content. The config file the Agent read in round 5 has been changed by the Agent itself by round 20; both versions remain in the context and the model has to work out which is current.
None of these is a performance problem; they are correctness problems. They are why context management cannot rely on caching alone, and the ten articles of part two (07 to 16) deal with them one by one.
Measuring: phase timers in the loop
The simulation above depends on assumed parameters. For a real Agent you need to measure where the time goes. The PhaseTimer below wraps each phase of the loop in a context manager (Python's with statement, which runs code automatically on entry and exit) and accumulates the time:
import time
from collections import defaultdict
from contextlib import contextmanager
class PhaseTimer:
"""Accumulate time per phase. A phase may be entered many times; the results add up."""
def __init__(self):
self.seconds = defaultdict(float)
self.counts = defaultdict(int)
@contextmanager
def phase(self, name):
"""Usage: with timer.phase("llm"): ... name is the phase name."""
start = time.perf_counter()
try:
yield
finally: # record the time spent even if the phase raises
self.seconds[name] += time.perf_counter() - start
self.counts[name] += 1
def report(self, wall):
"""wall: the task's wall-clock time, used to find the part no phase covered."""
covered = sum(self.seconds.values())
for name, sec in sorted(self.seconds.items(), key=lambda x: -x[1]):
print(f"{name:<14}{sec:6.2f}s {sec / wall:5.1%} n={self.counts[name]}")
print(f"{'(untracked)':<14}{wall - covered:6.2f}s {(wall - covered) / wall:5.1%}")
def demo():
"""Simulate 4 rounds with sleep: model 0.6s, tools 0.3s, context building 0.02s, one 0.5s rate-limit wait."""
timer = PhaseTimer()
start = time.perf_counter()
for step in range(4):
with timer.phase("orchestration"):
time.sleep(0.02) # build messages, serialize
if step == 2:
with timer.phase("waiting"):
time.sleep(0.5) # backoff after a 429
with timer.phase("llm"):
time.sleep(0.6)
if step < 3:
with timer.phase("tools"):
time.sleep(0.3)
timer.report(time.perf_counter() - start)
if __name__ == "__main__":
demo()
Typical output (the precision of sleep makes the last digit vary by a few milliseconds):
llm 2.42s 61.5% n=4
tools 0.91s 23.2% n=3
waiting 0.50s 12.8% n=1
orchestration 0.10s 2.4% n=4
(untracked) 0.00s 0.0%
The (untracked) line is wall-clock time minus every recorded phase. In a real system, if it is not close to zero, some code is not covered by a timer, for example log writes or saving state to a database.
Against a real API, split the llm phase one level further: the provider returns this call's token usage in the response's usage field. Anthropic reports input_tokens, cache_creation_input_tokens (the part written to cache) and cache_read_input_tokens (the part read from cache) separately; OpenAI's Responses API reports cache hits in usage.input_tokens_details.cached_tokens. Record these numbers and the time for every round and you can draw your own system's per-request input curve, cumulative input curve and cache hit rate, replacing the assumed parameters in this article.
Two metrics, watched separately
This article comes down to two metrics that need monitoring at the same time:
- input tokens per request: decides whether this request exceeds the window, and how long its prefill takes without a cache;
- cumulative input tokens per task: decides the task's total compute and cost, and grows with the square of the round count when the full history is resent.
Prefix caching can make the first metric's effect on time close to constant, but neither number itself goes down. To actually lower them, either less content enters the context each round, or old content leaves it. The former starts from tool results; the latter first requires knowing which parts of the history are still useful. The next article goes back to the message list itself: before deleting any message, you need to know which messages are bound together and cannot be split.