ReAct: Interleaving Reasoning and Acting

Thought, action, observation, repeat. What the ReAct paper actually showed, how the pattern maps onto native tool calling, a working agent with LangChain's create_agent, and where step-by-step reasoning breaks down.

Module 2 built the machinery of an agent: schemas, the execution loop, and failure handling. Nothing in it decided what to do next; the model did that, and we took it on faith. Module 3 is about that decision, the agent’s architecture. The first and still most common one is ReAct.

ReAct (Yao et al., 2022) is the reason “agent” and “a model calling tools in a loop” are nearly synonyms today. LangChain’s own docs define an agent as “a model calling tools in a loop until a given task is complete”, and that loop, with the model reasoning between calls, is ReAct.

1. The idea: thoughts are actions that only change the context

A plain tool-using agent picks an action from the space of tool calls. ReAct’s move is to add language to that action space: a “thought” is an action that doesn’t touch the environment, it only appends reasoning to the context. The model can then use thoughts to decompose the task, track progress, interpret what it just saw, and decide what to look up next.

flowchart TD
Q([Question]) --> T[Thought: what do I know, and what do I need next?]
T -->|need more information| A[Action: call a tool]
A --> O[Observation: the tool's result]
O --> T
T -->|enough to answer| F([Answer])
The ReAct loop. Thoughts change only the context; actions change, or query, the world.

The paper’s version of a step is three labeled lines of text:

Thought: I need to know where Alan Turing earned his PhD.
Action: search[Alan Turing]
Observation: Alan Turing (1912-1954) was an English mathematician ... earned his PhD at Princeton ...

The model writes the Thought and the Action; the system runs the action and writes the Observation; the model continues from there.

2. What the paper actually showed

ReAct is often summarized as “better than chain-of-thought”. The results are more interesting than that. On PaLM-540B with a handful of examples in the prompt:

MethodHotpotQA (exact match)FEVER (accuracy)
Chain-of-thought29.456.3
Chain-of-thought, self-consistency33.460.4
Act only (no thoughts)25.758.9
ReAct27.460.9
ReAct, falling back to CoT self-consistency35.162.0

On multi-hop QA, ReAct alone loses to chain-of-thought; on fact verification it wins; and the best results come from combining the two (switching to chain-of-thought self-consistency when ReAct fails to answer within its step budget). On the interactive benchmarks, the gap is large: ReAct beat imitation- and reinforcement-learning baselines by 34 points of success rate on ALFWorld and 10 on WebShop, prompted with one or two examples.

The error analysis explains why. The authors hand-labeled 200 HotpotQA trajectories (50 correct and 50 incorrect for each method):

Failure modeReActChain-of-thought
Hallucinated facts or reasoning0%56%
Reasoning error, including repeating earlier steps47%16%
Search returned nothing useful23%n/a

Chain-of-thought reasons fluently from memory, so when it fails, it’s usually confidently wrong. ReAct can’t make facts up because it reads them, but the rigid think-act-observe structure makes it worse at long reasoning, and it inherits every weakness of its tools. Its signature failure is the loop: repeating the previous thought and action because it can’t work out what to do next.

The practical lessons: use ReAct when correctness depends on external facts or actions, give it good tools (a weak search tool caps the agent), and plan for loops.

3. ReAct the original way: text in, regex out

Before providers offered native tool calling, ReAct was a prompt format plus a parser. It’s worth writing once, because every framework still does a version of this:

react_text.py
import re
PROMPT = """Answer the question by interleaving Thought, Action, and Observation steps.
Thought: what you still need to know, and why
Action: search[exact article title]
Observation: (written by the system, never by you)
Repeat as needed, then finish with:
Answer: the final answer
Question: {question}
"""
ACTION = re.compile(r"Action: (\w+)\[(.*?)\]")
def react_text(llm, question: str, tools: dict, max_steps: int = 8) -> str:
transcript = PROMPT.format(question=question)
for _ in range(max_steps):
# Stop before "Observation:" so the model can't invent the tool's output.
step = llm.invoke(transcript, stop=["\nObservation:"]).content
transcript += step
if "Answer:" in step:
return step.split("Answer:", 1)[1].strip()
match = ACTION.search(step)
if match is None:
transcript += "\nObservation: Invalid format. Write Action: tool[input].\n"
continue
name, arg = match.groups()
observation = tools[name].invoke(arg) if name in tools else f"Unknown tool {name!r}."
transcript += f"\nObservation: {observation}\n"
raise RuntimeError(f"no answer after {max_steps} steps")

The stop sequence is the critical line. Without it, the model happily writes Observation: itself and continues with an imagined result: the hallucination ReAct exists to prevent.

4. ReAct today: native tool calls

Native tool calling, as covered in 2.1, moves this protocol into the API:

ReAct (text)Native tool calling
Thought: lineThe message’s text content before the tool calls, or a reasoning model’s separate reasoning output
Action: search[Alan Turing], parsed with a regexA structured tool_calls entry with schema-validated JSON arguments
Observation: line appended to a promptA ToolMessage matched by tool_call_id
One action per stepSeveral independent calls per step, executed in parallel
A stop sequence to prevent fake observationsNot needed: the model’s turn ends at the tool call

The tool is a tiny offline encyclopedia (four articles, so the run is deterministic) with a search that suggests similar titles on a miss, as the paper’s Wikipedia API did:

wiki.py
from langchain_core.tools import tool
# A four-article "encyclopedia", so the example runs offline and deterministically.
ARTICLES = {
"alan turing": (
"Alan Turing (1912-1954) was an English mathematician, computer scientist, and cryptanalyst. "
"He is widely regarded as a founder of theoretical computer science and artificial intelligence. "
"Turing earned his PhD at Princeton University in 1938, with Alonzo Church as his advisor. "
"During the Second World War he worked at Bletchley Park on breaking the Enigma cipher."
),
"grace hopper": (
"Grace Hopper (1906-1992) was an American computer scientist and United States Navy rear admiral. "
"She was a pioneer of computer programming and led work on the first compiler for a computer "
"language. Hopper earned a PhD in mathematics from Yale University in 1934."
),
"princeton university": (
"Princeton University is a private research university in Princeton, New Jersey. Founded in 1746 "
"as the College of New Jersey, it is the fourth-oldest institution of higher education in the "
"United States and adopted its current name in 1896."
),
"yale university": (
"Yale University is a private research university in New Haven, Connecticut. Founded in 1701 as the "
"Collegiate School, it is the third-oldest institution of higher education in the United States and "
"was renamed in 1718."
),
}
@tool
def search(entity: str) -> str:
"""Look up an encyclopedia article by its exact title (a person, place, or organization). Returns its opening paragraph."""
article = ARTICLES.get(entity.strip().lower())
if article is None:
words = entity.lower().split()
similar = [title.title() for title in ARTICLES if any(w in title for w in words)]
return f"No article titled {entity!r}. Similar titles: {similar or 'none'}."
return article

The agent is LangChain’s create_agent, which builds the model-and-tools loop from Module 2 as a graph. The system prompt asks for the Thought explicitly, and for independent lookups to go out together:

react_agent.py
from langchain.agents import create_agent
from langchain.agents.middleware import ModelCallLimitMiddleware
from langchain.chat_models import init_chat_model
from wiki import search
SYSTEM_PROMPT = (
"Answer questions by looking facts up; never rely on memory for them. "
"Before each set of tool calls, write one sentence saying what you still need to know and why. "
"Request independent lookups together. When the observations answer the question, reply with the "
"answer and the evidence for it."
)
model = init_chat_model("<provider>:<model>", temperature=0)
agent = create_agent(
model,
tools=[search],
system_prompt=SYSTEM_PROMPT,
middleware=[ModelCallLimitMiddleware(run_limit=8)], # a step budget: stops the run cleanly at 8 model calls
)
run.py
from react_agent import agent
question = (
"Which was founded first: the university where Alan Turing earned his PhD, "
"or the one where Grace Hopper earned hers?"
)
result = agent.invoke({"messages": [("user", question)]})
for m in result["messages"][1:]:
if m.type == "ai":
label = "Thought: " if m.tool_calls else "Answer: "
if m.content:
print(label, m.content)
for call in m.tool_calls:
print(f"Action: {call['name']}({call['args']['entity']!r})")
elif m.type == "tool":
print("Observation: ", m.content[:88] + ("..." if len(m.content) > 88 else ""))

It’s a two-hop question twice over: find each person’s university, then each university’s founding year. With a scripted model standing in for a real one, the run printed (the observations are the real tool output):

Thought: I need the universities where Turing and Hopper earned their PhDs.
Action: search('Turing')
Action: search('Grace Hopper')
Observation: No article titled 'Turing'. Similar titles: ['Alan Turing'].
Observation: Grace Hopper (1906-1992) was an American computer scientist and United States Navy rear ...
Thought: There is no article titled 'Turing'; the similar title is Alan Turing.
Action: search('Alan Turing')
Observation: Alan Turing (1912-1954) was an English mathematician, computer scientist, and cryptanaly...
Thought: Turing: Princeton. Hopper: Yale. Now I need both founding years.
Action: search('Princeton University')
Action: search('Yale University')
Observation: Princeton University is a private research university in Princeton, New Jersey. Founded ...
Observation: Yale University is a private research university in New Haven, Connecticut. Founded in 1...
Answer: Yale was founded first. Grace Hopper earned her PhD at Yale (founded 1701), and Alan Turing earned his at Princeton (founded 1746), so Yale is 45 years older.

Two things the paper’s format couldn’t do. The two people, and later the two universities, were looked up in parallel: five actions took three tool rounds instead of five. And the first search missed, which is the paper’s “search returned nothing useful” failure: the observation suggested a better title, the next thought used it, and the agent recovered in one step. That’s interleaving earning its keep: a plan written up front would have kept going with the empty result.

5. Where it breaks

Myopia. ReAct decides one step at a time. On tasks with a long horizon or real dependencies (“migrate these 40 services”), it wanders, revisits work, and loses track of the overall goal, because nothing in the loop holds a plan. That’s the motivation for planning-first architectures in the next post.

Loops and compounding errors. The paper’s most common ReAct-specific failure is repeating the previous thought and action. A wrong observation early (a stale record, the wrong entity) also propagates: every later thought builds on it.

Cost grows quadratically. Every model call re-sends the whole conversation. These are the measured prompt sizes for the four model calls in the run above (approximate token counts, tool schemas excluded):

Measured on the run above with count_tokens_approximately. Each call adds its observations to every later prompt.

If each step adds about the same number of tokens, the prompt grows linearly and the total tokens across the run grow with the square of the step count. With real search results (thousands of tokens each, not 80), a 15-step run gets expensive and slow, and long contexts also degrade attention to the middle of the transcript.

Latency is serial. Every step is a full model round trip, and steps can’t overlap. Parallel tool calls help within a step, not across steps.

6. Guardrails

  • Budgets. ModelCallLimitMiddleware(run_limit=...) caps model calls per run and, by default, ends with a message rather than an exception; ToolCallLimitMiddleware caps calls per tool. Pair them with the graph’s recursion_limit as a last resort.
  • Detect repetition. A tool call identical to the previous one is almost always a loop. Reject it with an observation that says so (“you already searched for this; use the result above or try a different query”).
  • Manage the context. Truncate observations to what the model needs, and use SummarizationMiddleware or ContextEditingMiddleware to shrink old turns in long runs.
  • Invest in tools. 23% of ReAct’s failures in the paper came from searches that returned nothing useful. Suggestions on a miss (like the search above), better ranking, and clear descriptions move accuracy more than prompt tweaks.
  • Plan a fallback. The paper’s best HotpotQA result fell back to chain-of-thought when ReAct ran out of steps. The production version: when the budget is exhausted, answer from what was gathered and say what’s missing, rather than stopping with nothing.
  • Know when not to use it. If the steps are known in advance, a fixed workflow is cheaper and more reliable than an agent choosing them. If the task is long and decomposable, plan first, then execute.

7. Pitfalls

  • Letting the model write observations. In text-based ReAct, a missing stop sequence lets the model invent tool results. With native tool calling, the equivalent is a prompt that encourages answering from memory.
  • Treating thoughts as truth. A thought is the model’s narration, not a log of what the system did. Debug from the tool calls and observations.
  • Requiring visible thoughts from reasoning models. Models with built-in reasoning already think before acting; asking them to also narrate in the message mostly adds tokens. Keep the instruction for models without it.
  • One tool, many jobs. A single search that’s also expected to compute, filter, and compare pushes reasoning into the tool’s inputs. Give arithmetic and comparisons their own tools, or let the model do them in thoughts.
  • No budget. Without one, the loop failure mode is “runs until the recursion limit and raises”.

Study checklist

  1. Run react_text.py with a real model, delete the stop argument, and look for invented observations.
  2. Run run.py with a real model and compare how many tool rounds it takes with and without “Request independent lookups together” in the system prompt.
  3. Make search return nothing for one entity and see whether the agent recovers or loops.
  4. Log prompt tokens per call for a 10-step task with realistic tool outputs and fit the curve.
  5. Add a check that rejects a tool call identical to the previous one, and test it on a question that tends to loop.

References

Papers

Documentation and guides