Step Limits
Part of the Tools and Agents section of Coddy's AI Engineering journey. Lesson 9 of 22.
An agent loop ends when the model stops asking for tools, and nothing guarantees that it will. A tool that keeps failing with try again can make a model retry forever, and every pass costs a call and its tokens. Give the loop a limit:
steps = 1
while response.stop_reason == "tool_use":
if steps == MAX_STEPS:
break
# run the tools, append the turns, call the model again
steps += 1
if response.stop_reason == "tool_use":
print("Gave up: the task took too many steps")The check sits at the top of the loop, so the program never makes call number MAX_STEPS + 1. After the loop, the stop reason tells you which way it ended: still tool_use means the limit stopped it and there is no answer to show. Tell the user so instead of printing nothing. Retries are often right: a service that times out once may answer on the next try. The limit lets the loop retry and still end. Production agents also cap tokens and time the same way.
Challenge
MediumThe restaurant agent in the starter runs forever when a booking system keeps failing, because the model retries each time. Add a step limit.
- At the top of the loop,
breakwhenstepsequalsMAX_STEPS. - After the loop, if the stop reason is still
"tool_use", printStopped: no answer after 5 steps(useMAX_STEPS). - Keep printing the answer, when there is one, and the steps.
For example, for the input Is there a table at Golden Dragon tonight? the program prints:
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Stopped: no answer after 5 steps
Steps: 5Try it yourself
import coddy_ai as anthropic # in production: import anthropic
client = anthropic.Anthropic()
MAX_STEPS = 5
TABLES = {"Bella Vista": "a table for two at 8 pm", "Sunset Grill": "a table by the window at 9 pm"}
attempts = {}
def check_table(restaurant):
attempts[restaurant] = attempts.get(restaurant, 0) + 1
if restaurant == "Golden Dragon":
raise TimeoutError("The booking system is temporarily unavailable, try again")
if restaurant == "Sunset Grill" and attempts[restaurant] < 3:
raise TimeoutError("The booking system timed out, try again")
if restaurant in TABLES:
return f"{restaurant} has {TABLES[restaurant]}"
return f"{restaurant} has no free table tonight"
TOOLS = [
{
"name": "check_table",
"description": "Check if a restaurant has a free table tonight",
"input_schema": {
"type": "object",
"properties": {"restaurant": {"type": "string", "description": "The restaurant name"}},
"required": ["restaurant"],
},
}
]
def run_tool(block):
try:
output = check_table(**block.input)
except TimeoutError as error:
print(f"Tool: {block.name} {block.input} -> error: {error}")
return {"type": "tool_result", "tool_use_id": block.id, "content": str(error), "is_error": True}
print(f"Tool: {block.name} {block.input} -> {output}")
return {"type": "tool_result", "tool_use_id": block.id, "content": output}
request = input()
messages = [{"role": "user", "content": request}]
# Stop the loop when it has called the model MAX_STEPS times
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
steps = 1
while response.stop_reason == "tool_use":
messages.append({"role": "assistant", "content": response.content})
results = [run_tool(block) for block in response.content if block.type == "tool_use"]
messages.append({"role": "user", "content": results})
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
steps += 1
for block in response.content:
if block.type == "text":
print("Answer: " + block.text)
print(f"Steps: {steps}")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Tools and Agents
Practice on your own: Online Python compiler