Lesson 7.2: The agent loop
Understand the agent loop of observe, decide, act and repeat, when to use an agent or a fixed workflow, how cost grows with steps, and how to set stop rules.
In the last lesson a model asked for one tool, your code ran it and the model wrote an answer. That is a single trip. Many useful tasks need more than one: find a customer's order, notice that it was split into two shipments, look up each, compare the dates and then write a reply. You cannot always say in advance which tools will be needed, how many times or in what order, because the answer to one step decides the next. An agent is a system that handles this by running the model in a loop. At each turn the model looks at what has happened so far, decides what to do next, perhaps calls a tool, sees the result and decides again, until it judges the task finished or something stops it. The idea is simple and powerful, and it is also easy to get wrong: loops can wander, run up costs, repeat themselves and compound small errors. This lesson explains the loop, the pieces around it, how to choose between an agent and a fixed workflow, why cost grows faster than the number of steps, and how to set stop rules that keep a loop under control. By the end you will be able to describe the agent loop and name its parts, tell an agent apart from a workflow and choose between them for a task, estimate the tokens and cost of a run of many steps, set step, cost and progress limits, compute the chance that a run finishes within a step cap, recognise common patterns such as routing and orchestrator-worker, and sketch an agent for a real task. You should have read Lessons 7.1, 5.4 and 6.4. No programming is needed, and the arithmetic is multiplication and percentages.
What an agent is
The word is used loosely, so here is a working definition. An agent is a language model that is given a goal and a set of tools, and that decides for itself the sequence of actions to take, using the results of each action to choose the next, in a loop controlled by your code. The key feature is that the path is not fixed in advance.
Contrast this with a workflow, in which your code defines the path: first classify the message, then retrieve documents, then draft a reply, then check it. The model does work at each stage, but your program decides which stage comes next. A workflow is predictable, easy to test and cheap. An agent is flexible and can handle tasks you did not foresee, but it is less predictable, harder to test and costlier.
It helps to think of a scale. At one end is a single model call. Then come chains of fixed calls, then workflows with branches chosen by the model or by rules, and at the far end, agents that choose their own steps. Move along the scale only as far as the task demands, since each step adds cost, delay and risk.
The loop
Every agent runs some version of this cycle.
1. Observe. The model receives the goal, the history of what has been done and the latest result.
2. Decide. It chooses the next action: call a tool, ask the user a question or give a final answer. Many designs have the model write a short line of reasoning first, so that its choice is easier to follow and to debug.
3. Act. If it chose a tool, your code validates and runs it, as in Lesson 7.1.
4. Record. The request and the result are added to the history.
5. Check. Your code asks whether to stop: has the model given a final answer, has it hit the step limit, the cost limit or a time limit, has an error occurred that needs a person?
6. Repeat from step 1 if not stopped.
The loop itself is a few lines of ordinary code. The difficulty is everything around it: the instructions, the tools, the stop rules and the checks.
The pieces
The goal and the instructions. A system prompt that says what the agent is for, what it may and may not do, how to use the tools, when to ask the user and when to stop. Clear rules about stopping matter, since a model with no rule may keep working.
The tools. The set of actions available, described as in Lesson 7.1. Fewer, sharper tools make a better agent.
The state. What the agent knows at each step: the conversation, the tool results so far and perhaps a scratchpad of notes. Lesson 7.3 covers how to manage it.
The controller. Your code that runs the loop, validates calls, enforces limits and decides when to stop.
The guardrails. Permissions, approvals and checks, which Lesson 7.4 covers.
The trace. A record of every step, which lets you replay and debug a run.
Agent or workflow?
Many tasks that people reach for an agent to solve are better served by a workflow. Ask these questions.
Can you write down the steps? If the path is the same for nearly every request, such as "classify, retrieve, answer", build a workflow. It will be faster, cheaper and more reliable.
Does the path depend on what you find? If each step's result changes what to do next, and the number of steps varies, an agent earns its place. Research, debugging and multi-system lookups are examples.
What does a mistake cost? The more serious the harm from a wrong action, the more you should constrain the path and put people in the loop.
How much delay can the user take? An agent that runs ten steps may need a minute. A workflow with two calls takes seconds.
Can you test it? Workflows have a small set of paths to test. An agent has a huge number, so you must test outcomes and sample runs.
A sensible approach is to start with the simplest design that could work, measure where it fails and add flexibility only where the evidence calls for it. Often the best result is a workflow with one agentic step inside it, such as a research step that may run several searches, followed by fixed steps to format and check.
Predict first: an agent loop adds to the history at every step. If a run takes 10 steps and each step adds about 600 tokens, while the instructions and goal take 3,000 tokens, would you expect the total tokens sent to the model across the whole run to be about 10 times the first call, about 20 times or more? Work out roughly before you read on.
Why cost grows faster than steps
Each step is a call to the model, and each call must include the whole history so far. So step 1 sends the base prompt, step 2 sends the base plus what step 1 added, step 3 sends the base plus what steps 1 and 2 added, and so on. If the base is B tokens and each step adds S tokens, the input at step i is B + (i − 1) × S. Over n steps the total input is
n × B + S × n × (n − 1) ÷ 2.
The second term grows with the square of n. With B = 3,000 and S = 600:
5 steps: 5 × 3,000 + 600 × 10 = 15,000 + 6,000 = 21,000 tokens.
10 steps: 30,000 + 600 × 45 = 57,000 tokens.
20 steps: 60,000 + 600 × 190 = 174,000 tokens.
40 steps: 120,000 + 600 × 780 = 588,000 tokens.
Doubling the steps from 10 to 20 triples the input, and doubling again to 40 multiplies it by more than three. A 10-step run sends 57,000 tokens, which is 19 times the first call's 3,000, not 10 times. So the answer to the question above is "nearly twenty times".
At example prices of ₹30 per million input tokens and ₹120 per million output tokens, a 10-step run with 150 output tokens per step costs 57,000 × 30 ÷ 1,000,000 + 1,500 × 120 ÷ 1,000,000 = ₹1.71 + ₹0.18 = about ₹1.89. A 40-step run costs about ₹17.64 plus ₹0.72 of output, roughly ₹18. At 10,000 runs a month, the difference between a ten-step agent and a forty-step one is ₹19,000 against ₹1.8 lakh. Cost is therefore a design constraint, and you control it by keeping runs short, trimming the history, caching the fixed part of the prompt and capping steps.
Stop rules
An agent needs to know when to stop and your controller needs to enforce it. Use several rules together, because each catches a different failure.
A final answer. The normal exit: the model returns an answer with no tool request.
A step cap. A hard limit on the number of loops, for example 10 or 15. It prevents endless runs.
A cost or token cap, such as no more than ₹5 or 100,000 tokens a run.
A time limit. The user will not wait for ever.
Repetition detection. If the model makes the same call with the same arguments twice in a row, it is probably stuck. Stop, or tell it that it repeated itself and must try something different.
A progress check. Every few steps, test whether the run is getting closer to the goal, by a rule or a quick check by the model. If not, stop and report.
An error rule. After a number of failed tool calls, stop and hand over to a person.
A user interrupt. The user can cancel at any time.
What should happen when the cap is reached? Do not just cut off silently. Return what has been found so far, say that the task was not completed and why, and offer a way forward, such as continuing or handing off to a person.
How high should the step cap be? Suppose that on each step an agent has a 20% chance of reaching its answer, roughly independently. Then the chance that it has finished within n steps is 1 − 0.8 to the power n.
Step cap · Chance the run has finished3 · 48.8%
5 · 67.2%
10 · 89.3%
15 · 96.5%
20 · 98.8%
A cap of 10 lets about 89% finish, and the remaining 11% hit the cap. Raising it to 20 rescues another 9 points of runs but, for the runs that are stuck, it burns twice the steps, and with the quadratic growth in cost, much more than twice the money. The sensible cap is where the extra completions no longer justify the cost, and it should be set from data on real runs.
This model is crude, since real steps are not independent and stuck runs are stuck for a reason, but it shows the shape of the trade.
Common patterns
Beyond the basic loop, a few patterns appear again and again.
Routing. A first step classifies the request and sends it to a specialised path: billing, technical or sales. Each path can be a simpler workflow or a small agent with only the tools it needs.
Chaining. A fixed sequence of calls, each using the output of the last, with checks between them.
Parallel calls. Independent sub-tasks run at the same time and their results are merged, which saves delay.
Orchestrator and workers. A lead agent splits a task into parts, hands each to a worker with a narrow job and combines the results. Useful for research over many sources, but costly, as each worker is its own loop.
Generate and evaluate. One call drafts, another critiques against a rubric and the first revises, repeating a small fixed number of times. This is the idea behind many writing and code tools.
Reason and act. The common single-agent pattern in which the model alternates short reasoning with tool calls.
Choose the least complex one that solves your problem, and test it against a simpler baseline. It is common to find that a fixed workflow matches an agent on quality at a fraction of the cost.
Humans in the loop
An agent need not run alone. Place people at points where it matters: before an irreversible action, when the agent is unsure, when it has used a large share of its budget or when the request is outside the cases it was designed for. A good agent can ask the user a clarifying question instead of guessing, and can say "I need approval to do this". Lesson 7.4 covers where to put approvals.
Debugging a run
When a run goes wrong, read the trace from the top. At each step ask: what did the model see, what did it decide, was the decision reasonable given what it saw and did the tool return what was expected? Most problems fall into a few kinds: the goal was unclear, a tool description misled the model, a tool result was too long or confusing, the model repeated itself, or a small early error carried through the rest. Fix the cause, and add the run to your test cases.
Three worked examples
Example 1: a research assistant. A consultancy builds an agent to answer questions such as "what are the main digital-lending rules for NBFCs in India?" It has three tools: web search, open a page and note-taking. A run typically takes 8 to 12 steps: search, open two or three pages, note findings, search again for gaps and then write a summary with sources. The team caps runs at 15 steps and ₹6, checks that every claim has a source and shows the sources in the answer. About 91% of runs finish within the cap. The team trims old page text from the history after each note, which cuts the average run from ₹4.80 to ₹2.90.
Example 2: workflow beats agent. A support team first builds an agent that can search articles, look up orders and draft replies. It works but takes 7 steps on average and costs ₹1.60 a ticket. A review of 500 tickets shows that 85% follow one of three patterns: order status, return request or how-to question. The team builds a router and three fixed workflows of two or three steps each, with the agent kept only for the remaining 15%. The average cost falls to ₹0.35, the median delay drops from 25 seconds to 6 and quality on the test set is unchanged.
Example 3: a loop that got stuck. A coding assistant is told to make a failing test pass. It runs the test, edits a file, runs the test again and repeats. In one case it makes the same edit and runs the same test eleven times, since the edit does not fix the problem and nothing tells it that it is repeating itself. The team adds repetition detection, a step cap of 12 and a rule that after three failures with no change in the error message the agent must stop and describe what it tried. Stuck runs now end in 4 to 6 steps with a useful report and not 30 steps of waste.
An agent design worksheet
1. The goal. What should the agent achieve, and how will you know it did?
2. Workflow or agent? Can the steps be written down? What would a fixed workflow miss?
3. The tools. A small set, each with a clear purpose.
4. The instructions. Rules for acting, asking, stopping and declining.
5. The state. What the agent keeps between steps, and how long it can grow.
6. The stop rules. Final answer, step cap, cost cap, time limit, repetition, error rule.
7. The cost. Tokens and money for typical and worst-case runs.
8. The humans. Where approval or a question is required.
9. The trace and tests. What is logged, and which cases test outcomes.
10. The simplest baseline. What a fixed workflow would achieve.
Common mistakes
Using an agent where a workflow would do.
No step cap, so a stuck run continues.
Ignoring the quadratic growth of context, and so being surprised by cost.
Tools that overlap, which confuse the choice.
Letting the history grow without limit.
Silent cut-offs when a cap is reached.
No repetition check.
Testing only the happy path.
Judging an agent by one lucky run, and not by many.
Key takeaways
An agent is a model with tools in a loop controlled by your code, in which the model chooses its own next action from what it has seen. A workflow has a path fixed in advance.
The loop is observe, decide, act, record, check and repeat. The pieces around it are instructions, tools, state, a controller, guardrails and a trace.
Prefer the simplest design that works. Use an agent when the path depends on what is found, and a workflow when the steps can be written down.
Cost grows faster than steps, because each call re-sends the history. In the example 10 steps send 57,000 tokens, about 19 times the first call, and 40 steps send 588,000.
Use several stop rules: final answer, step cap, cost cap, time limit, repetition detection, progress check and error rule. If each step has a 20% chance of finishing, a cap of 10 lets about 89% of runs finish.
Common patterns are routing, chaining, parallel calls, orchestrator and workers, generate and evaluate, and reason and act.
Put people in the loop at irreversible, uncertain and high-cost points, and read traces to debug.
Check yourself
1. What is the main difference between an agent and a workflow?
In a workflow your code fixes the path. In an agent the model chooses its next step from what it has seen.
2. A base prompt is 2,000 tokens and each step adds 500. What is the total input for 6 steps?
6 × 2,000 + 500 × 6 × 5 ÷ 2 = 12,000 + 7,500 = 19,500 tokens.
3. If each step has a 30% chance of finishing, what share of runs finish within 5 steps?
1 − 0.7 to the power 5 = 1 − 0.168 = 83.2%.
4. Why stop a run that repeats the same call twice?
It is probably stuck. Repeating will not change the result and wastes tokens and time.
5. Why might a workflow beat an agent on a customer-support task?
If most requests follow a few patterns, fixed paths are faster, cheaper and easier to test, with similar quality.
6. What should happen when a step cap is reached?
The agent should return what it found so far, say that the task was not completed and why, and offer a way forward such as continuing or handing over.
Try this
Decide between an agent and a workflow for a real task. Set aside 60 minutes.
1. Choose a task, such as researching a question, handling a support ticket or preparing a report.
2. Write the steps a person takes, and mark those that depend on what the earlier steps find.
3. Decide whether a fixed workflow could cover 80% of cases. If so, write it as a short list of steps.
4. For the part that needs an agent, list the tools it would need and the stop rules you would set.
5. Use the first simulator to estimate the cost of a typical run and a worst-case run at your step cap.
6. Use the second simulator to choose a step cap, with your best guess of the chance that a step finishes the task.
7. Write the point at which a person should be asked to approve or help.
A good result is a task breakdown, a workflow-or-agent decision with reasons, a tool list, a set of stop rules with a step cap, cost estimates for typical and worst cases and a defined human checkpoint.
Tags: AI Engineering Agents Agent loop Workflows LLM applications