Course contents · Lesson 6 of 16

Build a Simple AI Agent Loop in Python

Structured Output and Tools · Lesson 6 of 16 · 12 min Hands-on

Ask a new teammate "Which of our policy pages covers refunds, and what does it say?" and they open the shared folder, scan the file names, open the likely file and read it before they reply. A simple AI agent works the same way: a model picks the next action, your program carries it out, and the two repeat until the question is answered. You will build one in Python, with two read-only file tools and safety rails.

An agent is the tool loop, repeated

In lesson 5 the model asked for a tool, your script ran it and sent the result back with role tool, and the model answered. An agent is the same loop left running until the goal is reached: each reply either asks for more tools or is the final answer.

Each pass is a step: one model call plus the tools it asks for. The model decides what happens next, so the number of steps is unknown in advance and your code needs a limit. Notice the flowchart's two exits: a final answer, which the model chooses, and the step limit, which your code enforces.

Flowchart. The goal goes to the model with POST /api/chat. Does the reply have tool_calls? No: it is the final answer, the goal is reached and the loop stops. Yes: check and run the tools list_files and read_file, append the results with role tool, then ask whether the step number is below MAX_STEPS. Yes: call the model again for the next step. No: stop with a message, MAX_STEPS reached. Every step writes one log line, for example [step 2] read_file with path returns-and-refunds.md.
The loop has two exits: the model ends it with a plain answer, or your code ends it at MAX_STEPS.

The loop in about 40 lines of Python

The lab's run_agent() is the flowchart in code. It starts a messages list with a system prompt and the goal, calls the model, and checks the reply for tool_calls as lesson 5 did. What is new is the for loop around it, capped at max_steps. With its ask() helper and the repeat check it is about 40 lines. The core, simplified:

def run_agent(goal, model, max_steps, read_timeout):
    messages = [{"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": goal}]
    for step in range(1, max_steps + 1):
        message = ask(model, messages, read_timeout)
        tool_calls = message.get("tool_calls") or []
        if not tool_calls:
            print(f"[step {step}] answer: the model replied with text")
            return (message.get("content") or "").strip()
        messages.append(message)
        for call in tool_calls:
            name = call["function"]["name"]
            arguments = call["function"].get("arguments") or {}
            result = run_tool(name, arguments)    # allow-list, then argument checks
            print(f"[step {step}] {name} {json.dumps(arguments)} -> {summarize(result)}")
            messages.append({"role": "tool", "tool_name": name,
                             "content": json.dumps(result)})
    return None                                   # the step limit came first

Read it as the checklist: the history gains a request and a result per tool call, and the model re-reads it all on the next call, so it sees which steps are done. The system prompt says it works in a loop: list the files, read the right one, answer with a quote, as Ollama's tool-calling docs suggest.

This lab uses a second model, qwen2.5:3b. A chat template is the pattern Ollama uses to turn your messages and tools into one prompt. The llama3.2:3b template places the tool list only next to the newest user message, so once a tool message is newest, the model no longer sees its tools. Qwen 2.5's template puts them in the system prompt, sent on every call.

A tool registry fenced into one folder

A tool registry is a dictionary from tool names to the functions that do the work. The lab has two tools, and both only read: list_files returns the file names, and read_file returns one file's text. Both are fenced into one folder, the sandbox: the lab's sandbox/ holds four short pages from a made-up tea shop.

def inside_sandbox(path_text):
    full = (SANDBOX / path_text).resolve()
    if not full.is_relative_to(SANDBOX):
        raise ToolError(f"{path_text!r} is outside the sandbox folder")
    return full

TOOLS = {"list_files": (list_files, NoArgs), "read_file": (read_file, ReadFileArgs)}

Each entry pairs a function with a pydantic class that checks its arguments, as in lesson 5. The path check matters because a model writes the path: resolve() turns ../agent.py, an absolute path or a symbolic link (a file that points elsewhere) into the real location, and is_relative_to refuses anything outside sandbox/. In the box diagram, notice that files are reached only through the registry.

