Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.2 — The Tool-Call Loop by Hand
LLM Engineering · Example 2 of 2

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.

01

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.

02

Write count_steps(messages) that returns how many assistant messages a message list contains.

Explain it without notes

01

Describe the tool-call loop step by step.

02

Why must the assistant message be appended before the tool message?

03

Why does every tool loop need a step limit, and what should happen when it is reached?

A loop with a step limit
Sign in to run this example in your browser.

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)