Skip to content
Visual explainer 4h to learn 4 steps

The agent loop: plan, act, observe

Build a bounded agent loop with step limits, state and stop conditions.

By Invicly Tech, , in AI Engineering with Python. About 12 minutes to read.

Topic 20 of 33

In short

An agent repeats a loop: the model decides on an action, your code runs it, and the result goes back to the model until the task is done. Step limits, state tracking and logs keep the loop safe and debuggable.

Explained simply

An agent is a model working in a loop. It looks at the goal and what has happened so far, picks one next action, sees the result, and decides again. It works like a person doing research: search, read, think, search again, then write up the answer.

Your code owns the loop. Each turn it sends the history to the model. If the model asks for a tool, your code runs it, adds the result to the history, and goes round again. If the model gives a plain answer with no tool call, the loop ends.

Without limits, a confused agent can go round forever, calling the same tool and spending money. So every loop needs a maximum number of steps, a token or cost budget, and a time limit. When a limit is hit, stop and say why.

Agents are flexible but less predictable than plain code. Many useful AI features are really fixed workflows with one or two model decisions inside. Start with the simplest design that works, and add autonomy only when the steps truly cannot be known in advance.

Press Play on a diagram to walk through it one step at a time.

CyclePlan, act, observe
  1. 1
    Plan

    Model reads goal and history, picks next step

  2. 2
    Act

    App runs the requested tool

  3. 3
    Observe

    Tool result is added to the history

  4. 4
    Check stop

    Done, step limit or budget reached?

  5. Back to step 1
SequenceA two-step agent run
User
Loop code
LLM
Tools
  1. 1Goal: summarise open bugs
    User to Loop code: Goal: summarise open bugs
  2. 2History, step 1
    Loop code to LLM: History, step 1
  3. 3Call search_issues(open)
    LLM to Loop code: Call search_issues(open)
  4. 4Run search_issues
    Loop code to Tools: Run search_issues
  5. 512 issues
    Tools to Loop code: 12 issues
  6. 6History plus result, step 2
    Loop code to LLM: History plus result, step 2
  7. 7Final summary, no tool call
    LLM to Loop code: Final summary, no tool call
  8. 8Summary and status done
    Loop code to User: Summary and status done

In depth

Workflow or agent? It is a spectrum

In a workflow, your code decides the steps: rewrite the query, search, answer. In an agent, the model decides the steps at run time. Between them sit useful patterns. A router uses one model call to pick which fixed path to take. An orchestrator breaks a task into parts and hands them to workers. An evaluator-optimizer loop has one call draft and another critique until a check passes.

The classic agent pattern is ReAct (reason plus act): the model writes a short thought, picks an action, reads the observation, and repeats. Modern tool-calling APIs give you this shape directly.

Choose by asking: can I write the steps down today? If yes, a workflow is cheaper, faster and easier to test. If the path depends on what each step finds, like debugging or open research, an agent earns its cost.

CompareWorkflow vs agent
Workflow
  • Code decides the steps
  • Predictable cost and latency
  • Easy to test step by step
  • Breaks on inputs that do not fit
Agent
  • Model decides the steps
  • Cost varies per task
  • Harder to test and debug
  • Handles open-ended tasks

State: what the loop must track

The main state is the message history, sometimes called the scratchpad: the goal, each model reply, each tool call and each result. Next to it, keep counters the model never sees: step number, tokens used, money spent and start time. Keep a set of calls already made so you can spot repeats, and any task state, such as files changed or the final draft.

Watch how fast the context grows. Every step resends the whole history. If each step adds 1,000 tokens, step 10 sends about 10,000 input tokens, and the run as a whole sends 1,000 + 2,000 + ... + 10,000 = 55,000. Cost grows much faster than the number of steps.

Keep it under control by truncating large tool outputs, storing big data outside the context and passing a short reference, and summarising old steps on long runs.

  • History: goal, replies, calls, results
  • Counters: steps, tokens, cost, elapsed time
  • Seen calls: for repeat detection
  • Large outputs: store outside, pass a reference

Stop conditions and guards

A good loop has one happy exit and several safety exits. The happy exit is a reply with no tool call, or a call to an explicit finish tool whose arguments hold the final answer. The safety exits are a step limit, a token or cost budget, a wall-clock timeout, repeated identical tool calls, and too many tool errors in a row.

Check the budgets before each model call, not after, so you never start a step you cannot pay for. Detect repeats by comparing the tool name plus its arguments, serialised with sorted keys, against the calls you have already made.

When a safety exit fires, do not fail silently. Return a clear status such as stopped: step limit, plus whatever partial result exists. The user, or a calling program, can then decide to retry, raise the limit or hand the task to a person.

FlowInside one iteration
  1. 1
    Check budgets

    Steps, tokens, cost, time

  2. 2
    Call the model

    With the full history

  3. 3
    Final answer?

    Yes: return it and stop

  4. 4
    Repeat call?

    Same name and args: stop

  5. 5
    Run the tool

    Validated, with a timeout

  6. 6
    Record observation

    Append result, update counters

Logging and debugging agent runs

An agent that fails without logs is nearly impossible to fix, because you cannot see why it chose what it chose. Give every run an ID and log one structured JSON line per step: step number, input tokens, the tool name and arguments, a short summary of the result, latency, cost and the reason the loop continued or stopped.

With those logs you can replay a run and spot the usual failure patterns. The agent picked the wrong tool because two descriptions overlap. It ignored an error message and repeated the same call. It looped because a tool returned an empty result with no hint. It stopped early and answered before it had enough information.

