Özer Cem KELAHMETKELAHMET
Articles · Agent steps

The agent loop step by step: instructions, tool calls, observations, errors and stopping

Every agent framework hides the same loop: call the model, parse its choice, run a tool, feed back the result, decide whether to stop. This article builds that loop in plain Python, traces one run step by step, and compares its stop rules with current LangGraph and OpenAI Agents SDK defaults.

Download Markdown
At a glance
Reading time
13 min
Sections
9
Code examples
3
Tables
1
Sources
6
Published
23 Nov 2026
In 30 seconds
What changed
OpenAI Agents SDK 0.25.0 released
Why it matters
Defaults are a design decision someone else made for you.
What to do
Write your stop rules down

Strip away the frameworks and an AI agent is a loop, the same one whether you use LangGraph or the OpenAI Agents SDK. The model reads everything so far, picks either an action or a final answer, the program runs the action, writes the result back into the conversation, and asks the model again. The loop ends when the model gives an answer or when the program decides it has spent enough.

That sounds simple, and it is. The hard parts are at the edges: what to do when the model calls a tool that does not exist, when a tool throws an exception, when the model repeats itself, and when to give up. Those edge decisions are where frameworks differ, and where their defaults can surprise you. LangGraph 1.2.24, for example, ships with a default recursion limit of 10,007 steps unless you set one, while the OpenAI Agents SDK 0.25.0 stops after 10 turns by default.

This article builds the loop in about 60 lines of plain Python with a scripted model, runs it, and explains every step of the trace. Then it maps each step to how current frameworks implement it.

What happened

OpenAI Agents SDK 0.25.0 released (18 November 2026)

In 0.25.0, Runner.run takes max_turns with a default of 10 and an error_handlers argument. The handlers are keyed by error kind, max_turns, model_refusal and invalid_final_output, and can return a final output instead of raising, so a run that hits its turn limit can still end with a controlled answer.

LangGraph 1.2.24 released (20 November 2026)

In the 1.2.24 source, the default recursion limit is defined as 10,007, read from the LANGGRAPH_DEFAULT_RECURSION_LIMIT environment variable when set. The langchain-core config module still defines its own DEFAULT_RECURSION_LIMIT = 25, but a compiled LangGraph graph uses its own default, which is high enough that it will not stop a looping agent in practice.

LangChain 1.5.2 released (18 November 2026)

LangChain's create_agent, which builds a LangGraph loop, offers ModelCallLimitMiddleware and ToolCallLimitMiddleware as explicit stop rules. Without them, the loop ends only when the model returns a message with no tool calls.

The nine steps of one turn

Think of a cook following a recipe with an assistant. The cook (the model) reads the order and the notes so far and says either "fetch me the flour" or "the dish is ready". The assistant (your program) checks the request makes sense, fetches the flour, writes a note on what happened, and hands the notes back. The assistant also decides when the kitchen closes.

In code, one turn has up to nine steps:

  1. Build the prompt. Instructions, the user task and all previous actions and observations.
  2. Call the model. It returns text, or a structured tool call.
  3. Parse. Turn the reply into a decision. Malformed output is an error, not a crash.
  4. Stop on a final answer. If the model says it is done, return.
  5. Validate the call. Does the tool exist? Are the arguments the right shape?
  6. Guard against loops. Has this exact call already been made?
  7. Execute. Run the tool, catching exceptions.
  8. Observe. Append the result or the error as a new message.
  9. Stop on budget. If the step limit is reached, end with a clear message.

Building the loop in plain Python

The scripted model below plays a realistic sequence: a correct call, a call with a typo in the tool name, a corrected call and a final answer. Real models make this kind of mistake, especially with many similar tool names.

import json

def get_weather(city: str) -> str:
    data = {"Istanbul": "18 C, cloudy", "Ankara": "9 C, clear"}
    if city not in data:
        raise KeyError(f"no data for {city}")
    return data[city]

TOOLS = {"get_weather": {"fn": get_weather, "description": "Current weather for a city."}}

SCRIPT = iter([
    '{"thought": "I need weather for both cities.", "action": "get_weather", "args": {"city": "Istanbul"}}',
    '{"thought": "Now Ankara.", "action": "get_wether", "args": {"city": "Ankara"}}',
    '{"thought": "Fix the tool name.", "action": "get_weather", "args": {"city": "Ankara"}}',
    '{"thought": "Done.", "final": "Istanbul is 18 C and cloudy; Ankara is 9 C and clear, so Ankara is colder."}',
])
def model(messages):
    return next(SCRIPT)

