Module 1 · Lesson 4 · 16 min read

The agent loop

The Agent Loop

Introduction

The agent loop is the engine that turns a language model from a responder into an executor. In this lesson we trace the stages of a single cycle, learn the stop conditions, write a complete loop in Python, and then see how a real library implements it.

Learning objectives

  • Describe the stages of a single cycle: perception, reasoning, action and observation
  • Explain why the code, not the model, runs the tool
  • Define suitable stop conditions for an agent loop
  • Write an agent loop in Python that treats tool errors as observations

The loop is what makes an agent an agent

If you removed the loop from any agent, it would become a single call to a language model. The agent loop is the structured repetition of steps: the agent perceives the situation, reasons about the next step, carries it out, observes the result, then returns to the start. The loop continues until a stop condition is met.

AgentAgent + goalPerceptionPerceivePlanningPlan / ReasonExecutionAct (Tools)ObservationObserve
The agent loop: it perceives, then plans, then executes, then observes the result, and repeats until the goal is achieved or a step limit is reached.

Stages of a single cycle

  1. Perception (Observe): gather what is available now: the goal, the user's message, earlier tool results, information retrieved from memory.
  2. Reasoning (Think): the agent sends this context to the model, and the model returns a decision: call a particular tool, or give a final answer.
  3. Action (Act): if the decision is a tool call, the code (not the model) actually runs the tool.
  4. Observation: the tool's result is added to the context, and a new cycle begins.

This pattern is very close to the ReAct pattern introduced by Yao and colleagues in 2022, in which the model alternates between written "thought", "action" through a tool and "observation" of the result. We study ReAct in depth in the ReAct pattern lesson.

Stop conditions

A loop without a stop condition is a real risk to cost and time. Common conditions:

  • Final answer: the model declares that it is done.
  • Maximum number of cycles: for example 10 cycles; it protects against infinite repetition.
  • Budget limit: the number of tokens, the cost or the time.
  • Unrecoverable error: an essential tool is down.
  • Request for human intervention: a decision that requires approval.

A practical example: an "expense calculator" agent

A student writes: "I spent 45 on books, 120 on housing and 30 on transport. How much is left of 250?" Let us trace the loop:

CycleReasoningActionObservation
1I need the total of the expensescalculator("45+120+30")195
2I need the difference from the budgetcalculator("250-195")55
3I have enough to answerFinal answer—

The following code implements this loop in full in pure Python. The policy function simulates the model with fixed rules.

python
import re

def calculator(expr):
    if not re.fullmatch(r"[0-9+\-*/(). ]+", expr):   # a simple security check
        raise ValueError("Expression not allowed")
    return eval(expr)

TOOLS = {"calculator": calculator}

def policy(goal, observations):
    """Simulates the language model's decision."""
    nums = [int(n) for n in re.findall(r"\d+", goal)]
    if len(observations) == 0:
        return {"action": "calculator", "input": "+".join(map(str, nums[:-1]))}
    if len(observations) == 1:
        return {"action": "calculator", "input": f"{nums[-1]}-{observations[0]}"}
    return {"final": f"You have {observations[-1]} left"}

def run_agent(goal, max_turns=5):
    observations = []
    for turn in range(1, max_turns + 1):
        decision = policy(goal, observations)              # reasoning
        if "final" in decision:
            return decision["final"], turn
        try:
            result = TOOLS[decision["action"]](decision["input"])   # action
        except Exception as e:
            result = f"Error: {e}"                            # an error is an observation too
        print(f"Cycle {turn}: {decision['action']}({decision['input']}) -> {result}")
        observations.append(result)                         # observation
    return "Stopped: reached the maximum number of cycles", max_turns

answer, turns = run_agent("I spent 45, 120 and 30. How much is left of 250")
print(answer, "| Number of cycles:", turns)

Notice that an error does not stop the loop; it becomes an observation that a real model can read and use to correct its request.

The same loop in a real framework

Modern frameworks run this loop for you. For example, in the OpenAI Agents SDK library (according to the official documentation, reviewed 18 November 2026, version 0.25.0) the Runner handles the loop: it calls the model, stops if the model returns a final output, runs the tools if it requests them and repeats, and raises the MaxTurnsExceeded exception if it exceeds max_turns. The following code requires installing openai-agents and an OPENAI_API_KEY key:

python
# Requires: pip install openai-agents  and the OPENAI_API_KEY environment variable
from agents import Agent, Runner

agent = Agent(name="Assistant", instructions="You are a helpful assistant")
result = Runner.run_sync(agent, "Write a haiku about recursion in programming.")
print(result.final_output)

Summary

The agent loop is a structured repetition of four stages: perceiving the situation, reasoning about the next step, carrying out the action and observing the result. The model requests that a tool be run and the code runs it, which allows permissions to be checked. Stop conditions such as a final answer, a maximum number of cycles and a budget are essential to avoid infinite loops. Frameworks such as the OpenAI Agents SDK run this loop for you, but the logic stays the same.

Terms

TermEnglishDefinition
The agent loopAgent LoopRepeating cycles of perception, reasoning, action and observation until stopping
ObservationObservationThe result of an action that is added to the context of the next cycle
Stop conditionStop ConditionA rule that ends the loop, such as a final answer or a cycle limit
ReAct patternReActA pattern in which the model alternates between thought, action and observation
Maximum number of cyclesmax_turnsThe number of cycles allowed before the agent is forcibly stopped

Review questions

  1. What are the four stages of an agent cycle? Which stage is run by the code and not the model?
  2. Why is it better to turn a tool error into an observation instead of stopping the loop?
  3. Name three stop conditions and explain when each one fits.
  4. What does the Runner in the OpenAI Agents SDK do when max_turns is exceeded?

References