The ReAct pattern mixes thinking and doing
The ReAct pattern is a way for an AI agent to think, act, look at the result and think again. ReAct is short for reasoning and acting.
It matters because a model alone cannot see today's bus times. With ReAct it writes a thought, asks for a tool, reads what the tool says and only then answers.
By the end of this lesson
Note
I can run a ReAct loop and read its trace.
Key words
| Word | What it means | Example |
|---|---|---|
| Thought | a line where the model plans its next move | |
| Action | a line naming a tool and its input | timetable[7] |
| Observation | the tool's result, written by your code | |
| Trace | every line of one run, in order | |
| Final answer | the line that ends the loop | |
| Stand-in model | a script that gives fixed replies |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsA thought, an action, an observation
A 2022 research paper named the pattern ReAct. The model writes a Thought line to plan. Then it writes an Action line with a tool name and an input in square brackets.
Your code reads that line, runs the tool and adds an Observation line with the result. The model reads it and writes the next Thought. A Final Answer line ends the loop.
Who writes each line of the trace
| Line | Written by | Example |
|---|---|---|
| Thought: | The model | Thought: I need the times of bus route 7. |
| Action: | The model | Action: timetable[7] |
| Observation: | Your code, after it runs the tool | Observation: 09:10 25 |
| Final Answer: | The model | Final Answer: You reach B12 at 09:42. |
The cells students fill in are left blank in this preview.
Check
Have a go
Check
3 questionsWrite the ReAct loop, part 1
docker exec -w /home/node/project agent sh -c "printf '%s\n' 'const TIMES = { \"7\": \"09:10 25\", \"12\": \"08:50 35\" };' 'const WALKS = { B12: \"7\", A3: \"4\" };' 'function add(arg) {' ' const parts = arg.split(\" \");' ' const hm = parts[0].split(\":\");' ' const all = Number(hm[0]) * 60 + Number(hm[1]) + Number(parts[1]);' ' return String(Math.floor(all / 60)).padStart(2, \"0\") + \":\" + String(all % 60).padStart(2, \"0\");' '}' 'const TOOLS = { timetable: function (a) { return TIMES[a]; }, walk: function (a) { return WALKS[a]; }, add: add };' 'const STEPS = [' ' \"Thought: I need the times of bus route 7.\",' ' \"Action: timetable[7]\",' ' \"Thought: It leaves at 09:10 and takes 25 minutes.\",' ' \"Action: add[09:10 25]\",' ' \"Action: walk[B 12]\",' ' \"Thought: The room code has no space. I try again.\",' ' \"Action: walk[B12]\",' ' \"Action: add[09:35 7]\",' ' \"Final Answer: You reach B12 at 09:42, 12 minutes after the 09:30 start.\",' '];' > react1.js"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the ReAct loop, part 2
docker exec -w /home/node/project agent sh -c "printf '%s\n' 'const LIMIT = 6;' 'function parse(line) {' ' const body = line.slice(8);' ' const open = body.indexOf(\"[\");' ' if (open < 1 || body.endsWith(\"]\") === false) return null;' ' return { tool: body.slice(0, open), arg: body.slice(open + 1, -1) };' '}' 'function observe(step) {' ' const tool = TOOLS[step.tool];' ' if (tool === undefined) return \"Error: \" + \"no tool\" + \" \" + step.tool;' ' const out = tool(step.arg);' ' return out === undefined ? \"Error: \" + \"no result\" : out;' '}' 'let actions = 0;' 'for (const line of STEPS) {' ' console.log(line);' ' if (line.startsWith(\"Final Answer:\")) break;' ' if (line.startsWith(\"Action: \")) {' ' const step = parse(line);' ' console.log(\"Observation: \" + (step ? observe(step) : \"Error: \" + \"not an action\"));' >> react1.js"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the ReAct loop, part 3
docker exec -w /home/node/project agent sh -c "printf '%s\n' ' actions = actions + 1;' ' if (actions === LIMIT) { console.log(\"Stopped: the action limit was reached.\"); break; }' ' }' '}' 'console.log(\"Actions\" + \": \" + actions);' >> react1.js"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Run the ReAct loop
docker exec -w /home/node/project agent node react1.jsShown here, not run. Press Start lab to type it into your own lab’s terminal.
What the loop prints
| Line | What happened |
|---|---|
| Action: timetable[7] | Observation: 09:10 25, so the bus leaves at 09:10 and takes 25 minutes |
| Action: add[09:10 25] | Observation: 09:35, the time the bus arrives |
| Action: walk[B 12] | Observation: Error: no result, because the room has no space in its code |
| Action: walk[B12] | Observation: 7, the minutes on foot |
| Action: add[09:35 7] | Observation: 09:42, then the final answer and Actions: 5 |
The cells students fill in are left blank in this preview.
An observation steers the next thought
Look at the third action. The tool found no room called B 12, and the code wrote an error as the observation. The next thought used it and tried B12.
That is the point of ReAct. Each result goes back to the model before it acts again, so a mistake can be fixed. The loop also stops after six actions, so a stuck model cannot run for ever.
Check
Have a go
Check
3 questionsA common mistake
Warning
Many people think the model runs the tool itself. It only writes the Action line. Your code runs the tool and writes the Observation, so an Observation line written by the model is a guess and must be ignored.
Ask a real model for the next line
The next Run sends the same question to the lab's model once and asks for one line. Your code then checks that line like any other. Is it a thought, a valid action or something else?
Results vary. A model may answer with a valid action, a thought or a whole paragraph. With no model it prints a Recorded sample line and checks a saved reply.
Write the one live call, part 1
docker exec -w /home/node/project agent sh -c "printf '%s\n' 'const base = process.env.AI_URL || \"http://ai:4000\";' 'const PROMPT = \"You answer with the ReAct pattern. Tools: timetable[route] gives the departure and minutes of a bus, walk[room] gives the minutes from the bus stop, add[HH:MM minutes] adds minutes to a time. Question: I take bus route 7 to a 09:30 lecture in room B12. Am I on time? Reply with one line only: your next Thought or Action.\";' 'const RECORDED = \"Action: \" + \"timetable\" + \"[7]\";' 'const TOOLS = [\"timetable\",\"walk\",\"add\"];' 'async function main() {' ' let line = RECORDED;' ' try {' ' const res = await fetch(base + \"/v1/chat/completions\", {' ' method: \"POST\",' ' headers: { \"content-type\": \"application/json\", authorization: \"Bearer lab\" },' ' body: JSON.stringify({ model: \"lab\", messages: [{ role: \"user\", content: PROMPT }], max_tokens: 60 }),' ' signal: AbortSignal.timeout(30000),' ' });' > ask1.js"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the one live call, part 2
docker exec -w /home/node/project agent sh -c "printf '%s\n' ' if (res.ok === false) throw new Error(\"status \" + res.status);' ' const data = await res.json();' ' line = data.choices[0].message.content.trim().split(String.fromCharCode(10))[0];' ' } catch (error) {' ' console.log(\"Recorded sample: no model answered\" + \" (\" + error.message + \")\");' ' }' ' console.log(\"Model\" + \": \" + line);' ' let verdict = \"not a ReAct line\";' ' if (line.startsWith(\"Thought:\")) verdict = \"a thought, no action yet\";' ' if (line.startsWith(\"Action: \")) {' ' const name = line.slice(8, line.indexOf(\"[\"));' ' verdict = TOOLS.includes(name) ? \"a valid action\" : \"an action with an unknown tool\";' ' }' ' console.log(\"Verdict\" + \": \" + verdict);' '}' 'main();' >> ask1.js"Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Ask the model for one line
docker exec -w /home/node/project agent node ask1.jsShown here, not run. Press Start lab to type it into your own lab’s terminal.
ReAct and tool calling today
Most model services now offer tool calling, where a tool request comes back as structured data rather than a line of text. The loop is the same: think, act, observe, repeat.
Reading a ReAct trace is still a useful skill. Many agents print one, and it shows where a run went wrong.
Match each line to its kind
Have a go
Loading…
Your answers are marked here and are not kept. An account keeps your marks.
Assignment: run a ReAct trace
Run a recorded ReAct trace yourself.
parse_line(line) returns a dictionary. A line starting Thought: gives {"kind": "thought", "text": ...} and one starting Final Answer: gives {"kind": "final", "text": ...}, the text after the colon trimmed. A line starting Action: with a tool name, then the input in square brackets at the end, gives {"kind": "action", "tool": ..., "arg": ...}. Anything else, an Observation line included, gives {"kind": "other", "text": line}.
run_steps(lines, tools, limit) goes through the lines. tools maps a tool name to a dictionary of inputs and results. For each action add an observation: the result, "Error: no tool <name>" or "Error: no result". Return {"observations": [...], "answer": ..., "stopped": ...}: stopped is "final" at a final answer, "limit" once there are limit observations, and "end" when the lines run out. The answer is "" unless stopped is final.
def parse_line(line):
return None
def run_steps(lines, tools, limit):
return None
Make a free account to save your work and track your progress.
Exit quiz
Have a go