def run_agent(task, max_steps=6):
    messages = [{"role": "system", "content": "Answer using tools. Reply with JSON: "
                 "{thought, action, args} or {thought, final}. Tools: " +
                 json.dumps({n: t["description"] for n, t in TOOLS.items()})},
                {"role": "user", "content": task}]
    seen_calls, per_step = set(), []
    for step in range(1, max_steps + 1):
        per_step.append(sum(len(m["content"]) for m in messages))       # 1. prompt size
        raw = model(messages)                                              # 2. model call
        messages.append({"role": "assistant", "content": raw})
        try:
            decision = json.loads(raw)                                     # 3. parse
        except json.JSONDecodeError:
            obs = "ERROR: reply was not valid JSON"
        else:
            if "final" in decision:                                        # 4. stop: answer
                return decision["final"], step, per_step
            name, args = decision.get("action"), decision.get("args", {})
            key = (name, json.dumps(args, sort_keys=True))
            if name not in TOOLS:                                          # 5. validate
                obs = f"ERROR: unknown tool {name!r}; available: {list(TOOLS)}"
            elif key in seen_calls:                                        # 6. loop guard
                obs = "ERROR: you already made this exact call; use the earlier result"
            else:
                seen_calls.add(key)
                try:
                    obs = TOOLS[name]["fn"](**args)                        # 7. execute
                except Exception as exc:
                    obs = f"ERROR: {type(exc).__name__}: {exc}"
            print(f"step {step}: {name}({args}) => {obs}")
        messages.append({"role": "user", "content": f"Observation: {obs}"})   # 8. observe
    return "Stopped: step limit reached", max_steps, per_step               # 9. stop: budget

answer, steps, per_step = run_agent("Which is colder right now, Istanbul or Ankara?")
print(answer); print("steps:", steps, "| input chars per step:", per_step)

Reading the trace

Our run printed (thoughts trimmed for width):

step 1: get_weather({'city': 'Istanbul'}) => 18 C, cloudy
step 2: get_wether({'city': 'Ankara'}) => ERROR: unknown tool 'get_wether'; available: ['get_weather']
step 3: get_weather({'city': 'Ankara'}) => 9 C, clear
Istanbul is 18 C and cloudy; Ankara is 9 C and clear, so Ankara is colder.
steps: 4 | input chars per step: [181, 307, 458, 567]

Step 1 is the happy path: a valid tool, valid arguments, a result. The observation is appended as a new message, so the model sees it next time.

Step 2 is the typo. The program did not crash and did not guess what the model meant. It returned an error observation that names the problem and lists valid tools. That message is a hint the model can use, and in step 3 it does.

Step 3 succeeds. Notice that a tool error does not end the run. Errors are information.

Step 4 is the final answer. The loop ends because the model said so, not because of a limit.

The last line shows the cost that grows quietly. Every turn re-sends everything so far: 181 characters, then 307, 458 and 567. The total sent was 1,513 characters, about 378 tokens at a rough four characters per token, to answer a two-lookup question. In real agents with long system prompts, tool schemas and large tool outputs, the per-step input is often thousands of tokens, and the sum grows roughly with the square of the number of steps. The agent loop token cost simulation lets you change step counts and output sizes, and prompt caching is the main way providers reduce the repeated part.

How frameworks implement each step

Modern models do not need the JSON-in-text format we used. They return structured tool calls through function calling, which removes most parsing errors but not all of the other steps.

Table 1. How frameworks implement each step
Step Our loop LangChain 1.5 / LangGraph 1.2 OpenAI Agents SDK 0.25
Final answer "final" key AI message with no tool calls ends the loop Text output, or rules in tool_use_behavior
Unknown tool or bad args Error observation Tools node returns an error ToolMessage for validation errors Source paths either return "Tool 'name' not found." to the model or raise ModelBehaviorError
Tool exception Caught, returned as text Raised unless ToolErrorMiddleware converts it By default the model sees "An error occurred while running the tool."; failure_error_function=None raises instead
Loop guard Exact-call set ToolCallLimitMiddleware per tool or overall Not built in; use hooks
Step budget max_steps=6 ModelCallLimitMiddleware; graph recursion limit default 10,007 max_turns=10 by default
Budget hit Return a message exit_behavior="end" or "error" MaxTurnsExceeded, or an error_handlers["max_turns"] result

Two rows deserve emphasis.

Stopping early on purpose. The OpenAI SDK's tool_use_behavior can be "run_llm_again" (the default), "stop_on_first_tool", a StopAtTools list, or a function. Stopping at a tool is useful when the tool's output is the answer, such as a structured record, and you do not want the model to rephrase it. That saves one model call per run.

Hitting the limit gracefully. A run that dies with an exception at turn 10 gives the user nothing. In 0.25.0 you can register error_handlers={"max_turns": handler} and return a final output, for example "I could not finish; here is what I found so far". LangChain's ModelCallLimitMiddleware(exit_behavior="end") does the same by ending with a message.

The ReAct tool-calling simulation shows the loop with a real reasoning trace, and the agent run simulation adds timing, so you can see where the wall-clock time goes.

Reasoning and planning inside the loop

