Build a ReAct Agent from Scratch
Generative & Agentic AI · Agentic AI · Intermediate · 22 min
Write a working ReAct agent in plain Python: a prompt that teaches Thought / Action / Observation, a tool registry, a parser for the model's reply, a loop with stop conditions, and error handling that lets the model recover.
A detective's notebook. On each line the detective writes a thought, then an instruction for an assistant ("check the train timetable"). The assistant writes the result underneath. The detective reads it, writes the next thought, and closes the notebook only when the case is solved or the page runs out.
The idea in everyday words
Think of a student doing homework with a calculator and an encyclopedia nearby. They think ("I need the number of legs on a spider"), act (open the encyclopedia), observe ("8"), and repeat until they can write the final answer. The student is the LLM; you are the one who actually hands over the encyclopedia and the calculator.
The ReAct loop, precisely
ReAct = Reason + Act. The model alternates between writing a Thought (reasoning in words) and an Action (a tool call). Your code runs the tool and appends an Observation. Repeat until the model writes a Final Answer.
The prompt teaches the format:
Answer the question. You can use these tools:
- lookup: look up a simple fact, e.g. lookup[cat legs]
- calculator: evaluate arithmetic, e.g. calculator[2*(3+4)]
Use this format:
Thought: what you are thinking
Action: tool_name[input]
Observation: (written by the system, never by you)
... repeat ...
Final Answer: the answer
Question: How many legs do 3 spiders and 2 cats have?
Each turn the model writes one Thought and one Action, then stops. A stop sequence (for example "Observation:") cuts generation there, so the model cannot invent its own observation. Your code runs the tool and appends Observation: 8 to the prompt. The whole growing text is called the scratchpad.
The key idea: the model never runs anything. It only writes text that asks for a tool. Your code decides whether and how to run it.
The five parts you build
| Part | Job | In our code |
|---|---|---|
| Prompt template | explains the tools and the format | the text above |
| Tool registry | maps a tool name to a function and a description | TOOLS = {"lookup": (lookup, "..."), ...} |
| Parser | turns the model's text into a decision: action, final answer, or error | parse(reply) |
| Executor | runs the tool safely and returns an observation string | try / except around the call |
| Controller (the loop) | calls the model, parses, executes, appends, checks stop conditions | run_agent(question, max_steps) |
Why a registry? It is your allow-list. The model can only reach functions you put in it, and the descriptions are what the model reads to choose a tool, so write them like documentation: what it does, what input it wants, an example.
The key idea: keep each part small and testable on its own. You can unit-test the parser and every tool without calling a model at all, which is exactly what this lesson's challenge does.
Parsing the model's output safely
Models do not always follow the format. Your parser must expect:
- extra spaces:
Action: lookup[ cat legs ] - a missing bracket:
Action: calculator - no action at all: "I think the answer is 5"
- brackets inside the input:
Action: search[a[b]](take the text between the FIRST "[" and the LAST "]")
Rule of thumb: scan lines in order, the first decisive line wins (a Final Answer or an Action), and anything else becomes an error observation sent back to the model, such as Observation: Error: bad action format. Use: Action: tool[input]. The model usually fixes itself on the next turn.
Native tool calling is the modern alternative. With the Amazon Bedrock Converse API you pass a toolConfig with a JSON schema for each tool. The model replies with a structured toolUse block (tool name and JSON input) and stopReason "tool_use", and you send back a toolResult block. No text parsing, and inputs are checked against your schema:
# boto3 sketch (runs in your AWS account, not in the browser)
resp = bedrock.converse(modelId=MODEL_ID, messages=messages, toolConfig={"tools": [
{"toolSpec": {"name": "lookup", "description": "Look up a simple fact",
"inputSchema": {"json": {"type": "object",
"properties": {"q": {"type": "string"}}, "required": ["q"]}}}}]})
if resp["stopReason"] == "tool_use":
for block in resp["output"]["message"]["content"]:
if "toolUse" in block:
name, args, tid = block["toolUse"]["name"], block["toolUse"]["input"], block["toolUse"]["toolUseId"]
# run the tool, then append {"toolResult": {"toolUseId": tid, "content": [{"text": result}]}}
The loop is identical; only the parsing step changes. Learning the text version first shows you what native tool calling does for you.
Stop conditions and failure modes
An agent loop must always end. Put these in the controller, not in the prompt:
| Condition | What happens |
|---|---|
| Final Answer parsed | return it (the happy path) |
| max_steps reached | stop and return a clear "could not finish" message |
| same action with the same input repeated (for example 3 times) | stop: the agent is stuck in a loop |
| token, time or cost budget used up | stop and report |
| risky action (send email, pay) | pause and ask a human to approve |
Errors are observations, not crashes. If a tool raises an exception or the model names an unknown tool, catch it and feed Observation: Error: ... back. The model can then retry with a different input. Only stop the run for errors the model cannot fix (for example the tool's service is down) or when the step limit is hit.
Also validate tool inputs before running them, and never pass model text to eval (or JavaScript's Function). A character filter is not enough: 9**9**9**9 contains only digits and *, yet eval would freeze the process computing a gigantic power. Our calculator therefore parses the expression itself (Python's ast module, or a 30-line parser in JavaScript) and evaluates only numbers, + - * / and brackets, with a length limit. Anything else becomes an error observation.
The key idea: the model proposes, the controller disposes. Every safety rule lives in code you control.
From scratch to production on AWS
You rarely ship the hand-written loop, but you will debug every framework better for having written it.
- Amazon Bedrock Converse API: native tool use with any supported model. Your own loop in Lambda or a container.
- Amazon Bedrock Agents: a managed ReAct-style loop. You define action groups (Lambda functions or OpenAPI schemas) and knowledge bases; Bedrock handles prompting, parsing, the loop and traces.
- Amazon Bedrock AgentCore Runtime: host your own agent code (Strands Agents, LangGraph, CrewAI or your own loop) with session isolation, plus AgentCore Gateway for tools, Memory and Observability.
- Strands Agents (open source, from AWS): define tools as Python functions with a decorator, and the SDK runs the model-driven loop for you.
Open source: LangGraph, LlamaIndex agents, smolagents. The ReAct idea comes from the 2022 paper by Yao et al.
Step by step
- Question:
"How many legs do 3 spiders and 2 cats have?" The prompt lists two tools: lookup and calculator.
- Step 1:
LLM: "Thought: I need spider legs. Action: lookup[spiders legs]". The parser returns tool = lookup, input = "spiders legs". The tool raises "no fact for 'spiders legs'".
- Recover:
The error is NOT a crash. It is appended as "Observation: Error: no fact for 'spiders legs'". Next turn the model retries with lookup[spider legs] and observes 8.
- More tools:
lookup[cat legs] gives 4. Then calculator[38 + 24] gives 32. Each observation is appended to the scratchpad so the model can see all earlier results.
- Finish:
LLM: "Final Answer: 32 legs". The parser sees Final Answer, and the loop returns it after 5 steps.
- Stop condition:
Run the same agent with max_steps = 2: it never reaches the final answer, so the controller stops and returns "Stopped: hit max_steps" instead of looping forever.
Code example
import ast
import operator
# ---------- tools: the allow-list the model can use ----------
# A safe calculator: parse the text into a syntax tree and evaluate ONLY
# numbers, + - * / and brackets. No eval(), so no names, calls or **.
OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv}
def calculator(expr):
if len(expr) > 100:
raise ValueError("expression too long")
def ev(node):
if isinstance(node, ast.Constant) and type(node.value) in (int, float):
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in OPS:
return OPS[type(node.op)](ev(node.left), ev(node.right))
if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.USub, ast.UAdd)):
return -ev(node.operand) if isinstance(node.op, ast.USub) else ev(node.operand)
raise ValueError("only numbers and + - * / ( ) are allowed")
try:
tree = ast.parse(expr, mode="eval")
except SyntaxError:
raise ValueError("not a valid arithmetic expression")
return str(ev(tree.body))
FACTS = {"spider legs": "8", "cat legs": "4"}
def lookup(q):
if q.lower() not in FACTS:
raise ValueError("no fact for '" + q + "'")
return FACTS[q.lower()]
TOOLS = {
"calculator": (calculator, "evaluate arithmetic, e.g. calculator[2*(3+4)]"),
"lookup": (lookup, "look up a simple fact, e.g. lookup[cat legs]"),
}
# ---------- a scripted fake LLM (in production: Bedrock Converse) ----------
SCRIPT = [
"Thought: I need to know how many legs a spider has.\nAction: lookup[spiders legs]",
"Thought: That failed, maybe singular works.\nAction: lookup[spider legs]",
"Thought: Now cats.\nAction: lookup[cat legs]",
"Thought: 3 spiders and 2 cats.\nAction: calculator[3*8 + 2*4]",
"Thought: I have everything I need.\nFinal Answer: 32 legs",
]
def fake_llm(prompt, step):
return SCRIPT[step]
def parse(text):
for line in text.split("\n"):
line = line.strip()
if line.startswith("Final Answer:"):
return ("final", line[len("Final Answer:"):].strip(), None)
if line.startswith("Action:"):
rest = line[len("Action:"):].strip()
i = rest.find("[")
if i <= 0 or not rest.endswith("]"):
return ("error", "bad action format", None)
return ("action", rest[:i].strip(), rest[i + 1:-1].strip())
return ("error", "no action found", None)
def run_agent(question, max_steps=8):
tools = "\n".join("- " + name + ": " + desc for name, (_, desc) in TOOLS.items())
prompt = "Answer the question. Tools:\n" + tools + "\nQuestion: " + question + "\n"
for step in range(max_steps):
reply = fake_llm(prompt, step)
prompt += reply + "\n"
kind, a, b = parse(reply)
print(f"[step {step + 1}] {reply.splitlines()[-1]}")
if kind == "final":
return a
if kind == "error":
obs = "Error: " + a + ". Use the format Action: tool[input]"
elif a not in TOOLS:
obs = "Error: unknown tool '" + a + "'"
else:
try:
obs = TOOLS[a][0](b)
except Exception as e: # tool errors become observations
obs = "Error: " + str(e)
print(" Observation:", obs)
prompt += "Observation: " + obs + "\n"
return "Stopped: hit max_steps without a final answer"
print("ANSWER:", run_agent("How many legs do 3 spiders and 2 cats have?"))
print()
print("ANSWER:", run_agent("Same question with a tiny budget", max_steps=2))
print()
for bad in ["9**9**9**9", "__import__('os').getcwd()"]:
try:
calculator(bad)
except ValueError as e:
print("calculator rejected", repr(bad), "->", e)Complexity
- Time: Parsing: O(length of the reply). The loop: at most max_steps model calls; the prompt grows every step, so total tokens grow roughly quadratically with the number of steps unless you trim the scratchpad.
- Space: O(total scratchpad length), which is why long runs need context management (see Agent Memory).
Interview tips
Describe the ReAct loop and who does what: the model writes Thought and Action; your code parses, runs the tool and appends the Observation.
Explain why a stop sequence on "Observation:" matters (the model must not invent tool results).
List stop conditions: final answer, max steps, repeated identical actions, budget, and human approval for risky actions.
Compare text-format ReAct with native tool calling (Bedrock Converse toolUse / toolResult blocks, schema-checked inputs).
Talk about safety: tool allow-lists, input validation (never eval raw model text), least-privilege credentials for tools.
Challenge: Parse a ReAct Reply
Write parse_action(text) that turns a model reply into a decision. Scan the lines in order, ignoring leading/trailing spaces on each line. The first line that starts with Final Answer: or Action: decides:
Final Answer: X→{"type": "final", "answer": "X"}(stripped)Action: tool[input]→{"type": "action", "tool": "tool", "input": "input"}(both stripped). The input is everything between the first[and the final].- An Action line with no
[, an empty tool name, or not ending in]→{"type": "error", "message": "bad action format"} - No decisive line at all →
{"type": "error", "message": "no action found"}
Example: parse_action("Thought: I need math\nAction: calculator[2+3]") → {"type": "action", "tool": "calculator", "input": "2+3"}
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- ReAct paper (Yao et al., 2022)
- Amazon Bedrock: tool use with the Converse API
- Basic Calculator II (build the calculator tool) (Medium)
- Evaluate Reverse Polish Notation (Medium)
More in Agentic AI
- What Is Agentic AI?
- AI Agents & Tool Calling
- Agent Memory, Planning & Reflection
- Model Context Protocol (MCP)
- Amazon Bedrock Agents
- Amazon Bedrock AgentCore: Running Agents in Production
- Multi-Agent Systems
Previous: AI Agents & Tool Calling · Next: Agent Memory, Planning & Reflection