Lesson 2 of 9 · Components
The Control Loop
Design an AI agent's control loop: stopping conditions, step and token budgets, repeated-action detection, error handling and an event log, in Python.
- 5 min read
- Intermediate
- Reviewed
- List the ways an agent loop should be allowed to end
- Add step, token and time budgets
- Detect an agent that repeats itself without progress
- Keep an event log that explains what the agent did
The loop is where reliability lives
The model decides; the control loop decides whether to keep going. A good loop guarantees that every run ends, at a known cost, with a record of what happened.
Ways a run should end
| Ending | Meaning |
|---|---|
| Final answer | The model says it's done: the normal ending |
| Step limit | Too many model calls |
| Token or cost budget | The run has become too expensive |
| Time limit | The user can't wait any longer |
| No progress | The same action repeats without new results |
| Policy stop | An action was refused or not approved |
| Unrecoverable error | A tool keeps failing, or credentials are invalid |
Every ending except the first should still produce a useful message: what was done, what wasn't, and why.
A loop with guards
import json
def run_loop(model, tools, goal, max_steps=8, max_tokens=4000):
"""A control loop with budgets, repeat detection and an event log."""
history, log, tokens_used = [], [], 0
for step in range(1, max_steps + 1):
decision = model(goal, history)
tokens_used += 300 + 50 * len(history) # rough cost: the prompt grows each step
if tokens_used > max_tokens:
log.append(("stop", "token budget used up"))
break
if "answer" in decision:
log.append(("answer", decision["answer"]))
break
call = json.dumps([decision["tool"], decision["args"]], sort_keys=True)
if sum(1 for h in history if h["call"] == call) >= 2: # same call already made twice
log.append(("stop", f"repeating {decision['tool']} without progress"))
break
result = tools[decision["tool"]](**decision["args"])
history.append({"call": call, "result": result})
log.append(("tool", f"{decision['tool']}({decision['args']}) -> {result}"))
else:
log.append(("stop", "step limit reached"))
return log, tokens_used
def search(query):
return "no results"
def stuck_model(goal, history): # keeps searching the same thing
return {"tool": "search", "args": {"query": "quarterly report 2026"}}
def good_model(goal, history):
if not history:
return {"tool": "search", "args": {"query": "quarterly report 2026"}}
return {"answer": "I couldn't find the quarterly report. Is it called something else?"}
for name, model in [("stuck model", stuck_model), ("good model", good_model)]:
log, tokens = run_loop(model, {"search": search}, "Find the Q3 report")
print(f"{name} ({tokens} tokens):")
for kind, detail in log:
print(f" {kind:<6} {detail}")The stuck model kept searching for the same thing. The loop noticed that the exact same call had already been made twice with no change, and stopped it on the third attempt, long before the step limit. The good model searched once, saw nothing, and asked the user a question instead.
Two details matter:
- The token estimate grows each step (
50 * len(history)), because each call re-sends the history. Budgets should track real usage from the API responses where possible. - The event log records every decision with its outcome. When users report a strange answer, the log tells you what happened.
Common mistakes
Add a token budget to the control loop, so a long task stops before it gets too expensive.
step_costs = [900, 1200, 1500, 1800, 2100] # tokens each model call would use
budget = 5000
# Run steps in order, but never start a step that would take the total over budget.
# Then print: Ran <n> steps, used <total> tokens
steps, used = 0, 0
for cost in step_costs:
steps += 1
used += cost
print(f"Ran {steps} steps, used {used} tokens")
An agent calls the same tool with the same arguments three times in a row and gets the same result each time. What should the control loop do?
Summary
- The control loop guarantees every run ends, at a known cost, with a record.
- Endings include a final answer, step, token and time limits, no progress, policy stops and errors.
- Detect repetition and stop early; budgets grow with history, so track them.
- Keep an event log of every step: it's how you debug agents.
Next: state, what an agent knows and how to save it.
Finished reading? Tick it off to track your progress.