Skip to content
Naveen Raj

Building AI Agents from Scratch with Python · Foundations

The Perceive–Think–Act Loop

Every agent, regardless of framework, is a variation of the same three-step loop:

┌──────────────┐
│   Perceive   │  gather the current state: user input, tool results, memory
└──────┬───────┘
       ↓
┌──────────────┐
│    Think     │  the model decides: respond directly, or call a tool?
└──────┬───────┘
       ↓
┌──────────────┐
│     Act      │  execute the tool call, or return the final answer
└──────┬───────┘
       └──────────────► back to Perceive, with the tool result added

The loop terminates when the "Think" step decides no more actions are needed and produces a final answer instead of a tool call.

Why a loop and not a single call

A single LLM call is reasoning in one shot — it has to get everything right without ever seeing the result of its own actions. A loop lets the model:

  • Correct course. If a tool call fails or returns something unexpected, the next iteration can react to that.
  • Gather information incrementally. It doesn't need to guess the answer to a database query before running it.
  • Decompose the problem. Complex tasks become a sequence of smaller, checkable steps.

This is also exactly why agents are harder to test than plain LLM calls: the number of possible paths through the loop grows with every tool you add. Chapter 3 covers guardrails for keeping that under control.