Chapter 3: The Agent Loop
Lecture
Chapter principle
Key takeaways
- An agent loop feeds action consequences back into later decisions.
- State is what lets a later decision differ because of an earlier event.
- Valid individual steps can still form a defective trajectory.
- Stopping conditions are part of control, not optional cleanup.
- The harness owns execution, validation, state updates, and termination.
Experiments
Every experiment in the book is small, runnable and printed with its real output. In the Lab you can replay a recorded real run of each one, with no programming, and watch what the model and the agent do.
Experiment 5: The smallest agent loop
How does an agent keep going until the task is done?
The task: multiply 27611 by 2033; if the result is even, add 6, otherwise subtract 6. Nobody knows which until the multiplication is done. The program runs a loop. The model decides, software runs the calculator, the result is added to the model's context, and the model decides again. The loop ends when the model answers, or after 10 steps. This is a recorded run of a real model. A new run may take a different number of steps.
Experiment 6: The agent that never finishes
What if the agent never decides it is done?
The agent must keep checking order 1042 until it has shipped, and it is told not to reply until the task is complete. But the order-status tool always says “pending”. Every decision is valid and every tool call works, yet the goal never comes true. Only a limit of 4 checks stops the loop. The program runs the agent five times. This is a recorded run of a real model.
All the code for this chapter: github.com/agentic-engineering-book/code
Download the bookBrowse all chapters