The ReAct Loop Explained: Thought → Action → Observation Execution Cycles
How the foundational ReAct (Reasoning + Acting) loop works under the hood: append-only message traces, grounding Thoughts in live Tool Observations, stop sequences, and building a clean ReAct loop in 25 lines of Python.
The ReAct (Reason + Act) loop alternates between generating a short reasoning Thought, executing an external Tool Action, and feeding the real-world Observation back into context until done.
Pure LLMs hallucinate live facts and math; grounding every reasoning step in real tool observations turns a chatbot into a problem-solving agent.
Strip away every fancy agent framework (LangGraph, CrewAI, AutoGen, OpenAI Agents SDK) and at the heart of ALL of them sits the exact same 25-line ReAct while loop!
Knowing how to write a clean ReAct loop from scratch with messages.append(...), tool dispatch, and max_steps gives you 100% control and debuggability without framework black boxes.
Understanding why Prompt Caching hits on 95%+ of the prefix across ReAct turns (because messages[] is strictly append-only!) saves up to 80% on multi-turn agent bills!
The #1 Agentic AI coding interview prompt: 'Implement a basic ReAct agent loop in Python that calls tools, appends observations, and returns the Final Answer or aborts at max_steps!'
In a ReAct loop using modern Tool Calling APIs, what signals the outer Python while loop to STOP iterating and return to the user?
- Trace the ReAct execution cycle: Thought (reasoning) → Action (tool call) → Observation (tool output) → Final Answer
- Understand how a ReAct loop is implemented as an append-only
messages[]list passed to a stateless LLM API - Explain why ReAct dramatically reduces hallucinations compared to pure Chain-of-Thought (closed-book vs. grounded observations)
- Compute quadratic token growth across multi-step ReAct loops and enforce clean
max_stepstermination
Imagine a detective solving a case with a notebook (messages[]). Pure Chain-of-Thought locks the detective in an empty room to guess from memory. ReAct lets the detective think out loud (Thought), make a phone call or check a database (Action), write the real answer into the notebook (Observation), and repeat until the mystery is solved (Final Answer)!
1. The ReAct Cycle: Interleaving Reasoning & Environment Grounding
Drag the Steps slider in the mini-lab below to see how cumulative input tokens grow across a multi-step ReAct loop!
The Canonical 15-Line ReAct Loop
for step in range(max_steps):
resp = llm.chat(messages, tools=TOOL_SCHEMAS)
messages.append(resp)
if not resp.tool_calls:
return resp.content # Final Answer!
for call in resp.tool_calls:
obs = dispatch_tool(call.name, call.args)
messages.append({"role": "tool", "tool_call_id": call.id, "content": obs})
return "Reached max_steps without final answer."
Quadratic Token Growth in Multi-Step ReAct Loops
2. Append-Only Trace Anatomy & Prefix Caching Synergy
Because every ReAct turn strictly appends new Assistant and Tool messages to the end of messages[], turns 2..10 reuse the KV-Cache of all prior turns automatically!
Never Mutate Earlier Messages Mid-Loop!
If you edit the System Prompt or insert a live timestamp at index 0 between step 2 and step 3, you invalidate the entire KV-Cache prefix! Keep messages[] strictly append-only during an active run so Prefix Caching cuts multi-step TTFT and cost by up to 80%!
3. Why ReAct Beats Pure Chain-of-Thought on Grounded Tasks
Yao et al. (ICLR 2023) showed that pairing Thought + Action dramatically reduces both hallucination (CoT's weakness) and aimless tool-spamming (Act-only's weakness).
Synergy of Reasoning + Acting
- Thought guides Action: Writing a brief plan before calling a tool helps the LLM pick the right parameters and avoid redundant calls.
- Observation grounds Thought: Real API/database results immediately override stale parametric guesses!
Worked Example: Tracing a 2-Step ReAct Run
User asks: 'What is 15% of NVDA stock price?' Tools: get_price(ticker).
LLM sees no live price in context → emits get_price(ticker='NVDA'). Harness executes it and appends Observation: 140.00.
Why should a ReAct loop keep messages[] strictly append-only across steps 1..N?
In older text-based ReAct prompting (before native Tool Calling APIs), why did developers MUST pass stop=['Observation:'] to the LLM?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
No! With native Tool Calling + built-in thinking tokens, the model already reasons internally before emitting structured tool_calls — you just run the clean while loop over resp.tool_calls!
ReAct Loop Execution Trace: Thought → Action → Observation
Watch the append-only message history grow step-by-step as tool Observations ground the LLM's next Thought.
messages[] cycle of Thought → Action → Observation that grounds LLM reasoning in live environment feedback until the model emits a Final Answer (zero tool calls) or hits max_steps.Research, Support & Coding Assistants
Every major coding and research agent runs a variant of the ReAct Thought → Tool → Observation loop.
# Minimal ReAct (Reason + Act) Execution Loop with Tool Registry
TOOLS = {
"get_price": lambda item: {"gpu": 1999, "ssd": 149}.get(item, 0),
"calc_tax": lambda amount: round(float(amount) * 0.08, 2),
}
def mock_llm_react(scratchpad: list[str]) -> tuple[str, str, str]:
if len(scratchpad) == 0:
return ("Need the base price of a gpu first.", "get_price", "gpu")
if len(scratchpad) == 1:
return ("Now compute 8% sales tax on 1999.", "calc_tax", "1999")
return ("I have both price and tax; ready to answer.", "finish", "Total = $2158.92")
scratchpad: list[str] = []
for step in range(1, 6):
thought, action, arg = mock_llm_react(scratchpad)
if action == "finish":
print(f"Step {step} FINAL: {arg}")
break
obs = TOOLS[action](arg)
scratchpad.append(f"Thought: {thought} | Action: {action}({arg}) | Obs: {obs}")
print(scratchpad[-1])
tool_call_id when appending a role: 'tool' Observation message.tool_call_id in an Assistant message has a matching role: 'tool' reply before the next LLM call!