Our scripted model wrote a short thought before each action. That is the ReAct pattern: reason, act, observe, repeat. With today's reasoning models, much of the thinking happens inside the model call, and the visible trace shows only the tool calls. The loop is the same; the model simply does more work per step.

Planning can also be made explicit. In a plan-and-execute design, a first model call writes a list of steps, and the loop executes them one by one, re-planning only when an observation contradicts the plan. That reduces the number of expensive "what next?" calls for long tasks, at the cost of rigidity. The plan and execute and ReAct loop pages compare the two.

What it means in practice

Defaults are a design decision someone else made for you. The same agent can stop after 10 turns in one framework and effectively never in another. Before deploying, write down the stop rules you want and set them explicitly: a turn or model-call limit, a per-tool limit for expensive tools, a total token or cost budget, and a wall-clock timeout.

Error observations are part of the prompt. Messages such as "unknown tool 'get_wether'; available: ['get_weather']" help the model recover in one step. Messages such as a 40-line stack trace waste tokens and may leak details. Treat error text as user interface for the model.

Finally, log every step. A trace that records each prompt size, decision, tool call, observation and stop reason turns "the agent was slow and wrong" into a specific step you can fix.

What to do now

  1. Write your stop rules down. Decide maximum turns, maximum tool calls per tool, a cost budget and a timeout before you deploy.
  2. Set limits explicitly in LangGraph. Do not rely on the default recursion limit; pass recursion_limit in the config or add call-limit middleware.
  3. Handle limits gracefully. Use exit_behavior="end" in LangChain or an error_handlers["max_turns"] handler in the OpenAI SDK to return a useful partial answer.
  4. Return helpful error observations. Name the problem and the valid options; never return raw stack traces.
  5. Add a repeat-call guard. Block or flag identical consecutive tool calls.
  6. Measure input growth. Log input tokens per step and watch for steps that re-send large tool outputs.
  7. Trim or summarise old observations. Replace bulky tool results with short summaries once they have been used.
  8. Use stop-at-tool where the tool output is the answer. Save a model call and avoid rephrasing errors.

Risks and open questions

Silent infinite loops. A loop that alternates between two slightly different calls defeats an exact-match guard. Combine guards with hard turn limits.

Defaults change between versions. Limits and error behaviours can move between releases. Pin versions and re-check defaults on upgrade.

Errors as an injection channel. If a tool returns text from an external source as its error, that text enters the prompt. Sanitise or summarise external content before it becomes an observation.

Hidden reasoning makes traces thinner. With reasoning models, the "why" behind a step may not be visible. Log what you can: tool choices, arguments and timings.

Watch next: whether frameworks converge on cost budgets as a first-class stop rule, and how hidden reasoning summaries appear in traces.

Frequently asked questions

What is one step of an agent?

One step is one model call plus whatever it triggers: parsing the reply, running any tool calls and appending their observations. Some frameworks call this a turn.

Why not stop the run when a tool fails?

Because many failures are fixable by the model, such as a wrong name or a bad argument. Returning the error as an observation lets the model correct itself, as our run did in one step.

How many steps should an agent be allowed?

It depends on the task, but set a number deliberately. Measure how many steps successful runs take, and set the limit a little above the high end, with a graceful message when it is reached.

Why does each step cost more than the last?

Each model call re-sends the whole conversation, including every previous observation. Input grows with each step, so total input grows roughly with the square of the number of steps unless you trim or cache.

Is ReAct still relevant with reasoning models?

Yes. The loop of acting and observing is unchanged. Reasoning models move more of the thinking inside each call, so you may see fewer visible thoughts but the same sequence of tool calls and observations.

Summary

The agent loop is nine small decisions repeated: build the prompt, call the model, parse, stop on an answer, validate, guard against repeats, execute, observe and stop on budget. A 60-line Python version recovered from a mistyped tool name in one step and finished in four, while its per-step input grew from 181 to 567 characters. Frameworks implement the same steps with different defaults: OpenAI Agents SDK 0.25.0 stops at 10 turns, while LangGraph 1.2.24's default recursion limit of 10,007 means you must set your own. Write down your stop rules, make errors helpful, and log every step.

Sources

Cite this article

Kelahmet, Ö. C. (2026, November 23). The agent loop step by step: instructions, tool calls, observations, errors and stopping. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/agent-loop-step-by-step-trace

BibTeX
@online{kelahmet2026agent,
  author = {Kelahmet, {\"O}zer Cem},
  title  = {{The agent loop step by step: instructions, tool calls, observations, errors and stopping}},
  year   = {2026},
  month  = {nov},
  url    = {https://www.ozercemkelahmet.com/articles/agent-loop-step-by-step-trace}
}
Version historyfirst version
  1. Published

Factual corrections are listed here with what changed. Wording and formatting edits are not listed.

Last updated Nov 23, 2026
Type to search.
    ↑↓ navigate↵ open