The Agent Loop
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
| Stage | Description |
|---|---|
| Plan | It is used by the model to choose the next tool, or to finish |
| Act | It is used by your code to run the chosen tool, after any checks |
| Observe | It is used to send the tool's result back so the model can see what happened |
| Repeat or stop | It is used to continue until a final answer, a refusal or the step limit |
Example: The Checkpoint Agent
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.
[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
| Guard | Description |
|---|---|
| Step limit | It is used to stop a confused agent from looping forever (MAX_STEPS) |
| Final answer check | It is used to end the loop when finish_reason is not tool_calls |
| Honest results | It 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:
- What happens in one step of the loop?
- What stops the loop?
- Why does
book_meetingcallconfirm()before booking?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Loop with a limit | for step in range(1, MAX_STEPS + 1): |
| Done? | reply.finish_reason != "tool_calls" |
| Approval | if not confirm(...): return "declined" |
| Return a result | messages.append(tool_result(call, output)) |
Was this tutorial helpful?