The Agent Loop

Updated · 7 min read
hardPython 3.13aiagentstool-usepythonllm-api

The agent loop is the code that turns a model with tools into an agent. It calls the model, runs the tool the model asks for, sends back the result, and repeats until the model gives a final answer or a limit is reached. It is the same loop you saw in "Tool Use and Function Calling", allowed to run for several steps.

This lesson builds the chapter's checkpoint: Campus Helper with two tools, look up a fee and book a meeting, asking for confirmation before booking.

Plan, Act, Observe, Repeat

Each step: the model chooses, the code acts, the result goes back
StageDescription
PlanIt is used by the model to choose the next tool, or to finish
ActIt is used by your code to run the chosen tool, after any checks
ObserveIt is used to send the tool's result back so the model can see what happened
Repeat or stopIt is used to continue until a final answer, a refusal or the step limit

Example: The Checkpoint Agent

Python
from model_api import ModelClient, tool_result
 
FEES = {(10, "lab"): 45, (10, "field trip"): 30, (11, "lab"): 50, (11, "field trip"): 35}
MAX_STEPS = 6  # stop runaway loops
 
def look_up_fee(grade, item):
    amount = FEES.get((grade, item.lower()))
    return f"${amount}" if amount is not None else "No fee found for that grade and item."
 
def book_meeting(day, time, topic):
    return f"Booked: {day} at {time} with the school office about {topic} (confirmation M-1042)."
 
def confirm(question):
    return input(f"{question} (yes/no) ").strip().lower() == "yes"
 
def schema(**fields):
    return {"type": "object", "properties": {k: {"type": t} for k, t in fields.items()},
            "required": list(fields), "additionalProperties": False}
 
TOOLS = [
    {"name": "look_up_fee", "parameters": schema(grade="integer", item="string"),
     "description": "Look up a school fee by grade (9-12) and item, such as lab or field trip."},
    {"name": "book_meeting", "parameters": schema(day="string", time="string", topic="string"),
     "description": "Book a meeting with the school office. Use only when the person asks for a meeting."},
]
 
def run_tool(name, args):
    if name == "look_up_fee":
        return look_up_fee(**args)
    if name == "book_meeting":
        if not confirm(f"Book {args['day']} at {args['time']} about {args['topic']}?"):
            return "The person declined, so nothing was booked."
        return book_meeting(**args)
    return f"Unknown tool: {name}"
 
client = ModelClient()
messages = [{"role": "user", "content": "What is the grade 10 lab fee? Then book me a meeting "
                                        "with the office on Thursday at 3 p.m. to talk about it."}]
 
for step in range(1, MAX_STEPS + 1):
    reply = client.chat(
        messages, tools=TOOLS, max_tokens=1000,
        system="You are Campus Helper. Use the tools. Never claim a booking the tool didn't confirm.",
    )
    messages.append(reply.message)
    if reply.finish_reason != "tool_calls":
        print("Campus Helper:", reply.text)
        break
    for call in reply.tool_calls:
        output = run_tool(call.name, call.arguments)
        print(f"[step {step}] {call.name} {call.arguments} -> {output}")
        messages.append(tool_result(call, output))
else:
    print("Stopped after", MAX_STEPS, "steps without finishing.")

Example output. The tool results, the confirmation question and the step log are real output of this code; at the question, the person typed yes. The model's choices and final reply were produced by an AI model on November 16, 2026, to show the shape; the program ran end to end against a local test server that returned them, not a live API.

Output
[step 1] look_up_fee {'grade': 10, 'item': 'lab'} -> $45
Book Thursday at 3:00 p.m. about the grade 10 lab fee? (yes/no) yes
[step 2] book_meeting {'day': 'Thursday', 'time': '3:00 p.m.', 'topic': 'the grade 10 lab fee'} -> Booked: Thursday at 3:00 p.m. with the school office about the grade 10 lab fee (confirmation M-1042).
Campus Helper: The grade 10 lab fee is $45. Your meeting with the school office is booked for Thursday at 3:00 p.m. (confirmation M-1042).

Explanation: Each pass through the for loop is one step. In step 1 the model asks for look_up_fee, and the code returns $45. In step 2 it asks for book_meeting; run_tool() first calls confirm(), and only books after the person types yes. In step 3 the model has everything it needs and answers, so finish_reason is no longer tool_calls and the loop ends. If the person types no, the tool returns "The person declined, so nothing was booked", and the model's reply says the meeting wasn't booked.

Stopping Safely

GuardDescription
Step limitIt is used to stop a confused agent from looping forever (MAX_STEPS)
Final answer checkIt is used to end the loop when finish_reason is not tool_calls
Honest resultsIt is used to return declines and errors as tool results, so the model reports them truthfully

Common Mistakes

No step limit. Always cap the loop and report when it stops early.

Hiding failures from the model. Return "declined" or error messages as tool results so it can respond honestly.

Trusting the model to ask permission. Enforce approvals in the tool code.

Interview Corner

Describe the agent loop.

Call the model with the tools and conversation; if it requests a tool, run it and append the result; repeat until it gives a final answer or a step limit is reached.

Where should human approval be enforced?

In the code that runs the tool, before the action happens. Prompts can encourage asking first, but only code guarantees it.

Practice

Exercise: extend the checkpoint. Add a third tool, cancel_meeting(confirmation), that also requires confirmation. Ask the agent to book and then cancel a meeting, answering yes and then no. Read the step log: did it do what you expected?

Check your understanding:

  1. What happens in one step of the loop?
  2. What stops the loop?
  3. Why does book_meeting call confirm() before booking?

Quick check: the agent loop

4 questions
1What does the code do when finish_reason is "tool_calls"?
2Why is MAX_STEPS there?
3What happens if the person types "no"?
4Where is the booking confirmation enforced?

Key Takeaways

Quick reference

NeedCode
Loop with a limitfor step in range(1, MAX_STEPS + 1):
Done?reply.finish_reason != "tool_calls"
Approvalif not confirm(...): return "declined"
Return a resultmessages.append(tool_result(call, output))

Was this tutorial helpful?

Lesson 103 of 186