AI Engineering Tutorial · Tools and Agents · Lesson 13 of 25

A Minimal Agent Loop

An agent is a loop: call the model, run the tools it asks for, send results back, repeat until done, with limits.

Create a free account to save this page, take notes and track your progress. Sign in

The loop

while not done and steps < limit:
    reply = model(messages, tools)
    if reply asks for tools: run them, append results
    else: done

That is an agent: the model decides the next step, your code executes it. Always add limits (maximum steps, cost) so a confused model can't loop forever, and approvals for actions that change things.

Three steps of an agent loopTry it yourself
def search_flights(dest):
    return {"LIS": ["TP123 08:10", "FR882 14:45"]}.get(dest, [])

def book(flight):
    return f"booked {flight}"

script = [("tool", "search_flights", {"dest": "LIS"}), ("tool", "book", {"flight": "TP123 08:10"}),
          ("answer", "Booked TP123 at 08:10 to Lisbon.", None)]
TOOLS = {"search_flights": search_flights, "book": book}
transcript, max_steps = [], 5
for step, (kind, name, args) in enumerate(script, 1):      # each item stands for one model reply
    if step > max_steps:
        print("stopped: step limit"); break
    if kind == "answer":
        print(f"step {step}: final answer -> {name}"); break
    result = TOOLS[name](**args)
    transcript.append((name, result))
    print(f"step {step}: {name}({args}) -> {result}")

Output

step 1: search_flights({'dest': 'LIS'}) -> ['TP123 08:10', 'FR882 14:45']
step 2: book({'flight': 'TP123 08:10'}) -> booked TP123 08:10
step 3: final answer -> Booked TP123 at 08:10 to Lisbon.

Read more in the course AI Agents and MCP in Production.

Test yourself

Why must an agent loop have a step limit?

  1. APIs reject long conversations
  2. A confused model can keep calling tools forever, wasting time and money
  3. Tools can only run once
  4. It makes answers more creative
Show answer

Answer: A confused model can keep calling tools forever, wasting time and money

The loop's end is otherwise decided only by the model.

Was this page helpful?