ReAct explained: the reason-act-observe loop from the paper to LangChain 1.5 code
ReAct is the loop under almost every tool-using agent. This guide walks through the original paper step by step, rebuilds its prompt format in plain Python, runs the same agent with LangChain 1.5, and shows what the paper measured and what the loop costs.
- Reading time
- 15 min
- Sections
- 7
- Code examples
- 5
- Tables
- 2
- Sources
- 7
- Published
- 24 Nov 2026
- What changed
- The ReAct paper appears on arXiv
- Why it matters
- Cost grows faster than steps.
- What to do
- Start with the framework loop
ReAct, short for "reasoning and acting", is the pattern that turned language models into agents. The model writes a thought, picks an action, reads what the action returned, and repeats until it can answer. Almost every agent framework in late 2026, from LangChain's create_agent to the OpenAI Agents SDK, runs a version of this loop, even when the "thought" is now hidden inside a reasoning model.
Knowing the original algorithm matters for a practical reason. When an agent loops forever, calls the wrong tool or invents an observation, the fix is almost always in one of the three parts ReAct defines: the prompt, the action space or the stopping rule. This article explains each part from the paper, rebuilds it in about 40 lines of Python, then runs the same task with LangChain 1.5.
What happened
The ReAct paper appears on arXiv (6 October 2022)
Shunyu Yao and co-authors from Princeton and Google Research posted "ReAct: Synergizing Reasoning and Acting in Language Models". The idea was simple: instead of asking a model to reason only (chain of thought) or act only (output commands), let it interleave free-text reasoning traces with actions that change or query an environment. The paper tested this on question answering, fact checking, a text game and a shopping website.
ReAct is published at ICLR 2023 (May 2023)
The paper was accepted to the International Conference on Learning Representations 2023. Its prompting code and results for HotpotQA, FEVER, ALFWorld and WebShop are public in the authors' GitHub repository, which also reports a re-run with GPT-3 (text-davinci-002) next to the paper's PaLM-540B numbers.
LangChain 1.5.2 and LangGraph 1.2.24 ship the loop as a default (18 and 20 November 2026)
The current LangChain release builds every agent with create_agent, which compiles a LangGraph graph with a model node and a tools node joined by a loop. That is ReAct with native tool calls instead of parsed text. The code later in this article was run against langchain==1.5.2 and langgraph==1.2.24.
How the ReAct loop works, step by step
Think of a detective. A detective does not solve a case by thinking alone in a dark room, and does not solve it by knocking on random doors either. They think ("the alibi depends on the train time"), act ("check the timetable"), observe ("the train left at 9:40"), and think again. ReAct gives a language model the same rhythm.
The paper formalises it like this. At each time step the agent receives an observation from the environment and chooses an action. ReAct widens the action space with one extra kind of action: a "thought", which is free language. A thought does not change the environment and returns no observation. It only updates the context the model will read on the next step. Everything else is ordinary acting.
The loop then runs in five steps:
- Build the prompt. A few solved examples (the paper used one to six), then the new question.
- Generate a thought. The model writes "Thought n: ..." where it decomposes the task, tracks progress or notes an exception.
- Generate an action. The model writes "Action n: ..." in a fixed format the runtime can parse.
- Execute and observe. The runtime, not the model, runs the action and appends "Observation n: ...".
- Repeat or stop. The loop ends when the model emits a finish action or a step limit is hit.
For the knowledge tasks, HotpotQA and FEVER, the paper gave the model a tiny Wikipedia API with three actions: search[entity] returns the first sentences of a page or suggests similar titles, lookup[string] returns the next sentence containing the string on the current page, and finish[answer] ends the episode. The API was kept deliberately weak, so the model had to reason about what to look up next.
The prompt format
A ReAct prompt is a list of worked trajectories followed by the new question. Each trajectory looks like this:
Question: What is the elevation range for the area that the eastern sector
of the Colorado orogeny extends into?
Thought 1: I need to search Colorado orogeny, find the area that the eastern
sector extends into, then find the elevation range of that area.
Action 1: Search[Colorado orogeny]
Observation 1: The Colorado orogeny was an episode of mountain building ...
Thought 2: ...
Action 3: Finish[1,800 to 7,000 ft]
The model never writes an "Observation" line itself. In the original text-completion setup the runtime stopped generation at the word "Observation", ran the tool and pasted the result. If you forget that stop sequence, the model will happily invent observations, which is the classic ReAct hallucination.
A runnable ReAct loop in plain Python
The code below rebuilds the loop with a scripted model, so it runs with no API key. Replace llm() with a real completion call and keep everything else.
import re
DOCS = {
"Colorado orogeny": "The Colorado orogeny was an episode of mountain building in Colorado "
"and surrounding areas. The eastern sector extends into the High Plains.",
"High Plains": "The High Plains are a subregion of the Great Plains. They rise in elevation "
"from around 1,800 to 7,000 ft.",
}
def search(q):
return DOCS.get(q, f"Could not find [{q}]. Similar: {list(DOCS)}")
def lookup(q, last_page):
hits = [s for s in DOCS.get(last_page, "").split(". ") if q.lower() in s.lower()]
return hits[0] if hits else "No more results."
SCRIPT = iter([ # what a few-shot prompted model would write, one call at a time
"Thought 1: I need to search Colorado orogeny, find the area its eastern sector extends "
"into, then find that area's elevation range.\nAction 1: Search[Colorado orogeny]",
"Thought 2: The eastern sector extends into the High Plains. I need the elevation range "
"of the High Plains.\nAction 2: Search[High Plains]",
"Thought 3: The High Plains rise from around 1,800 to 7,000 ft, so the answer is "
"1,800 to 7,000 ft.\nAction 3: Finish[1,800 to 7,000 ft]",
])
def llm(prompt):
return next(SCRIPT)
def react(question, max_steps=6):
prompt, last_page = f"Question: {question}\n", None
for step in range(1, max_steps + 1):
out = llm(prompt)
prompt += out + "\n"
m = re.search(r"Action \d+: (\w+)\[(.*)\]", out)
if not m:
obs = "Invalid action. Use Search[...], Lookup[...] or Finish[...]."
else:
kind, arg = m.groups()
if kind == "Finish":
return arg, step
if kind == "Search":
obs, last_page = search(arg), arg
elif kind == "Lookup":
obs = lookup(arg, last_page)
else:
obs = f"Unknown action {kind}."
prompt += f"Observation {step}: {obs}\n" # written by the runtime
return None, max_steps
print(react("What is the elevation range for the area that the eastern sector "
"of the Colorado orogeny extends into?"))
Running it prints ('1,800 to 7,000 ft', 3). Three details carry over to any real agent. The parse failure branch returns an error as an observation instead of crashing, so the model can correct itself. The max_steps guard is the only thing that stops a confused model. And the prompt grows on every step, which is where the cost comes from.
What the paper measured
The paper used PaLM-540B with few-shot prompts and compared ReAct with standard prompting, chain of thought (CoT), CoT with self-consistency (CoT-SC) and an "Act" baseline that has actions but no thoughts.
| Task | What the agent does | Headline finding reported in the paper |
|---|---|---|
| HotpotQA | Multi-hop questions over a Wikipedia API | ReAct reduces hallucination compared with CoT; the best results come from combining ReAct with CoT-SC |
| FEVER | Verify a claim against Wikipedia | ReAct beats CoT; again best when combined with CoT-SC |
| ALFWorld | Text game: find and place household objects | Beats imitation and RL baselines by 34 points absolute success rate |
| WebShop | Buy a product matching an instruction on a simulated site | Beats imitation and RL baselines by 10 points absolute success rate |
The decision-making gains came from one or two in-context examples, against baselines trained on thousands of demonstrations. The authors' repository lists the ReAct numbers per task:
| Model | HotpotQA EM | FEVER EM | ALFWorld success | WebShop success |
|---|---|---|---|---|
| PaLM-540B (paper) | 29.4 | 62.2 | 70.9 | 40 |
| GPT-3 text-davinci-002 (repo re-run) | 30.4 | 54 | 78.4 | 35.8 |
HotpotQA and FEVER were scored on 500 random development examples. Two points stand out. First, ReAct alone did not beat chain of thought on HotpotQA exact match. Its advantage was grounding: fewer invented facts, and a trace you can audit. Second, the paper's own error analysis found that a large share of ReAct failures came from searches that returned nothing useful, after which the model struggled to recover. That is why the paper proposed switching between methods: fall back from ReAct to CoT-SC when the agent does not finish within a step budget, and from CoT-SC to ReAct when the sampled answers disagree.
Why thoughts help on long tasks
On ALFWorld the "Act" baseline often lost track of sub-goals: it picked up the right object and then forgot what it was for. Thoughts work like a notepad. "Now I have the pan, next I need to clean it at the sink" costs a few tokens, but keeps the goal inside the context the model reads on every step. Modern reasoning models do this internally, which is why many current frameworks no longer ask for an explicit "Thought:" line, but the function is the same.
Continue learning
How this article connects
4 pages link to or from it. Drag to turn, click a dot to open it.
ReAct in current frameworks
The text format above was designed for completion models in 2022. Today models return structured tool calls, so the runtime no longer parses Action n: Search[...]. The loop is unchanged. Here is the same agent on LangChain 1.5.2, with a fake chat model so it runs offline:
from langchain.agents import create_agent
from langchain.tools import tool
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
from langchain_core.messages import AIMessage
PAGES = {
"Colorado orogeny": "The eastern sector extends into the High Plains.",
"High Plains": "The High Plains rise in elevation from around 1,800 to 7,000 ft.",
}
@tool
def search(entity: str) -> str:
"""Return the first sentences of the encyclopedia page for an entity."""
return PAGES.get(entity, f"No page for {entity}.")
class FakeToolModel(FakeMessagesListChatModel):
def bind_tools(self, tools, **kwargs): # the fake model ignores tool schemas
return self
model = FakeToolModel(responses=[
AIMessage(content="", tool_calls=[{"name": "search", "args": {"entity": "Colorado orogeny"}, "id": "c1"}]),
AIMessage(content="", tool_calls=[{"name": "search", "args": {"entity": "High Plains"}, "id": "c2"}]),
AIMessage(content="About 1,800 to 7,000 ft."),
])
agent = create_agent(model, tools=[search], system_prompt="Answer with the search tool.")
result = agent.invoke({"messages": [{"role": "user",
"content": "Elevation range of the area the eastern Colorado orogeny extends into?"}]})
for m in result["messages"]:
print(f"{m.type:>5}: {m.content or m.tool_calls}")
The output is the ReAct trace in message form:
human: Elevation range of the area the eastern Colorado orogeny extends into?
ai: [{'name': 'search', 'args': {'entity': 'Colorado orogeny'}, 'id': 'c1', 'type': 'tool_call'}]
tool: The eastern sector extends into the High Plains.
ai: [{'name': 'search', 'args': {'entity': 'High Plains'}, 'id': 'c2', 'type': 'tool_call'}]
tool: The High Plains rise in elevation from around 1,800 to 7,000 ft.
ai: About 1,800 to 7,000 ft.
The mapping is direct. An AIMessage with tool_calls is "Action n". A ToolMessage is "Observation n". An AIMessage without tool calls is finish[...]. The thought is either the text the model writes beside its tool call or the hidden reasoning of a thinking model. To swap in a real model, pass a "provider:model" string or any chat model object as the first argument and delete the fake class. The LangGraph graph that create_agent compiles is the same two-node loop you would draw by hand, and you can watch it run in the ReAct tool-calling simulation.
What it means in practice
Cost grows faster than steps. Every step re-sends the whole history. If the system prompt and tools take 2,000 tokens and each step adds 400 tokens of thought, call and observation, a 6-step run reads 2,000, 2,400, 2,800, 3,200, 3,600 and 4,000 input tokens: 18,000 in total, against 2,000 for a single call. That roughly quadratic growth is why prompt caching matters so much for agents, as the agent loop token cost simulation shows.
The step limit is a product decision. A low limit cuts cost and stops runaway loops, but fails tasks that genuinely need more hops. The paper itself used a step budget and fell back to CoT-SC when it ran out. The step limit simulation lets you see how solved tasks and cost per task move as you change the cap.
Observations are untrusted input. Whatever a tool returns goes straight into the prompt. A web page that says "ignore your instructions" lands in the same context as your system prompt, which is the root of indirect prompt injection. See prompt injection defence for the standard layers.
ReAct is the baseline, not the ceiling. Plan-and-execute, ReWOO, Reflexion and tree search were all proposed as fixes for specific ReAct weaknesses: too many calls, no learning from failure, or a single greedy path. The agentic patterns simulation compares them side by side.
What to do now
- Start with the framework loop. Use
create_agentin LangChain or the equivalent in your stack rather than parsing "Action:" lines yourself; native tool calls remove a whole class of format errors. - Set an explicit step limit. Pick a number from your traces, for example the 95th percentile of steps on solved tasks plus two, and log every run that hits it.
- Return errors as observations. Bad arguments, timeouts and empty results should come back to the model as text it can act on, not as exceptions that kill the run.
- Write tool descriptions for the model. The docstring is the only manual the model gets. Say what the tool returns, when it returns nothing and what to try next.
- Keep observations short. Truncate or summarise long tool outputs before they enter the history; each extra token is paid again on every later step.
- Trace every run. Record thoughts, calls and observations so you can see where loops start. The agent loop walkthrough shows what a good trace contains.
- Add a fallback. Copy the paper's idea: when the agent hits its budget, fall back to a cheaper non-tool answer or a human, instead of returning nothing.
- Evaluate trajectories, not just answers. Check that the right tools were called in a sensible order, using function calling logs as the ground truth.
Risks and open questions
Hallucinated observations still happen. If a model is allowed to write text that looks like a tool result, or the runtime does not enforce the boundary, the agent can "observe" facts that never came from a tool. Native tool-call APIs reduce this but do not eliminate made-up claims in the final answer.
Greedy search gets stuck. ReAct follows one path. One unhelpful search result can derail the whole trajectory, as the paper's error analysis found. Search-based methods such as LATS exist because of this.
Reported numbers are old and model-specific. The headline results used PaLM-540B and GPT-3 era models on four benchmarks. Current models are far stronger, so treat the paper as evidence for the mechanism, not as a prediction of your accuracy.
Hidden reasoning changes debugging. With reasoning models the "thought" is often summarised or hidden. You gain accuracy but lose part of the audit trail that made ReAct attractive.
Watch next: how frameworks combine ReAct loops with planners and parallel tool calls, how far prompt caching cuts the quadratic history cost, and whether trajectory-level evaluation becomes a standard part of agent CI.
Frequently asked questions
What is the difference between ReAct and chain of thought?
Chain of thought only reasons inside the model, so it cannot fetch new facts and may invent them. ReAct interleaves reasoning with actions that return real observations. The paper found ReAct more grounded and easier to audit, while CoT was sometimes better at pure reasoning structure.
Do I still need "Thought:" lines with modern models?
Not usually. Tool-calling APIs carry the action and the result as structured messages, and reasoning models think internally. Some teams still ask for a short visible plan before each call because it makes traces easier to read.
How many steps should a ReAct agent take?
There is no universal number. Measure the distribution of steps on tasks your agent solves, set the limit a little above its upper tail, and treat hitting the limit as a failure that needs a fallback.
Why does my ReAct agent loop on the same tool call?
Usually the observation gives it nothing new, so it repeats the action. Return clearer "not found" messages with suggestions, deduplicate identical calls, or add middleware that stops a run after repeated identical calls.
Is ReAct the same as a LangGraph agent?
create_agent in LangChain 1.5 compiles a LangGraph graph that implements the ReAct loop with native tool calls. LangGraph itself is more general: you can build plan-and-execute, reflection or multi-agent graphs with it as well.
Summary
ReAct lets a language model alternate between thinking, acting and observing. The 2022 paper showed that this interleaving reduces hallucination on knowledge tasks and beats trained imitation and RL baselines on ALFWorld and WebShop with one or two examples. The loop is easy to write: a prompt, a parser or tool-call API, a tool runner that writes observations, and a step limit. Its weaknesses, a growing context, greedy single-path search and untrusted observations, are what later patterns such as ReWOO, Reflexion and LATS were designed to fix. In LangChain 1.5 the same loop is one call to create_agent.
Sources
Cite this article
Kelahmet, Ö. C. (2026, November 24). ReAct explained: the reason-act-observe loop from the paper to LangChain 1.5 code. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/react-reason-act-loop-paper-code
BibTeX
@online{kelahmet2026react,
author = {Kelahmet, {\"O}zer Cem},
title = {{ReAct explained: the reason-act-observe loop from the paper to LangChain 1.5 code}},
year = {2026},
month = {nov},
url = {https://www.ozercemkelahmet.com/articles/react-reason-act-loop-paper-code}
}Version historyfirst version
- Published
Factual corrections are listed here with what changed. Wording and formatting edits are not listed.