Box diagram of agent.py. In the middle, the agent loop run_agent(): call the model, run the tool calls, append the results, repeat or stop, with MAX_STEPS = 6. Below it, the Ollama model qwen2.5:3b on port 11434 receives the history and tools and sends a reply. On the right, the tool registry TOOLS, the allow-list, with list_files(), which returns the file names, and read_file(path), which returns one file's text. Below the registry, the sandbox folder with returns-and-refunds.md, shipping.md, contact.md and opening-hours.md; the tools only read it and paths with ../ are refused. On the left, the step log: step 1 list_files, 4 files; step 2 read_file, 15 lines; step 3 answer.
The model only chooses; every file it sees passes through the registry and the sandbox check.

Safety rails, then a run

A safety rail is a limit in your code that holds whatever the model writes. The lab has five:

  • Step limit: MAX_STEPS, an environment variable (a setting the shell hands to the program), default 6.
  • Allow-list: the registry. A name not in TOOLS gets an unknown tool error and never runs.
  • Argument checks: unknown or empty arguments and paths outside the folder are refused.
  • Repeat check: the same call with the same arguments gets a repeated call error instead of running again.
  • Step log: one line per tool call and one for the answer.

Every refusal goes back to the model as the tool result, so it can correct itself on the next step.

Run the lab

With Ollama from lesson 1 running, pull the second model once (about 1.9 GB) in the 01-ollama-setup folder. Then move to the agent's folder, make a virtual environment as in the last two labs, and give the agent its goal:

docker compose exec ollama ollama pull qwen2.5:3b
cd ../06-agent-loop
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
python3 agent.py 'Which file mentions the refund policy and what does it say?'

The pull should end with success. The agent then prints its log; the model's choices and wording can differ:

Goal: Which file mentions the refund policy and what does it say?
Model: qwen2.5:3b | MAX_STEPS=6 | tools: list_files, read_file | folder: sandbox/
[step 1] list_files {} -> 4 files: contact.md, opening-hours.md, returns-and-refunds.md, shipping.md
[step 2] read_file {"path": "returns-and-refunds.md"} -> 15 lines of returns-and-refunds.md
[step 3] answer: the model replied with text
Answer: It is in returns-and-refunds.md: "You can return unopened tea within 30 days of delivery for a full refund." ...

It worked if list_files comes before read_file, the file read is returns-and-refunds.md, and the quote really is in that file. HTTP 404 with not found means the pull did not finish; cannot connect to Ollama means the container is stopped.

Table of a sample run for the goal: Which file mentions the refund policy and what does it say? Step 1: the model asks for a tool, list_files, with no arguments, and gets 4 file names including returns-and-refunds.md. Step 2: it asks for read_file with path returns-and-refunds.md and gets 15 lines, the refund policy and how to send a return. Step 3: it replies with text, no tool; the final answer names the file and quotes the policy. With MAX_STEPS=1, step 1 runs list_files and the loop stops with a message. Marked illustrative.
The answer comes only after a read_file step fetched the text it quotes.

Where it breaks, and what to change

Looping on the same call. One tool with the same arguments, step after step, answered by error: repeated call, until Stopped: reached MAX_STEPS. The model is not using the result, often because it was long or unclear. Keep results short and plain, and keep MAX_STEPS low so a loop costs seconds.

Picking the wrong tool. A read_file with a guessed name such as refunds.txt before any list_files, or an unknown tool error. Say in each tool's description when to use it, and write errors that name the fix: the lab's ends call list_files to see the names.

Drifting off the goal. The agent reads files that do not matter, or answers before any read_file line, so its "quote" cannot come from a file. Restate the goal in the system prompt, offer fewer tools, and check that every quote is in a file read_file returned.

The model matters too: with the template difference above, --model llama3.2:3b may answer straight after list_files, which is drift. Measuring quality over many questions comes in lesson 11.

Check yourself

The log shows read_file with the same path at steps 2, 3 and 4. What is happening, and what keeps it from running forever?

The model is looping instead of using the result it has. The repeat check refuses the later runs and MAX_STEPS ends the loop; both live in your code, so they hold however often the model asks.

Why does read_file resolve the path before checking it, instead of refusing text that starts with ".."?

A path can escape in many spellings: notes/../../agent.py, an absolute path or a symbolic link. Resolving first gives the real location, so one check covers them all.

The answer quotes a refund rule, but the log has no read_file line. Should you trust the quote?

No. The tools returned only file names, so the model never saw the policy and invented the quote. An agent's facts can only come from its tool results.

Go deeper