Each pattern has a fix, usually in tool descriptions, error messages or the system prompt. Save every failing run as an eval case so you can check that the fix really works.

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Implement a plan-act-observe loop~1h
  2. 2
    Track state between steps~1h
  3. 3
    Add step limits and stop conditions~1h
  4. 4
    Log each step for debugging~1h

Key points

  • Always set a maximum number of steps and a token or time budget.
  • Stop when the model gives a final answer with no tool call.
  • Log every step's input, tool call and result for debugging.
  • Prefer a simple workflow when the steps are known in advance.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
MAX_STEPS = 8

def run_agent(goal: str, call_model, run_tool) -> str:
    history = [{'role': 'user', 'content': goal}]
    for step in range(MAX_STEPS):
        reply = call_model(history)
        history.append(reply)
        if not reply.get('tool_call'):
            return reply['content']  # final answer
        call = reply['tool_call']
        result = run_tool(call['name'], call['args'])
        print(f'step {step}: {call["name"]} -> {result}')
        history.append({'role': 'tool', 'content': str(result)})
    return 'Stopped: step limit reached.'

A bounded loop with a final-answer stop and step logging.

A loop with a budget, repeat detection and stop reasons

This builds on a basic loop. Step 1: track tokens used from each reply's usage data. Step 2: when the reply has no tool call, return status done with the answer. Step 3: build a key from the tool name and its arguments with sorted keys; if the key was seen before, or the budget is spent, stop with a reason. Step 4: truncate tool output to 2,000 characters before adding it to the history, so one big result cannot flood the context. The message shapes are generic; adapt them to your SDK.

python
import json
def run(goal, call_model, run_tool, max_steps=8, max_tokens=50_000):
    history, seen, used = [{"role": "user", "content": goal}], set(), 0
    for step in range(max_steps):
        reply = call_model(history)
        used += reply["usage"]["total_tokens"]
        history.append(reply["message"])
        if (call := reply.get("tool_call")) is None:
            return {"status": "done", "answer": reply["message"]["content"], "steps": step + 1}
        key = (call["name"], json.dumps(call["args"], sort_keys=True))
        if key in seen or used > max_tokens:
            return {"status": "stopped", "reason": "repeat" if key in seen else "budget"}
        seen.add(key)
        history.append({"role": "tool", "id": call["id"], "content": str(run_tool(call))[:2000]})
    return {"status": "stopped", "reason": "max_steps"}

Reading the log of a stuck agent

A user reports that the docs agent sometimes takes 30 seconds and then gives up. You open the step log for one of those runs. Step 1: steps 1 to 3 all call search_docs with the query refund policy for annual plans, and each returns an empty list. Step 2: the model has no idea why the search failed, so it tries the same thing again until repeat detection stops it. Step 3: the fix is in the tool, not the loop: when nothing matches, return a hint such as No results. Try fewer words, for example refund annual. Step 4: re-run the case. The agent now retries with a broader query on step 2 and answers on step 3. Step 5: add the case to your eval set.

json
{"run": "r-81f", "step": 1, "tool": "search_docs", "args": {"q": "refund policy for annual plans"}, "result": "[]", "ms": 640}
{"run": "r-81f", "step": 2, "tool": "search_docs", "args": {"q": "refund policy for annual plans"}, "result": "[]", "ms": 610}
{"run": "r-81f", "step": 2, "stop": "repeat", "tokens": 9120}

Quick reference

  • Loop: call model, run requested tool, append result, repeat until a reply has no tool call
  • Always set max steps, a token or cost budget and a wall-clock timeout
  • Detect repeats with (tool name, json.dumps(args, sort_keys=True))
  • Check budgets before each model call, not after
  • Context grows every step: 10 steps of 1,000 tokens resend about 55,000 tokens in total
  • Truncate big tool outputs; store large data outside the context
  • On a safety stop, return a status, the reason and any partial result
  • If you can write the steps down today, build a workflow instead of an agent

Common mistakes

  • Running loops without a step limit, burning tokens on endless retries.
  • Using an agent for a task a fixed three-step script would do better.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What normally ends an agent loop successfully?

Question 2

2Each step adds about 1,000 tokens to the history. Roughly how many input tokens do 10 steps send in total?

Question 3

3The agent calls the same tool with the same arguments three times. What is the best guard?

Question 4

4A task always runs: fetch the ticket, classify it, draft a reply. What design fits best?

Question 5

5Why log a short JSON line for every agent step?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Add a wall-clock limit to an agent loop: stop with reason timeout if more than 60 seconds have passed before a model call.

  2. Exercise 2medium

    Write a step logger that prints one JSON line per step with run ID, step number, tool name, arguments, a 100-character result preview and milliseconds taken.

  3. Exercise 3hard

    Add an error guard: if three tool calls in a row return an error, stop the loop with reason too_many_errors, but reset the counter after any successful call.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need a framework to build an AI agent?
No. A basic agent is a for loop around a model call and a tool dispatcher. Frameworks can help later, but writing the loop yourself first makes debugging much easier.
How many steps should an agent be allowed?
Base it on your task: look at how many steps successful runs take in testing and set the limit a little above that. Many simple agents need fewer than ten.
What is the ReAct pattern?
ReAct (reason plus act) has the model alternate between short reasoning, an action such as a tool call, and reading the observation, until it can answer.
Why do agents cost so much more than single calls?
Each step is a full model call, and each call resends the growing history, so tokens add up quickly over a run.
ShareXLinkedInWhatsApp