ReAct agent: think, act, observe, repeat

A ReAct agent alternates between reasoning and tool calls, using each result to choose its next move. Use it for open-ended questions where you cannot know the steps in advance.

ReAct agent in 60 seconds

  • What: an agent that alternates between a short reasoning step (thought), a tool call (action), and the tool result (observation).
  • How: loop thought, action, observation until the model can answer or a step limit is reached.
  • Best for: research questions, troubleshooting, and any task where the next step depends on what the last one revealed.
  • Weak spots: loops that wander, rising cost per step, and tool results that mislead the next thought.
  • Research link: ReAct (Yao et al., 2022) interleaves reasoning traces with actions such as tool calls, so the model can update its plan from what the tools return.

Where this type fits

The types of AI agents hub groups agents by how they decide. ReAct sits in the first family, between the reactive agent, which does one thing per input, and the planning agent, which writes everything out first. It is the adaptive middle: it plans a little, acts, learns, and plans a little more. Many production assistants are ReAct loops under the surface.

The problem it solves

Without tools, a language model answers from what it learned in training. That knowledge may be out of date, and the model may state a wrong fact with confidence. Ask it what an Acme order's status is, and it cannot know. It can only guess. Connecting tools fixes the missing data, but it creates a new question: which tool, with which input, and in what order?

A fixed script does not answer that. Suppose a customer writes, "My parcel says delivered but I do not have it." The right steps depend on what the order lookup returns. If the address looks wrong, check the address book. If the carrier shows a signature, check the delivery photo. If the order does not exist, ask for the number again. No one can write all those branches in advance, and a full upfront plan would be built on facts the agent does not yet have.

Asking the model to reason without acting has a different flaw. It can build a convincing chain of thought on a false premise and never find out. ReAct closes the gap by tying thinking to evidence. Each thought leads to an action, and each action returns an observation that can confirm or correct the thought. Reasoning guides the actions, and the actions keep the reasoning honest.

How it works

  • Receive the question. The prompt holds the question, the list of tools with their descriptions, and the format the model must follow.
  • Think. The model writes a short thought about what it knows and what it still needs. This is a working note, not the final answer.
  • Act. The model names one tool and its arguments. Your code validates the call and runs it. The model never runs tools itself.
  • Observe. The tool result is added to the prompt as an observation. Long results should be trimmed or summarised first.
  • Repeat or answer. If the thought says it has enough, the model writes the final answer. Otherwise the loop goes round again. A hard step limit ends the loop if the answer never becomes clear.
The ReAct loop repeats thought, action, and observation until the model has enough to answer.

The loop has two exits, and both matter. The good exit is the arrow from thought to the final answer, taken when the model judges it has enough evidence. The safe exit is the step limit. Without it, a confused agent can keep calling tools indefinitely. When the limit is hit, return a partial answer that says what was found and what is missing, rather than failing silently.

The ReAct paper by Yao and colleagues, published in 2022, describes interleaving reasoning traces with actions such as tool calls. The point is that the model can update its plan from what the tools return. That is the property to protect in your implementation. If you hide observations from the model, or stop it reading the trace, you lose what makes the pattern work.

A worked example

A customer of Acme writes: "Order 48213 says delivered but nothing arrived." The agent has three tools: get_order(order_id), get_tracking(tracking_id), and get_address(customer_id). The step limit is six.

Step 1. Thought: "I need the order details first." Action: get_order("48213"). Observation: {"status": "delivered", "tracking_id": "TRK-77120", "customer_id": "C-905", "ship_to": "14 Mill Lane, Leeds"}.

Step 2. Thought: "The order is marked delivered. I should check what the carrier recorded." Action: get_tracking("TRK-77120"). Observation: {"delivered_at": "2026-11-20 11:42", "left_with": "neighbour at number 41", "address_scanned": "41 Mill Lane, Leeds"}.

Step 3. Thought: "The carrier scanned number 41, but the order says number 14. The digits look swapped. Let me check the address on file." Action: get_address("C-905"). Observation: {"line1": "14 Mill Lane", "city": "Leeds"}.

Step 4. Thought: "The address on file is correct, so the carrier delivered to the wrong house. I have enough to answer." Final answer: "Your parcel was left with a neighbour at 41 Mill Lane, but your address is 14 Mill Lane. I have raised a carrier claim and will email you the reference." Four steps, three tool calls, and each choice came from the previous result. A fixed script would not have known to compare the two addresses.

The trace from the example, as stored for review (illustrative) (json)
[
  {"step": 1, "thought": "Need order details first", "action": {"tool": "get_order", "args": {"order_id": "48213"}}, "observation": {"status": "delivered", "tracking_id": "TRK-77120"}},
  {"step": 2, "thought": "Check what the carrier recorded", "action": {"tool": "get_tracking", "args": {"tracking_id": "TRK-77120"}}, "observation": {"address_scanned": "41 Mill Lane, Leeds"}},
  {"step": 3, "thought": "Scanned 41 but order says 14. Verify address on file", "action": {"tool": "get_address", "args": {"customer_id": "C-905"}}, "observation": {"line1": "14 Mill Lane"}},
  {"step": 4, "thought": "Carrier error. Enough to answer", "final": true}
]

Building it

The sketch below is a complete loop with the safeguards that matter: a step limit, a tool allow-list, argument validation, a per-tool timeout, a cap on observation size, and a clear stop reason. llm.generate() and tools are placeholders for your own model client and tool functions.

A bounded ReAct loop with validated tool calls (illustrative) (python)
import json

