Stop the Runaway Agent

capping iterations and recovering from tool errors

Part of: Tool-Using Agent

A validated tool call still isn't a safe agent. Two failure modes remain, and both are about the loop, not a single call. The loop can run forever, and a tool can raise an exception mid-execution instead of returning a bad result. Failure 1: the loop never stops Nothing in the loop from lesson 5 guarantees the model ever reaches stop reason == "end turn". A confused model can call tools back to back forever, chasing an answer it never lands on, and every pass costs real tokens and real money. The fix is a hard ceiling: The for i in range(MAX ITERATIONS) replaces while True. If the model still hasn't finished after 8 tool calls, you stop on your own terms with a clear message instead of an unbounded bill. Failure 2: the tool itself throws Lesson 6 caught bad input. But a tool can fail for reasons that have nothing to do with the arguments: a weather API can be down, a network call can time out. safe execute should catch exceptions raised during execution, not only reject malformed input beforehand: That error string flows back as a normal tool result. The model sees that the weather tool failed and can apologize, try a different tool, or answer without it, instead of your whole prog

Challenge: Cap the Runaway Agent