Sub topic 14
Step Limits, Cost, and Latency
This chapter assumes you have read the earlier chapters. You should know how a tool definition works and how the loop runs tool calls and returns results. You should also be comfortable with Python and chat-style message lists. Here you will learn what a tool loop costs, why it can be slow, and how to bound it.
Why a loop needs limits
The model decides whether to call another tool. Your code does not control that decision. A model can keep calling tools for many reasons:
- It repeats the same call because the result did not answer its question.
- It retries a failing call with the same bad arguments.
- It searches a large space one item at a time.
- A tool result tricks it into doing more work (see the security chapter).
Without a limit, any of these can run until you hit a provider rate limit or a large bill. The max_steps argument in run_agent is the first guard. This chapter explains how to pick its value and which other limits to add.
What one step costs
A step is one call to the model plus the tool calls that follow it. Each step re-sends the whole message list. The model has no memory between requests, so every request carries the system prompt, the tool definitions, the user message, and every earlier assistant message and tool result.
That makes input tokens grow with each step. Suppose the fixed part of a request (system prompt plus tool definitions) is 1,500 tokens. Suppose each step adds about 500 tokens of assistant text and tool output.
| Step | Input tokens sent | Running total of input tokens |
|---|---|---|
| 1 | 1,500 | 1,500 |
| 2 | 2,000 | 3,500 |
| 3 | 2,500 | 6,000 |
| 4 | 3,000 | 9,000 |
| 5 | 3,500 | 12,500 |
Five steps do not cost five times the first step. They cost more than eight times as much here, because each request repeats everything before it. Total input grows roughly with the square of the step count when results are large. Output tokens are billed separately and usually at a higher rate, but they stay small unless the model writes long text.
Some providers offer prompt caching. It lets repeated prefixes, such as the system prompt and tool definitions, be billed at a lower rate. It helps most in loops, because the prefix is identical on every step. Check your provider's rules. Caching often requires the prefix to be byte-identical, so do not reorder tools or edit the system prompt between steps.
Why latency adds up
Each step is a network round trip to the model followed by your tool's own run time. These are sequential, because the model needs a result before it can decide the next call. A loop of four steps with a 2-second model call and a 1-second tool takes about twelve seconds, including the final answer step.
Latency has three sources:
- Model time per step. It grows with input size and with the number of output tokens.
- Tool time. A slow database query or web request blocks the whole loop.
- Step count. This is the multiplier, and the one you control most directly.
To reduce latency, cut steps first. Combine tools that are always called together, return enough data in one result, and run independent calls from the same turn at the same time (covered in the parallel calls chapter).
Setting limits
Use several limits, because each one catches a different failure.
| Limit | What it stops | Typical use |
|---|---|---|
| Max steps | Endless looping | 5 to 10 for most tasks |
| Max tool calls per task | A turn that proposes many parallel calls | A fixed cap, such as 20 |
| Wall-clock deadline | A slow tool or provider | Seconds to a few minutes |
| Token budget | Growing context and cost | Fraction of the model's context window |
| Per-tool timeout | One hung function | 5 to 30 seconds |
| Repeat detection | Identical calls that never help | Stop after 2 repeats |
Pick max_steps from the task. Look at how many tool calls a correct run needs, then add a small margin. If the longest legitimate task takes three steps, a limit of 6 leaves room for one retry. A limit of 50 hides bugs, because a looping model burns money before anyone notices.
A loop with budgets
The loop from earlier chapters only checks max_steps. The version below adds a deadline, a cap on total tool calls, and repeat detection. It reuses the idea of run_tool_call from the dispatcher chapter, so a small stand-in is included to keep the code runnable. call_model is still your provider's SDK call.
import json
import time
def run_tool_call(call):
return {"is_error": False, "content": json.dumps({"ok": True})}
class LoopLimitError(RuntimeError):
pass
def run_agent_limited(call_model, messages, max_steps=6,
max_tool_calls=12, deadline_seconds=60):
started = time.monotonic()
tool_calls_made = 0
seen = {}
for step in range(1, max_steps + 1):
if time.monotonic() - started > deadline_seconds:
raise LoopLimitError("Deadline exceeded at step " + str(step))
reply = call_model(messages)
messages.append(reply)
calls = reply.get("tool_calls", [])
if not calls:
return reply["content"]
tool_calls_made += len(calls)
if tool_calls_made > max_tool_calls:
raise LoopLimitError("Too many tool calls: " + str(tool_calls_made))
for call in calls:
key = call["name"] + json.dumps(call["arguments"], sort_keys=True)
seen[key] = seen.get(key, 0) + 1
if seen[key] > 2:
outcome = {
"is_error": True,
"content": "You already made this call twice. "
"Use the earlier results or answer the user.",
}
else:
outcome = run_tool_call(call)
messages.append({
"role": "tool",
"tool_call_id": call["id"],
"content": outcome["content"],
})
raise LoopLimitError("No final answer within " + str(max_steps) + " steps")Two details matter here. First, every tool call gets a result message even when the call is refused, because most providers reject a conversation where a tool call has no matching result. Second, the repeat check sorts keys with sort_keys=True, so the same arguments in a different order count as the same call.
What to do when a limit is hit
Raising an exception is the simplest choice, but it throws away the work done so far. You have three better options, depending on the product:
- Force a final answer. Make one more model call with tools disabled (see the tool choice chapter) and a message such as "Answer with what you have." The user gets a partial answer instead of an error.
- Report the limit honestly. Tell the user the task was not finished and what was completed. Do not let the model claim it succeeded.
- Log the whole message list. A limit hit is a bug report. The trace shows whether the model looped, a tool failed, or the limit was too low.
Keeping cost down in each step
Steps are the multiplier, but the size of each step matters too. These changes help most:
- Trim tool results. Return the fields the model needs, not the whole database row or web page. Cap result length, and say so in the result, for example "truncated to 20 of 340 rows".
- Keep tool definitions short. Every tool you register is sent on every request. Twenty tools with long descriptions can add thousands of tokens per step. Offer only the tools relevant to the task.
- Drop old results. In long sessions, replace large results from early steps with a short summary once the model has used them. Keep the assistant's tool call and a tool message for it, so ids still match.
- Use a smaller model for easy steps. Routing simple lookups to a cheaper model works if the choice is made in your code, not by the model.
- Cache tool results. If the same read-only call repeats, return the stored result. Only cache calls without side effects.
Measuring a run
You cannot tune what you do not measure. Record these values for every run:
- Step count and tool-call count
- Input and output tokens per step (providers return them in the response's usage field)
- Time spent in the model and time spent in tools
- Which limit ended the run, if any
A short summary function shows the shape of it:
def summarize(steps):
total_in = sum(s["input_tokens"] for s in steps)
total_out = sum(s["output_tokens"] for s in steps)
model_s = sum(s["model_seconds"] for s in steps)
tool_s = sum(s["tool_seconds"] for s in steps)
return {
"steps": len(steps),
"input_tokens": total_in,
"output_tokens": total_out,
"model_seconds": round(model_s, 2),
"tool_seconds": round(tool_s, 2),
}
print(summarize([
{"input_tokens": 1500, "output_tokens": 40, "model_seconds": 1.8, "tool_seconds": 0.4},
{"input_tokens": 2000, "output_tokens": 60, "model_seconds": 2.1, "tool_seconds": 0.0},
]))Compare the two time figures. If tool time dominates, speed up the tools or run them in parallel. If model time dominates, shrink the context or cut steps.
Common errors
- Setting no deadline. A step limit alone does not bound time. One hung HTTP call stalls the loop forever, so give each tool a timeout.
- Counting only steps. A single turn can propose many parallel calls, so cap total tool calls too.
- Retrying without change. Return an error that tells the model what to change. A bare "failed" invites the same call again.
- Leaving out a result message. Skipping the result for a refused call breaks the message pairing and the next request fails.
- Ignoring the growth in context. A loop that works at 3 steps may exceed the context window at 15, so track tokens as well as steps.
Exercises
Exercise
A request has 2,000 fixed tokens (system prompt and tool definitions). Each step adds 600 tokens of messages and tool results. How many input tokens in total are sent across 4 steps?
Show answer
Step 1 sends 2,000, step 2 sends 2,600, step 3 sends 3,200, and step 4 sends 3,800. The total is 11,600 input tokens. This is more than four times the first request because each step re-sends all earlier messages.
Exercise
Your loop has max_steps=6 but a user report shows one request ran for several minutes without hitting the limit. Name two likely causes and one fix for each.
Show answer
First, a tool call hung or ran slowly, because a step limit does not bound time. Fix it with a per-tool timeout and a wall-clock deadline. Second, a single turn proposed many parallel calls, each slow or numerous, so the work per step was large. Fix it with a cap on total tool calls and by running independent calls concurrently with timeouts.
Exercise
The model asks for the same search with the same arguments three times. In the loop above, what happens on the third call, and why does the code still append a tool message?
Show answer
The repeat counter passes 2, so the code skips running the tool and returns an error result telling the model to use earlier results or answer. It still appends a tool message because the provider expects a result for every tool call id, and a missing result makes the next request fail.