The AI Agent Loop Explained: Think, Act, Observe and Stop
Under all the excitement, most AI agents run on a surprisingly small piece of code. It is a loop. In this lesson you will understand the AI agent loop line by line, using a fake model so that the example is free and repeatable. You will also see why a good stop condition matters so much.
📖 What You’ll Learn
- The four steps of an agent loop
- How a model asks to use a tool
- Why results must go back to the model
- Which stop conditions every agent needs
💡 The AI Agent Loop
Explain Like I’m 5: Looking for Your Shoe
Imagine: You think, “Maybe it is under the bed.” You look. You see no shoe. You think again and check the cupboard. You stop when you find it.
What it really means: An agent repeats think, act and observe until it is done.
In testing: It calls a tool, reads the result and decides what to do next.
| Step | What happens | QA example |
|---|---|---|
| Think | The model decides the next step | “I need the test results” |
| Act | Your code runs the chosen tool | Reads the report |
| Observe | The result returns to the model | “login-test failed with a timeout” |
| Stop | The goal is met or a limit is reached | Writes a summary |
🔍 The Model Does Not Run Tools
Explain Like I’m 5: Asking a Parent
Imagine: A small child says, “Please pour me some milk.” The child asks, and the parent does the pouring.
What it really means: The model only asks for a tool, and your code runs it.
In testing: This is where you can enforce every safety rule.
This point is very important. Your code stands between the model and the real world, so your code can refuse any request.
🧩 A Complete Loop
This TypeScript example has no dependencies. fakeModel stands in for a real AI model.
type Decision =
| { type: 'tool'; tool: string; input: string }
| { type: 'finish'; answer: string };
function fakeModel(history: string[]): Decision {
if (history.length === 0) {
return { type: 'tool', tool: 'getTestResult', input: 'login-test' };
}
return { type: 'finish', answer: `Summary: ${history[0]}` };
}
const tools: Record<string, (input: string) => string> = {
getTestResult: (name) => `${name} failed with a timeout`,
};
const MAX_STEPS = 5;
function runAgent(): string {
const history: string[] = [];
for (let step = 1; step <= MAX_STEPS; step++) {
const decision = fakeModel(history);
if (decision.type === 'finish') {
return decision.answer;
}
const tool = tools[decision.tool];
if (!tool) {
return `Stopped: unknown tool ${decision.tool}`;
}
const result = tool(decision.input);
console.log(`Step ${step}: ${decision.tool} -> ${result}`);
history.push(result);
}
return 'Stopped: reached the step limit';
}
console.log(runAgent());
Step 1: getTestResult -> login-test failed with a timeout
Summary: login-test failed with a timeout
On the first pass, the history is empty, so the model asks for a tool. On the second pass, it has the result, so it finishes.
🛠️ Stop Conditions
Explain Like I’m 5: Bedtime Rules
Imagine: Stop playing when the game ends, when it is bedtime or when someone is hurt.
What it really means: An agent needs several reasons to stop.
In testing: Never rely only on the model deciding that it has finished.
| Stop reason | Why it matters |
|---|---|
| Task finished | The normal, successful end |
| Step limit | Prevents endless loops |
| Time or cost limit | Controls spending |
| Unknown tool | Stops an invalid request |
| Repeated tool failure | Prevents wasted retries |
| Model refused or was cut off | Handles an incomplete response |
| Human approval needed | Pauses risky actions |
A limit is not success
Report “reached the step limit” as a stopped run. Do not let the agent’s final message hide that it failed to finish.
📌 Handling Tool Errors
If a tool fails, send the error back as the observation so that the model can adapt, up to your limit. Do not silently drop it. In Testing AI Agents, you saw how a hidden tool failure can lead to a false success message.
🌍 Real-Life Example: The Endless Search
An agent is asked to find a report that does not exist. Each search returns nothing, so it tries again with almost the same search. Without a limit, the bill keeps growing. A step limit and a repeated-call check end the run, with a clear message that the report was not found.
🧪 Try It Yourself
- Install Node.js as shown in Install Playwright, save the code as
loop.tsand runnpx tsx loop.ts. - Change
fakeModelso that it always asks for the tool. - Confirm that the agent stops at the step limit.
- Make it ask for an unknown tool.
- Use the prompt below to explain any part you do not understand.
📋 Ready-to-Copy Prompt
You are a patient AI engineering mentor teaching a software tester.
Explain this agent loop line by line in simple words:
[paste code]
Then tell me:
1. Where the model decides
2. Where real actions happen
3. Where a safety check should go
4. Three ways this loop could fail
Do not add any frameworks. Do not rewrite the code yet.
⚠️ Common Mistakes
- Writing a loop with no step limit
- Thinking the model runs the tool itself
- Forgetting to send tool results back
- Hiding tool errors from the model and logs
- Reporting a stopped run as a success
🎯 Key Takeaways
- Agents repeat think, act and observe until they stop.
- The model requests tools, and your code runs them.
- Your code is the place to enforce safety.
- Every agent needs clear stop conditions.
🎤 Interview Questions
1. What is an agent loop?
Model answer: It is a cycle in which a model decides the next step, code runs a tool, and the result goes back to the model. It repeats until the task finishes or a limit stops it.
2. Does an LLM execute tools directly?
Model answer: Normally, no. The model produces a structured request, and application code validates and runs it. That gives us a control point for permissions and safety.
3. Why does an agent need a step limit?
Model answer: Without one, it could loop indefinitely, wasting time and money. A limit guarantees that the run ends, and the system should report that it stopped without completing.
4. How should tool errors be handled?
Model answer: The error should be logged and returned to the model as a result, so that it can respond. Retries should be limited, and the agent must not claim success after a failure.
5. How would you test an agent loop?
Model answer: I would use a fake model and mock tools to test normal completion, unknown tools, tool failures, step limits and approvals. Scripted decisions make these tests repeatable and free.
📝 Assignment
Add two features to the loop: a check that stops when the same tool is called twice with the same input, and a log of every step. Write a test for each stop condition using a fake model.
❓ FAQ
Why use a fake model?
It costs nothing and always behaves the same way, so you can test the loop’s logic before adding a real model.
Can an agent call several tools at once?
Yes, some models can request several at once. Run them, then return all the results together, and apply the same safety checks to each.
🚀 Next Steps
Well done on finishing this lesson. Complete the assignment, then continue with Build an AI Agent from Scratch: Your First One-Tool QA Agent.