Planning and the Agent Loop
An agent works in a loop: it thinks about what to do, takes an action, looks at the result, and repeats until the goal is done.
The Agent Loop
- Think: "What do I know? What should I do next?"
- Act: call a tool (search, read, calculate...).
- Observe: read the tool's result.
- Repeat or finish with a final answer.
This pattern is often called ReAct (reason + act). In code, the loop is simple. The hard part is the model's decisions inside it.
A Simulated Agent Loop
Here the "model" is a simple Python function so you can run the example without an API. It decides the next action from what it has seen so far:
Example
def fake_model(goal, observations):
if "price" not in observations:
return ("call", "get_price", "rice 5kg")
if "total" not in observations:
return ("call", "calculator", observations["price"] * 3)
return ("finish", f"3 bags of rice 5kg cost Rs {observations['total']}")
def run_tool(name, arg):
if name == "get_price":
return {"price": 1450}
if name == "calculator":
return {"total": arg}
goal = "How much do 3 bags of 5kg rice cost?"
observations = {}
for step in range(1, 6): # never loop forever
action = fake_model(goal, observations)
if action[0] == "finish":
print("Answer:", action[1])
break
_, tool, arg = action
result = run_tool(tool, arg)
print(f"Step {step}: {tool}({arg!r}) -> {result}")
observations.update(result)Step 1: get_price('rice 5kg') -> {'price': 1450}
Step 2: calculator(4350) -> {'total': 4350}
Answer: 3 bags of rice 5kg cost Rs 4350A real agent replaces fake_model with a call to a language model, passing the goal, the tool descriptions and the observations so far.
Planning Ahead
For bigger tasks, it helps to ask the model for a plan first, then carry it out step by step:
Example
Goal: Compare 3 laptops under Rs 200,000 for a design student.
First write a numbered plan of at most 5 steps.
Do not start until the plan is written.
After each step, mark it done and update the plan if needed.A plan might be:
| Step | Action |
|---|---|
| 1 | Search for laptops under Rs 200,000 |
| 2 | Pick 3 with good screens and at least 16 GB RAM |
| 3 | Collect price, RAM, GPU and screen details |
| 4 | Make a comparison table |
| 5 | Recommend one, with reasons |
Plans make agents easier to follow and to correct: you can say "skip step 1, here are three models I already like".
Stop Conditions
Agents can get stuck: repeating the same search, or never deciding they are done. Always add limits in your code, not only in the prompt:
- Maximum steps (like
range(1, 6)above) - Maximum time or maximum cost in tokens
- Repeated action check: stop if the same tool is called with the same input twice in a row
- A clear finish rule in the instructions: "When you have the answer, reply with FINAL: and the answer."
Example
history = [("search", "rice price"), ("search", "rice price")]
if len(history) >= 2 and history[-1] == history[-2]:
print("Stopping: the agent repeated the same action.")Stopping: the agent repeated the same action.
Reflection
Some agents add a check step: after finishing, the model reviews its own result against the goal ("Did I compare exactly 3 laptops? Are all prices under Rs 200,000?"). This catches many simple mistakes.
Start agents with small goals and a low step limit. Read every step they take. Raise the limits only once you trust the behaviour.
Exercise
Exercise
Why should an agent loop have a maximum number of steps in code?