# Placeholders: llm.generate(prompt) -> str (JSON); tools is a dict name -> callable.
# Each tool function takes keyword arguments and returns a small dict.

MAX_STEPS = 6              # hard stop: a wandering agent must end
MAX_OBS_CHARS = 1500       # trim big tool results so the prompt stays small
TOOL_TIMEOUT_S = 10        # no tool call may hang the loop
ALLOWED = {'get_order', 'get_tracking', 'get_address'}

SYSTEM = ('Answer the question. Each turn return JSON: '
          '{"thought": str, "action": {"tool": str, "args": {}}} or {"thought": str, "final": str}. '
          'Use only the listed tools. Do not guess facts you can look up.')

def safe_call(name, args):
    # Why: the model proposes, your code decides. Validate before running.
    if name not in ALLOWED:
        return {'error': f'unknown tool {name}'}
    if not isinstance(args, dict):
        return {'error': 'args must be an object'}
    try:
        result = tools[name](timeout=TOOL_TIMEOUT_S, **args)
    except Exception as err:
        return {'error': str(err)[:200]}   # let the model see failures and adapt
    return result

def run(question):
    trace = []
    for step in range(1, MAX_STEPS + 1):
        prompt = SYSTEM + '\nQuestion: ' + question + '\nTrace so far: ' + json.dumps(trace)
        try:
            turn = json.loads(llm.generate(prompt))
        except ValueError:
            trace.append({'step': step, 'error': 'model returned invalid JSON'})
            continue                         # one bad turn should not end the run
        if 'final' in turn:
            return {'answer': turn['final'], 'trace': trace, 'stop': 'answered'}
        action = turn.get('action', {})
        obs = safe_call(action.get('tool'), action.get('args'))
        text = json.dumps(obs)[:MAX_OBS_CHARS]  # trim before it enters the prompt
        trace.append({'step': step, 'thought': turn.get('thought'),
                      'action': action, 'observation': text})
    # Step limit reached: return what was found instead of failing silently.
    return {'answer': None, 'trace': trace, 'stop': 'step_limit'}

Two details deserve attention. Tool errors are returned to the model as observations, so it can try another route rather than crash. And the trace is returned with every result, whether answered or not. That trace is your main debugging and audit tool.

Design decisions

  • Step limit: start at five to eight steps and raise it only when evidence shows tasks need more. Each extra step adds latency and cost.
  • Tool set: keep it small and clearly described. Ten well-named tools beat forty overlapping ones, because the model has to choose between them every turn.
  • Observation handling: trim, summarise, or paginate large results. The whole trace is resent on each step, so long observations multiply cost.
  • Failure handling: return tool errors as observations, retry only idempotent calls, and set a timeout per tool. Stop with a partial answer when limits are hit.
  • Access control: check permissions in code for each tool call, using the end user's rights, not the agent's. Never rely on the prompt to block a call.
  • Trace storage: store each trace with tool versions and the model version. It supports debugging, audits, and evaluation, so keep it for a defined retention period.
  • Concurrency: run tool calls in sequence by default. Allow parallel calls only for independent, read-only tools.

Measuring it

  • Task success rate: the share of test questions answered correctly, scored against a reference answer or a checklist.
  • Steps per task: the mean and the 95th percentile of steps used. A long tail shows where the loop wanders.
  • Tool-call validity: the share of proposed calls that pass validation on the first try. Low values point at poor tool descriptions.
  • Step-limit rate: the share of runs that hit the limit without answering. Inspect those traces first.
  • Cost and latency per task: tokens and seconds, including the repeated trace. Compare against a simpler baseline to confirm the loop earns its cost.

When to use it, and when not to

SituationUse this type?Why
Troubleshooting where each finding decides the next checkYesThe route cannot be known in advance, and ReAct adapts to each result.
Research questions that need several lookups across sourcesYesThe agent can follow leads and stop when it has enough.
Customer support that must consult order, account, and policy dataYesDifferent cases need different tool sequences.
A fixed workflow with known steps in a known orderNoA pipeline or plan is cheaper and more predictable.
Actions with irreversible side effects and no approval stepNoStep-by-step choices give no moment to review the full route. Add a human checkpoint first.
Very high volume, low-value inputsNoSeveral model calls per input costs too much. Use a reactive agent.

Trade-offs

DimensionEffectWhat to do about it
QualityStrong on open-ended tasks because answers rest on gathered evidence.Provide clear tool descriptions and test on realistic questions.
LatencyEach step is a model call plus a tool call, so total time grows with steps.Set a step limit, stream progress to the user, and trim observations.
CostThe growing trace is re-read every step, so cost rises faster than step count.Summarise old steps and cap observation size.
ComplexityModerate. The loop is simple, but tools, limits, and traces need care.Start from a small loop and add safeguards as tests demand.
Failure modesWandering loops, repeated identical calls, and over-trust in a wrong observation.Detect repeated calls, cap steps, and cross-check key facts.

The planning agent writes the whole route first. That helps when steps are known and a person must approve them, but it suffers when early results change what should happen next. ReAct accepts less foresight in return for adaptivity. The plan-and-execute agent offers a compromise: plan once, execute cheaply, and replan only when a step fails.

On the orchestration side, a ReAct loop with a handful of tools is what the single agent with tools pattern usually means. The tool-using agent page goes deeper on validating and permitting each call, which every ReAct system needs.

What this means for your role

Common mistakes

Further reading

ReAct gives an agent the ability to learn as it goes. Pair it with firm limits and good traces, and it becomes a dependable default for open-ended tool work.

Search topics

↑↓ to move · Enter to open · Esc to close