Chapter 3 of 32 · ~22 min read & lab+80 XP
Chapter 3 · Agentic AI

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.

What Is It?

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.

Why Is It Required?

Pure LLMs hallucinate live facts and math; grounding every reasoning step in real tool observations turns a chatbot into a problem-solving agent.

Everyday Analogy: A detective forming a hypothesis (Thought), running a lab test (Action), reading the lab report (Observation), and updating their theory.
Why ML Engineers & Data Scientists Actually Need This

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!

ML / AI Engineer

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.

Data Scientist

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!

Interview & Debug Edge

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!'

Step 0 · Test Your Gut Before Any Math!

In a ReAct loop using modern Tool Calling APIs, what signals the outer Python while loop to STOP iterating and return to the user?

What You Will Master in This Chapter
  • 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_steps termination
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
Thought→Action→Obs\text{Thought} \to \text{Action} \to \text{Obs}Say aloud:“ReAct step triplet”
Plain-English Meaning
Interleaving internal reasoning with external tool invocation and real environment feedback
Everyday Example
Thought → get_price('NVDA') → $140
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

Everyday Story First (Zero Math Yet!)

Drag the Steps slider in the mini-lab below to see how cumulative input tokens grow across a multi-step ReAct loop!

The ReAct Execution Cycle: Thought → Action → Observation → Repeat1. THOUGHTReason about gap2. ACTIONCall tool(args)3. OBSERVATIONReal tool outputFINAL ANSWERExit loop ✓Append Observation to messages[] → Loop back to Thought until done!
ReAct interleaves Reasoning (Thought) with Acting (Tool Call) and Grounding (Observation) in a loop until the agent emits a Final Answer.

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."
Animated Mini-Lab • 1.2

Quadratic Token Growth in Multi-Step ReAct Loops

Final Step Context Length
2,200 tok
Cumulative Input Tokens Billed
7,500 tok

2. Append-Only Trace Anatomy & Prefix Caching Synergy

Everyday Story First (Zero Math Yet!)

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!

Anatomy of a ReAct Trace Inside the Messages ArrayUSERWhat is 15% of NVDA's current stock price?ASSTThought: Need live price. Action: get_price(ticker='NVDA')TOOLObservation: {'ticker': 'NVDA', 'price': 140.00}ASSTThought: 0.15 * 140 = 21. Final Answer: $21.00 ✓
Under the hood, a ReAct loop is simply an append-only list of [System, User, Assistant(Thought+Call), Tool(Observation), ...] messages fed back to the LLM!

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

Everyday Story First (Zero Math Yet!)

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).

Pure Chain-of-Thought (Closed Book) vs. ReAct (Open Environment)Chain-of-Thought Only• Relies 100% on stale parametric weights• Error in step 1 snowballs unchecked• Cannot inspect DBs, APIs, or live filesReAct (Reason + Act + Observe)• Fetches live ground-truth via Observations• Self-corrects when a tool returns an error• Dramatically slashes factual hallucinations ✓
Pure Chain-of-Thought reasons purely inside frozen weights (hallucinating stale facts); ReAct grounds every step against live Observations from external tools!

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!
Walk Through With Me · Interactive Worked Example

Worked Example: Tracing a 2-Step ReAct Run

User asks: 'What is 15% of NVDA stock price?' Tools: get_price(ticker).

11. Step 1 (LLM → Tool Call)Step 1 / 2

LLM sees no live price in context → emits get_price(ticker='NVDA'). Harness executes it and appends Observation: 140.00.

Teacher's Note: No guessing from 2024 training data!
Pause & Check · Quick Intuition Pulse

Why should a ReAct loop keep messages[] strictly append-only across steps 1..N?

Try It YourselfStandard

In older text-based ReAct prompting (before native Tool Calling APIs), why did developers MUST pass stop=['Observation:'] to the LLM?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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!

Interactive Visual Lab
Lab Challenge: Watch all 5 turns of the 60 FPS ReAct Trace Stepper execute Thought → Action → Observation → Final Answer.
Interactive Animation • 1.2 Deep Lab

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.

Turn 1 / 5
[THOUGHT]I need Tokyo's live temperature in °C before converting to °F.
0%
THOUGHT
Intuition Takeaway: The ReAct loop is an append-only 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.
Where This Powers Real ML, Deep Learning & Generative AI

Research, Support & Coding Assistants

Every major coding and research agent runs a variant of the ReAct Thought → Tool → Observation loop.

Production NumPy & PyTorch Code Patterns
# 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])
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting to attach the matching tool_call_id when appending a role: 'tool' Observation message.
Best Practice: OpenAI/Anthropic/Gemini APIs strictly validate that every tool_call_id in an Assistant message has a matching role: 'tool' reply before the next LLM call!
Chapter Mastery Check (+80 XP)
Score: 0 / 1
1In a modern Tool-Calling ReAct loop, how does the harness know the agent has reached its Final Answer?

Apply What You Learned — Solve Matching Coding Problems