Sub topic 14
Step limits, cost, and latency
This chapter assumes you have the tool-calling loop from the earlier chapters: a run_agent function that calls the model, runs the proposed tool calls with a dispatcher, appends the results, and repeats. Here you will see what that loop costs and how to bound it.
Why the loop needs bounds
The model decides when to stop calling tools. It can also get stuck. It may repeat the same failing call, or keep searching when it already has enough information. Without a bound, a stuck loop runs forever and you pay for every pass.
Where the cost comes from
Each pass through the loop is a full model request. Your code resends the whole message history every time, so each step carries everything the previous steps added. Input tokens grow with every step, and the total over a run grows faster than the step count.
Three things add to the history:
- Tool definitions, which are sent on every request.
- Tool results, which stay in the history for the rest of the run.
- The model's own tool-call messages.
A tool that returns a 20,000-character web page makes every later step more expensive. Trim results before appending them. Return only the fields the model needs, and cut long text with a clear marker such as [truncated].
Where the latency comes from
Latency is the sum of the following:
- One model call per step, which is usually the slowest part.
- The run time of each tool.
- Network overhead.
Steps happen in sequence because each depends on the previous result. Several independent calls in one turn can run together, as described in the parallel-calls chapter. One model call that asks for three tools is faster than three separate steps.
A bounded loop
This version adds a time limit and detection of repeated identical calls. It takes the dispatcher as an argument so it can run on its own.
import json
import time
def run_agent_bounded(call_model, run_tool_call, messages,
max_steps=5, max_seconds=30, max_result_chars=2000):
start = time.monotonic()
seen = set()
for _ in range(max_steps):
if time.monotonic() - start > max_seconds:
raise TimeoutError("Tool loop exceeded the time budget")
reply = call_model(messages)
messages.append(reply)
calls = reply.get("tool_calls", [])
if not calls:
return reply["content"]
for call in calls:
key = (call["name"], json.dumps(call["arguments"], sort_keys=True))
if key in seen:
content = "Repeated call with the same arguments. Use the earlier result or try something different."
else:
seen.add(key)
content = run_tool_call(call)["content"]
if len(content) > max_result_chars:
content = content[:max_result_chars] + " [truncated]"
messages.append({
"role": "tool",
"tool_call_id": call["id"],
"content": content,
})
raise RuntimeError("Tool loop did not finish within max_steps")Every tool call must still get a result with its tool_call_id, even a repeated one. Skipping the result makes most providers reject the next request.
Choosing the limits
| Limit | Typical starting point | What it protects against |
|---|---|---|
| Steps | 5 to 10 | Runaway loops and repeated failures |
| Wall-clock time | 30 to 60 seconds for interactive use | Slow tools and user timeouts |
| Result size | A few thousand characters | Growing input cost |
| Tool timeout | Set per tool | One slow tool blocking the run |
Measure real runs, then set the limits just above what normal tasks need. When a limit is hit, fail visibly. Log the messages so you can see why the loop did not finish.
Exercise
A run has five steps, and each tool result adds 1,000 tokens to the history. Why does the fifth model call cost more than the first, even if the tool definitions stay the same?
Show answer
Every call resends the whole history. By the fifth call, the input includes the four earlier tool results (about 4,000 extra tokens) plus the model's earlier messages. Trimming results or lowering the step count reduces this growth.