A loop with a step limit
The same loop as a function. The second fake model asks for the same tool forever.
The tool loop is: send the conversation and the tools, run any tool calls the model returns, append the results as tool messages, and ask again until the model answers in plain text. A step limit stops a model that never finishes.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write run_loop(script, registry, max_steps) that returns the final text of the first scripted message without tool_calls, running each call with registry[name](args), and returns None if max_steps is reached. Messages in script use the real shape.
Write count_steps(messages) that returns how many assistant messages a message list contains.
Explain it without notes
Describe the tool-call loop step by step.
Why must the assistant message be appended before the tool message?
Why does every tool loop need a step limit, and what should happen when it is reached?
Expected output
a model that finishes:
finished at step 2
answer: 31 C in Pune.
a model that never stops asking:
stopped: step limit 3 reached
answer: (none)