ProjekinAja. Agentic AI Stage 2 · How Agents Work Lesson 2.1
● Stage 2 · Lesson 2.1

The Agent Loop

The heartbeat of every agent. Once you see the loop, you can never un-see it — almost every modern tool-using agent is running this same simple cycle.

⏱ ~14 min read 🔁 The core mechanism 🔧 Opening the hood

🎯 By the end you'll understand

The four beats every agent repeats (Think → Act → Observe → repeat), why a feedback loop beats a one-shot plan, what makes an agent stop (and what happens when it can't), the LLM's exact job on each turn, and how the agent's context quietly grows with every step.

KEY INSIGHTThe one idea to take away

An agent isn't a single clever answer. It's a loop: think of a next move, do it, look at what happened, think again — over and over until the goal is met.

In Lesson 1.1 we said an agent is LLM + tools + a loop, pointed at a goal. Stage 1 was the view from outside. Now we open the hood — and the very first thing you find inside is that loop, beating away. Master this one cycle and the rest of Stage 2 is just detail bolted onto it.

🔑 Hold onto this

The agent doesn't plan the whole journey and then execute it blindly. It takes one small step, looks at the result, and only then decides the next step. The loop is what lets it react to a world it can't fully predict.

CORE CONCEPTThe four beats

Strip an agent down to its mechanism and you get a cycle with four beats. Different people name them differently — you'll hear Perceive → Reason → Act → Observe, or the popular ReAct pattern (Reason + Act) — but the core is always these four:

🧠

Think

Given the goal and everything that's happened so far, decide the single next action. This is the LLM reasoning: "the test is failing — I should read the file to see why."

🛠️

Act

Call a tool to actually do something — run code, read a file, search the web, send a request. This is the agent reaching into the world. (Tools are next, in Lesson 2.2.)

👁️

Observe

Read the result the tool sent back — the test output, the file contents, the error message. This is the feedback that makes the next "Think" smarter than the last.

🔁

Repeat

Feed that observation back in and loop — Think again, Act again — until the goal is met or a stop condition trips.

That's it. That's the engine under almost every coding agent, research agent, and customer-support agent you've ever heard of. The intelligence lives in the Think step; the power lives in Act; the wisdom lives in Observe. Take away the loop and you're back to a chatbot — one turn, no follow-through.

📖 The agent loop

The agent loop is the repeating cycle of Think → Act → Observe that an agent runs to pursue a goal. One pass through the cycle is called a turn (or iteration, or step). The loop keeps spinning until a stop condition ends it.

CORE CONCEPTWhy a loop, and not one big shot

The obvious question: why not just have the LLM plan the entire task up front in one go, then run the plan? It's faster, after all. The answer is the single most important idea in this lesson:

Real tasks give you feedback you couldn't have predicted. The loop exists to absorb that feedback and adapt.

Think about fixing a failing test. Before you run it, you don't know which line breaks, what the error says, or whether your first fix will work. You can't plan it all in advance — the information you need only arrives after you act. So you run the test (act), read the error (observe), form a hypothesis (think), try a fix (act), re-run (observe)… The plan emerges one observation at a time.

A one-shot agent is like writing a 12-step recipe for a kitchen you've never seen, then following it blindfolded. The loop is opening your eyes after each step. When step 3 turns up an empty cupboard, you adapt — instead of confidently completing a recipe that was wrong from step 4 onward.

💡 The rule of thumb

The more uncertain a task is — the more it depends on results you can't know in advance — the more a loop beats a plan. For perfectly predictable tasks you barely need an agent at all; a plain script would do.

This is also why agents can recover from their own mistakes. A bad action produces a bad observation ("error: file not found"), and the next Think step gets to react to it. The loop turns errors into information instead of dead ends.

FRAMEWORKThe loop, drawn

Here's the whole mechanism in one picture. Notice it's a circle — Observe feeds back into Think — with one exit: the stop check. Press play to follow one task round it. It is the same test fix you will run yourself in the next section.

The loop in motion
Goal in Think Act Observe Done (stop check)
Context · history so far
goal: make the test suite pass
turn 1 · run_tests() → 1 failed, cart.py:14
turn 2 · read_file("cart.py") → total = a + b
turn 3 · edit_file(…), run_tests() → all pass
The whole loop, and the context it leaves behind after three turns. Press play to follow one task round it, one beat per step, or drag the slider to any beat.

Every turn, the agent passes through Think and decides: is the goal met (or should I stop)? If yes, it exits to Done. If no, it Acts, Observes, and loops back. The dashed line is the only way out — and as you'll see in the next section, making sure that exit always exists is a matter of safety, not just neatness.

SEE ITRun the loop

Below is a real agent task: "Fix the failing test." Press ▶ Step to advance the loop one beat at a time and watch the agent reason, act, and observe. The context panel on the right shows the history accumulating — every turn, more gets added (you'll meet this growing context properly in Lesson 2.3). Or press ▶ Run all to let it play out.

🔁 Interactive · One agent, one loop

Goal: Make the test suite pass.

Press Step to begin. Each press = one beat of the loop.
🧠

THINKTurn 1

Goal is to make tests pass. I don't know what's broken yet — first I'll run the suite to see the failure.

🛠️

ACTrun_tests()

Calling the test runner tool.

👁️

OBSERVEResult

1 failed: test_total — expected 30, got 20 in cart.py:14.

🧠

THINKTurn 2

The math is wrong in cart.py. I should read line 14 to see the actual code before editing.

🛠️

ACTread_file("cart.py")

Calling the file-read tool.

👁️

OBSERVEResult

Line 14: total = a + b — but it should multiply quantity by price.

🧠

THINKTurn 3

Found the bug: addition where it should be multiplication. I'll edit line 14, then re-run to confirm.

🛠️

ACTedit_file("cart.py", 14, "total = qty * price")

Applying the fix.

🛠️

ACTrun_tests()

Re-running the suite to verify.

👁️

OBSERVEResult

All tests pass ✅

✅

Done

Stop condition: goal met. The loop exits and the agent reports back.

📜 Context / history so far
    empty — nothing has happened yet

    Notice it only ever grows. Every turn adds to what the LLM must read next time — which is exactly why context is a budget you manage (Lesson 2.3).

    Look at what just happened: the agent could not have known the bug was on line 14, or that it was a + instead of a *, before it acted. Each observation unlocked the next think. That's the loop earning its keep.

    CORE CONCEPTStop conditions — the exit that must exist

    A loop that can't stop is a disaster. So every well-built agent has stop conditions — the rules that end the loop. There are four common ones:

    Stop conditionWhat it meansWhy it's there
    🎯 Goal metthe task is done — tests pass, flight bookedthe happy path; the agent succeeded
    🔢 Budget hitmax steps, time, or tokens reacheda hard safety cap so it can't run forever
    🛑 Gives upagent decides it's stuck and can't proceedbetter to fail cleanly than thrash
    🙋 Asks a humanpauses and hands control back to youfor risky or ambiguous decisions (Stage 3)
    ⚠️ Critical: without a stop condition, an agent loops forever

    An agent that never hits an exit will Think → Act → Observe endlessly — burning money and time, sometimes repeating the same failing action over and over. This is the runaway loop, and it's a real failure mode you'll learn to prevent in Lesson 2.9. The single most important guardrail is a hard step budget: "stop after N turns no matter what."

    This is why the dashed exit arrow in the diagram matters so much. A loop is only as safe as its exit. When you build agents in Stage 4, setting a max-steps cap will be one of the first things you do — before the agent is even useful, you make sure it can't run away.

    FRAMEWORKThe LLM's job on every single turn

    Here's a subtlety that trips people up. The LLM doesn't "watch" the loop run. It is called fresh on each turn, and its job is narrow and identical every time:

    Given the goal + the history of everything that's happened so far, output the next action. That's the entire job.

    That's it. The LLM isn't holding the loop in its head between turns — the loop is run by the surrounding code (the "agent runtime"). On each turn that code hands the model a package:

    📥

    In: goal + history

    The goal ("fix the test"), plus the full record of past actions and observations — Think 1, Act, the result, Think 2, and so on.

    🧠

    The model reasons

    It reads all of that and decides one thing: what to do next. Either a tool call (read_file("cart.py")) or "I'm done — here's the answer."

    📤

    Out: the next action

    The runtime executes that action, captures the observation, appends both to the history, and calls the model again. Loop.

    ▸ The consequence

    Because the goal and the entire history are re-sent every turn, the package the model reads gets longer with each step. That accumulating package is the agent's context — and managing it (so it doesn't overflow or fill with noise) is its own craft. That's exactly the next lesson but one, Lesson 2.3.

    So when people say "the agent remembers what it did," what they really mean is: the runtime keeps the history, and re-feeds it to a model that is otherwise starting from scratch every turn. The memory lives in the loop, not in the LLM.

    WEAKNESSCommon mistakes to avoid

    ✗ "Agents plan everything upfront, then execute it blindly."

    Drawing up a plan first is a legitimate, common pattern (plan-then-execute — covered in Lesson 2.5). The failure is pure upfront planning with no observation or adaptation — committing to the whole plan and barreling through even when results contradict it. The point of the loop is that the agent observes after each step and re-decides; the plan adapts instead of running blind.

    ✗ "One big clever prompt makes an agent."

    A single prompt → single answer is a chatbot turn, not an agent. What makes it an agent is the loop wrapped around it — acting on the world and feeding results back in. No loop, no agent.

    ✗ "Loops are always safe — they'll just stop when done."

    Only if you built in a stop condition. Without a hard step budget, an agent can loop forever, repeating a failing action and burning money. The exit isn't automatic — you have to give it one (Lesson 2.9).

    KEY INSIGHTWhere this connects in your course

    • Chatbot vs agent (1.1) — the loop is the precise thing that turns a one-turn chatbot into an agent that gets work done.
    • Tools (2.2) — the "Act" beat is always a tool call. Next lesson, we go deep on what tools are and how the agent picks one.
    • Context (2.3) — the history that grows every turn (you watched it in the widget) is the agent's context, and managing it is a skill of its own.
    • Reasoning & self-correction (2.6) — the quality of the "Think" beat is what makes a loop productive instead of chaotic.
    • Runaway loops (2.9) — what goes wrong when a loop has no exit, and how to cap it safely.

    This is the spine of Stage 2. Every lesson from here either explains one beat of the loop in depth (tools, reasoning) or explains what flows through it (context) or what happens when it breaks (runaway loops). Keep the cycle in your head: Think → Act → Observe → repeat, until you stop.

    GLOSSARYKey terms introduced

    Agent loop
    The repeating Think → Act → Observe cycle an agent runs to pursue a goal until a stop condition ends it.
    Iteration / turn
    One pass through the loop — one Think, one Act, one Observe. Also called a step.
    Observation
    The result a tool returns (test output, file contents, an error) that the next Think step reacts to.
    Stop condition
    A rule that ends the loop: goal met, budget hit, the agent gives up, or it asks a human.
    ReAct
    A popular framing of the loop — "Reason + Act" — where the model alternates reasoning steps with tool actions.
    Step budget
    A hard cap on how many turns the loop may run, used to guarantee the agent can't loop forever.

    ACTIVE RECALLCheck your understanding

    Answer in your own words first, then reveal.

    1What are the four beats of the agent loop, and which one reaches into the world?›

    Think → Act → Observe → repeat. Act is the beat that reaches into the world — it's a tool call. Think decides the next action, Observe reads the result, and the loop repeats until a stop condition trips.

    2Why run a loop instead of having the LLM plan the whole task in one shot?›

    Because real tasks produce feedback you can't predict in advance — error messages, file contents, search results. The loop lets the agent act, observe the actual result, and adapt the next step, instead of blindly following a plan that may have been wrong from step one.

    3Name the stop conditions. What happens if there are none?›

    Goal met, budget/step limit hit, the agent gives up, or it asks a human. With no stop condition the agent loops forever — a runaway loop that burns time and money, often repeating a failing action. A hard step budget is the key guardrail (Lesson 2.9).

    4What exactly is the LLM's job on each turn — and why does the context keep growing?›

    Given the goal plus the full history of past actions and observations, output the single next action. The runtime executes it, appends the new action and observation to the history, and calls the model again — so the history (the agent's context) grows every turn. The memory lives in the loop, not in the model (Lesson 2.3).

    You've opened the hood. Next: the hands the agent acts with →