ReAct: the agent loop

In one sentence

The canonical agent loop: the model thinks, picks an action, your harness runs it and feeds back the real observation, and it repeats until done or until a cap you set stops it.

Analogy: A detective who writes down a hunch, checks one lead, reads what actually turned up, and only then decides the next lead, instead of solving the case from the armchair.

The model chooses each action; the harness executes it, feeds back the real result and owns the stop.

How it works

  • Reasoning alone states facts it never checks; acting alone can't plan. Interleaving grounds each step in evidence.
  • Today native tool calling carries the actions and a reasoning model's thinking plays the Thought; same loop.
  • Stop conditions are yours: final answer, no progress, a budget, or a step cap ~2–3× a typical successful run.
  • Watch for loops, goal drift, hallucinated observations and one bad early result derailing the rest.
  • Cost grows faster than steps: each call re-sends the whole transcript; prompt caching cheapens the repeated prefix.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your text-protocol ReAct agent (the harness parses Action: lines) answers confidently, but facts it presents as observations never appear in your tool logs. Most likely cause?

Go deeper

Full explanation

ReAct (Reason + Act; Yao et al., 2022) is the canonical agent loop. The model alternates thinking and acting, and each action's real result feeds the next thought:

  • Thought: reason about the goal and what is still missing.
  • Action: call a tool (search[...], SQL, a file read) or finish[answer].
  • Observation: the harness runs the tool and appends the real result.

Repeat until done. Reasoning alone (Chain-of-thought (CoT)) states facts it never checks; acting alone can't plan or recover. Interleaving grounds each step in evidence.

The paper did it in plain text: the harness parsed Action: lines and stopped generation at Observation: so the model couldn't invent results. Today native Tool / function calling carries the actions and a reasoning model's thinking plays the Thought, but the loop is identical.

Stop conditions are yours, not the model's:

  • a final answer (no tool call) or a finish tool;
  • a step cap and a token, time or $ budget;
  • no progress: repeated calls, or N steps with nothing new;
  • an action that needs a human (Human-in-the-loop & approvals).

Failure modes: loops (the same search again and again), drift (the goal fades as the transcript grows), hallucinated observations, and one bad early result derailing the rest. Cost grows faster than steps: each call re-sends the whole transcript.

Code Classic text ReAct loop with guards
pythonClassic text ReAct loop with guards
import re
from openai import OpenAI

client = OpenAI()
MODEL = "gpt-4.1-mini"  # any chat model that supports stop sequences

SYSTEM = """Solve the question by repeating:
Thought: what you know and what is missing
Action: search[query] | lookup[term] | finish[answer]
You will then receive an Observation. Never write an Observation yourself."""
TOOLS = {"search": wiki_search, "lookup": wiki_lookup}  # your real tools

def react(question: str, max_steps: int = 8) -> str:
    transcript, seen = f"Question: {question}\n", set()
    for _ in range(max_steps):  # hard cap: the loop never runs forever
        out = client.chat.completions.create(
            model=MODEL, temperature=0, stop=["Observation:"],  # can't invent results
            messages=[{"role": "system", "content": SYSTEM},
                      {"role": "user", "content": transcript}],
        ).choices[0].message.content
        transcript += out
        m = re.search(r"Action:\s*(\w+)\[(.*?)\]", out)
        if not m:
            obs = "Invalid format. Reply with one Thought and one Action."
        elif m.group(1) == "finish":
            return m.group(2)
        elif m.groups() in seen:  # no-progress guard
            obs = "You already ran this action. Try something different."
        else:
            seen.add(m.groups())
            tool = TOOLS.get(m.group(1))
            obs = tool(m.group(2))[:1500] if tool else f"Unknown tool {m.group(1)}."
        transcript += f"\nObservation: {obs}\n"  # real, truncated result goes back in
    return "Stopped: step budget exhausted without an answer."
Real example

Question: "In what year was the CEO of the company that makes Pixel phones born?"

  • Thought: find the maker → search[Pixel phone manufacturer] → Google.
  • Thought: now its CEO → search[Google CEO] → Sundar Pichai.
  • Thought: birth year → search[Sundar Pichai born] → 1972 → finish[1972].

Four model calls, three tool calls, ~5 s. In another run the first search returned an unrelated page and the agent issued the same query three times; the repeat guard answered "you already ran this", it searched Google Pixel maker instead and recovered within the 8-step cap.

Trade-offs +4 · −3

+ You gain

  • Grounds reasoning in real observations: fewer invented facts than pure chain-of-thought.
  • Recovers: a bad result becomes input to the next thought instead of a dead end.
  • Interpretable: the thought/action trace is a debuggable log of why each step happened.
  • Simple: ~20 lines around any tool-calling model.

− You pay

  • Sequential: one model call per step, so latency grows linearly with steps.
  • Input tokens grow roughly quadratically: every step re-sends the growing transcript.
  • Greedy and step-by-step: with no global plan, long tasks drift or loop (Planning (plan-and-execute)).

Use it when

Tasks where the next step depends on what the last one found: multi-hop QA, debugging, research, data exploration, interactive environments. It's the default inner loop of almost every agent.

Avoid it when

When the steps are known (use a workflow), for single-lookup questions (one retrieval is enough), or for long tasks with many dependent subgoals, where you add an explicit plan or orchestrator on top.

Numbers to know 4
  • ReAct paper: +34 and +10 points absolute success over imitation and RL baselines on ALFWorld and WebShop, prompted with only 1–2 examples.
  • On HotpotQA, ReAct alone slightly trailed chain-of-thought; combining it with self-consistent CoT scored best. On FEVER, ReAct beat CoT.
  • Cost math: step k re-sends k prior steps, so n steps send ~n²/2 step-sized chunks of input; Prompt caching makes the repeated prefix cheap.
  • Rule of thumb: set the step cap at ~2–3× the steps a typical successful run needs, measured from traces.
Common pitfalls 4
  • No stop sequence in a text-protocol loop: the model writes its own Observation: and answers from invented data.
  • Only a step cap: also detect no-progress (repeated identical calls) and fail early.
  • Appending raw tool output: a 30K-token page in step 2 crowds out the goal by step 6.
  • Trusting finish blindly: check the answer is supported by the observations, or have a verifier grade it.
Interview questions 3

Answer out loud first, then reveal.

Walk me through an agent loop. How does it terminate?Show answer

It's ReAct: the model reasons, picks an action, my harness executes it and appends the real observation, and we repeat. Termination is mine, not the model's. It ends when the model answers without a tool call, but I also enforce a step cap, a token and wall-clock budget, a no-progress check on repeated calls, and a hand-off to a human for risky actions. When a guard trips I return an explicit 'couldn't finish' with the partial trace, never a guess.

Your agent calls the same search six times in a row. What do you do?Show answer

First I read the trace: usually the observation isn't usable, a vague result or an error the model can't act on, so it retries. Fixes in order: make the tool's output and errors actionable, like 'no results; narrow the date range'; add a repeat detector that answers 'you already ran this' and forces a different action; and trim old observations so the goal stays in view. Then that trace goes into the eval set so the regression gets caught.

Is ReAct still relevant with native tool calling and reasoning models?Show answer

Yes. The loop is unchanged; the transport changed. Actions are structured tool calls instead of parsed text, so no regex and no invented observations, and the Thought is the model's reasoning, which some APIs let it interleave between tool calls. What still decides quality is everything around the loop: stop conditions, budgets, context management and evals. ReAct is the inner loop; planning, memory and orchestration sit on top of it.