Give a model tools: the loop from scratch
Write the loop that lets a model call your functions, with no framework, so you know what every framework is doing for you.
You build: agent.py: about 80 lines that answer questions about a folder by listing and reading files.
- Python 3.11 or newer and uv
- An OpenRouter key (free models are enough), or Ollama with a model that supports tools
-
01Describe two tools to the model: list_dir and read_file
A tool is a name, a sentence and a JSON schema. The model never runs anything: it only asks.
uv run --with openai agent.py --once "Which files are in this folder?"You pass when: The script prints a tool call the model asked for (list_dir with a path) and stops. Nothing is executed yet.
-
02Run the tool the model asked for and send the result back
uv run --with openai agent.py --once "Which files are in this folder?"You pass when: Now the answer lists the real files in the folder.
-
03Loop until the model stops asking for tools, with a limit of 8 turns
The turn limit is your first safety control. Without it a confused model loops until your budget is gone.
uv run --with openai agent.py "Which file in this folder has the most lines, and how many?"You pass when: It lists the folder, reads several files, then names the right file. Check the number with wc -l.
-
04Print one line per step: who spoke, which tool, how many tokens
uv run --with openai agent.py --trace "How many Python files are here?"You pass when: A numbered trace prints before the answer, and reading a file that does not exist shows up as a tool error the model recovers from, not a crash.
The check runs on the computer, not on your word: a step passes when its command exits with 0 there.
Computers are not set up on this site yet. Run each command on your own machine and compare with "You pass when".
Commands run in labs/13-tool-loop and may take up to 60 seconds each. Every command starts a new shell: put keys and settings in a .env file there, it is loaded each time.