← All lessons
Agents and workflows · Lesson 1 of 7

The agent loop and its tools

An agent is a model working in a loop with tools. It looks at the goal and what's happened so far, chooses the next step (often a tool call), your code runs it, the result goes back in, and the loop repeats until the model says it's done or a limit stops it.

# a stand-in for the model: the steps it would choose, one per turn
plan = [("search_orders", "Ana"), ("get_order", "A-1042"), ("done", "Your order A-1042 has shipped.")]

MAX_STEPS = 5
for step in range(1, MAX_STEPS + 1):
    action, arg = plan[step - 1]
    if action == "done":
        print("answer:", arg)
        break
    print(f"step {step}: {action}({arg!r})")
else:
    print("stopped: too many steps")
Prints
step 1: search_orders('Ana')
step 2: get_order('A-1042')
answer: Your order A-1042 has shipped.

Every loop needs limits: a maximum number of steps, a time limit and a budget for tokens or money. Without them, a confused agent can call the same tool forever. When a limit is hit, stop cleanly and hand over to a person with what's been done so far.

The tools are the agent's hands. Keep the set small and distinct (two tools that do nearly the same thing confuse the choice), say plainly in each description when to use it, and separate tools that only read from tools that change things. Open standards such as the Model Context Protocol (MCP) let one tool server be used by many agent apps, but the design rules are the same however tools are connected.

Before building an agent, ask whether you can write the steps down. If the task always goes classify, look up, draft, check, then a fixed workflow (next lesson) is cheaper, faster, easier to test and easier to explain. Agents earn their keep when the path really depends on what's found along the way: research, debugging, open-ended support cases.

Keep the agent's state in your code as well as in the conversation: what's been done, what was found, what was changed. You need it for limits, for logs, for resuming after a crash, and for showing a person what happened.

Practice

Put one turn of the agent loop in order.

  1. Tap the items below in order.
More info

Quick reference

AgentA model in a loop: choose a step, act with a tool, observe, repeat.
Step limit, budgetThe ceilings that stop a stuck loop.
Read vs write toolsLooking things up vs changing things; treat them differently.
MCPAn open protocol for connecting tools to agent apps.
WorkflowFixed steps written in code; prefer it when the steps are known.

The other AI and data engineering courses