BeginnerCoder

Lesson 15 — The agent loop with a step limit

Think, act, observe — until done

Now the full loop. Each step: call the model; if it gives a final answer, stop; otherwise run the tool it asked for and add the result to the messages.

A model can get stuck and ask for tools forever. So every real agent has a step limit (max_steps): after that many steps it gives up with a clear message. A loop with no limit can run up a big bill with a real paid API, or freeze the program.

for turn in range(1, limit + 1):
    ...           # think, act, observe
return "gave up"   # only reached if no final answer

Why it matters: the step limit is the simplest and most important safety net an agent has.

Want it another way?
Task

Make the loop use max_steps instead of the fixed 10, and after the loop return "stopped: step limit reached".

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.