Velamuvi AIAcademy

Lesson 3 of 7 · What Is an Agent?

The Agent Loop

How AI agents work step by step: the loop of deciding, acting with tools and observing results, recovering from errors, and stopping rules like step limits.

  • 5 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • Describe the steps of the agent loop
  • Trace an agent through a multi-step task, including a mistake
  • Explain how tool errors help an agent correct itself
  • Add stopping rules so an agent can't run forever

The loop at the heart of every agent

Every agent, from a tiny script to a coding assistant, runs the same loop:

  1. Think: the model reads the goal and everything so far, and decides the next step.
  2. Act: if the step is a tool call, your code runs the tool.
  3. Observe: the result is added to the history.
  4. Repeat until the model gives a final answer, or a stopping rule ends the loop.

This pattern is often called ReAct (reasoning and acting), after a 2022 research paper that showed models do better when they alternate between reasoning about a task and taking actions.

Watching the loop

A customer asks for money back for a late order. The model is again a scripted stand-in so the page runs without a key, but it behaves like a real one, including making a mistake:

Try it yourselfPython
ORDERS = {"A-1042": {"status": "delivered", "days_late": 3, "total": 58.0}}

# ---- Tools ----
def lookup_order(order_id):
    if order_id not in ORDERS:
        return {"error": f"No order {order_id}. Order IDs look like A-1234."}
    return ORDERS[order_id]

def issue_refund(order_id, amount):
    return {"refunded": amount, "order_id": order_id}

TOOLS = {"lookup_order": lookup_order, "issue_refund": issue_refund}

# ---- A stand-in for the LLM: reads the history and picks the next action ----
def scripted_model(history):
    last = history[-1]
    if last["role"] == "user":
        return {"tool": "lookup_order", "args": {"order_id": "1042"}}          # a mistake: wrong ID format
    result = last["content"]
    if "error" in result:
        return {"tool": "lookup_order", "args": {"order_id": "A-1042"}}        # reads the error, corrects itself
    if "days_late" in result and result["days_late"] > 2:
        return {"tool": "issue_refund", "args": {"order_id": "A-1042", "amount": round(result["total"] * 0.2, 2)}}
    if "refunded" in result:
        return {"answer": f"Sorry about the delay! I've refunded {result['refunded']:.2f} euros (20%)."}
    return {"answer": "Your order wasn't late enough for a refund."}

# ---- The agent loop ----
def run_agent(task, max_steps=6):
    history = [{"role": "user", "content": task}]
    for step in range(1, max_steps + 1):
        decision = scripted_model(history)                     # 1. think
        if "answer" in decision:
            print(f"[{step}] FINAL ANSWER: {decision['answer']}")
            return decision["answer"]
        result = TOOLS[decision["tool"]](**decision["args"])   # 2. act
        history.append({"role": "tool", "content": result})    # 3. observe
        print(f"[{step}] {decision['tool']}({decision['args']}) -> {result}")
    print("Stopped: step limit reached")

run_agent("My order 1042 arrived 3 days late. Can I get some money back?")

Follow the four steps:

  1. The model looks up order “1042”, but the real ID is “A-1042”. The tool returns an error message that explains the right format.
  2. The model reads the error and corrects itself: this is why tool errors should be clear sentences, not crashes.
  3. The order was 3 days late, so the model issues a 20% refund.
  4. It sees the refund succeeded and writes the final answer.

Nobody programmed the sequence in advance. The path came from the observations, which is what makes agents flexible, and what makes them harder to predict.

Stopping rules

A model can get stuck: repeating the same search, going in circles, or never deciding it's done. Every agent needs limits:

  • A maximum number of steps (the max_steps above).
  • A time or cost budget: stop when the task has taken too long or spent too many tokens.
  • A clear finishing condition: the model gives a final answer.
  • Human approval for risky actions, which pauses the loop until a person agrees.

Common mistakes

Practice exercise

Protect an agent from looping forever: add a step limit.

Your solutionPython
def stubborn_model(history):
    return {"tool": "search", "args": {"q": "weather"}}    # a model stuck repeating itself

def search(q):
    return "no results"

history = []
max_steps = 3
step = 0
# This loop never ends on its own. Add a step limit: stop after max_steps steps
# and then print "Stopped after 3 steps".
while True:
    step += 1
    decision = stubborn_model(history)
    history.append(search(**decision["args"]))
    print(f"Step {step}: search -> no results")
    break   # remove this line once your limit works
Knowledge check

An agent's tool call fails because an ID was in the wrong format. What should the tool return?

Summary

  • The agent loop is: think, act, observe, repeat.
  • The path through a task emerges from observations, so agents can adapt and even correct their own mistakes.
  • Return tool errors as messages, not crashes.
  • Always add stopping rules: step limits, budgets and human approval for risky actions.

Next: what agents are good at today, and where they still struggle.

Finished reading? Tick it off to track your progress.