Knowing when to stop
Back in lesson 2 the loop stopped because the goal was close and every step landed exactly on it. Real agents aren't that tidy. The goal might be 1000 away while each step moves 100; the model might wander, repeat itself, or chase a target it can never reach. A loop whose only exit is "reached goal" will, on a hard task, run until it times out — and with a real model that's a metered API call billing you on every turn. An agent loop that can't stop isn't slow; it's a runaway cost.
So every real loop needs two stop conditions, not one. The first is the happy
path: reaching the goal. The second is the safety net: a step budget — a hard
ceiling maxSteps on how many turns the loop may take regardless of progress. The
loop halts on whichever fires first, and — this is the part beginners skip — it
records which one so the caller can tell success from a forced cutoff.
Walk it: goal 1000, step 100, budget 8. The agent steps to 100, 200, ... 800. After
the 8th step steps equals maxSteps while position is only 800 — still short of
1000. The goal check fails, the budget check fires, reason becomes "hit step budget,"
and the loop breaks with the work unfinished but the process safely terminated. In
production that distinction is everything: "reached goal" means ship it; "hit step
budget" means escalate, retry, or ask for help.
Below, replace the steps < 20 backstop logic with real guards. Inside the loop, stop
with reason = "reached goal" when position >= goal, and stop with
reason = "hit step budget" when steps >= maxSteps — then report it. "Done" is
exactly stopped: hit step budget (pos=800, steps=8).
Never write a loop you can't prove will end. The goal check is the plan; the step budget is the seatbelt — and reporting which fired is how anyone downstream knows whether the agent succeeded or just gave up.