What is the ReAct pattern?

Learning path, stage 4 of 5: Agents, tools and MCP · question 3 of 10

ReAct (Reason + Act) mixes reasoning with actions: the model thinks about what to do, calls a tool, reads the observation, thinks again, and repeats. Reasoning guides which actions to take, and real observations keep the reasoning grounded, which reduces hallucination compared with reasoning alone.

The loop

Thought: I need the population of the city first.
Action: search("population of Pune 2025")
Observation: ~7.4 million (metro)
Thought: Now compare with Mumbai...
Action: ...
Final Answer: ...

Why it mattered

  • Before ReAct, CoT reasoned without facts, and tool-using models acted without a plan.
  • It's the conceptual basis of most modern agents.
  • Today it's built into APIs: models emit thinking and tool calls natively, so you don't parse "Action:" lines with regex any more.

Weak points

  • It can loop, repeating the same search. Add step limits and detect repeats.
  • Errors compound over long chains. Add checks, reflection or a human checkpoint.

Sources

Code example

tsx
1// Classic text-based ReAct (how it worked before native tool calling).
2declare function llm(prompt: string): Promise<string>;
3const TOOLS: Record<string, (q: string) => Promise<string>> = {
4 search: async (q) => `results for ${q}...`,
5 calculate: async (expr) => String(Function(`"use strict";return (${expr})`)()), // demo only: never eval untrusted input
6};
7
8export async function react(question: string, maxSteps = 6) {
9 let scratchpad = "";
10 for (let i = 0; i < maxSteps; i++) {
11 const out = await llm(
12 `Answer the question. Use this format:\nThought: ...\nAction: tool[input]\n` +
13 `or\nFinal Answer: ...\nTools: search, calculate\n\nQuestion: ${question}\n${scratchpad}`,
14 );
15 const final = out.match(/Final Answer:\s*([\s\S]*)/);
16 if (final) return final[1].trim();
17
18 const act = out.match(/Action:\s*(\w+)\[([\s\S]*?)\]/);
19 if (!act || !TOOLS[act[1]]) { scratchpad += `${out}\nObservation: invalid action\n`; continue; }
20 const obs = await TOOLS[act[1]](act[2]);
21 scratchpad += `${out}\nObservation: ${obs}\n`;
22 }
23 return "Gave up after max steps";
24}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod @modelcontextprotocol/sdk, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app