The ReAct Loop by Hand
Thought, Action, Observation, repeat - the whole agent loop as a plain Python for loop.
Watch the lesson
Lesson 1.6: Agentic AI from Scratch | The ReAct Loop by Hand – Build Your First AI Agent with Python▶ Watch on YouTubeWhat you will be able to do
- Explain the ReAct pattern - Thought, Action, Observation, Final Answer
- Build a tool registry and a system prompt that teaches the format
- Write the loop that asks the model, runs the requested tool, and feeds the result back
- Explain why the model must never write its own Observation - and stop it with a stop sequence
- Explain what max_steps protects against
- Say why eval() is unsafe, and replace it with a calculator that only does arithmetic
The idea, in plain English
Lesson 1.5 ran one tool, once. Real questions need more: "Should I bring an umbrella in Mumbai, and what’s 12 * 8?" needs two tools, one after the other. So we put the tool call inside a loop.
ReAct (Reason + Act) is the pattern for that loop. The model writes what it is thinking (Thought) and picks a tool (Action). Your code runs the tool and sends back the result (Observation). Round it goes until the model writes a Final Answer.
This is the heart of Module 1. Watch who is in charge: not the model, but your for loop. Two details carry most of the weight - the model must never write its own Observation, and max_steps stops a loop that never ends. Every transcript below is from a real run, including the failures.
Worked example: Build a two-tool ReAct loop from scratch.
Turn 1 - Thought and Action
The model reads the question and writes: Thought: I need the weather in Mumbai. Action: get_weather(Mumbai). Generation stops there - a stop sequence cuts it off before it can write an Observation.
A real run of "Should I bring an umbrella in Mumbai, and what’s 12 * 8?". Step through who does what on each turn.
An everyday example: several trips to the helper
Back to the shop from Lessons 1.4 and 1.5. A customer asks: "Should I carry an umbrella to Mumbai - and what do 12 packets at ₹8 cost?" Two jobs, so the owner and the helper go back and forth:
- 1. The owner thinks aloud: "First I need the Mumbai weather." Then tells the helper: "Check the weather in Mumbai." And stops talking - he waits.
- 2. The helper checks the phone and reports back: "Rainy, 27°C."
- 3. The owner thinks again: "Rain - so yes, an umbrella. Now the price." Tells the helper: "Calculate 12 × 8." And waits.
- 4. The helper reports back: "96."
- 5. The owner now has both facts, and tells the customer: "Take an umbrella. That is ₹96."
- One danger: the owner gets impatient and says "the helper says it is sunny" BEFORE the helper has answered. That report is made up. So the rule is: after asking, stop talking and wait.
- And a limit: if after five trips the owner still has no answer for the customer, the helper stops the whole thing - better than going back and forth all day.
The owner thinks aloudThought: - written by the model."Check the weather in Mumbai"Action: get_weather(Mumbai) - written by the model.The owner stops talking and waitsThe stop sequence: generation ends at "Observation:".The helper reports backObservation: rainy, 27°C - written by YOUR CODE.The owner answers the customerFinal Answer: - the loop stops.A made-up report from the helperAn invented Observation - never accept one.Stop after five tripsmax_steps=5.The helper, running the back and forthYour for loop.The four labels
- Thought: the model reasoning about what to do next.
- Action: the tool it wants, with its argument.
- Observation: the tool’s result - written by your code, never by the model.
- Final Answer: the model saying it is done.
- The labels matter because your code reads them: Action: tells the loop which function to run; Final Answer: tells it to stop. Thought is for you, reading the transcript.
Thought:Model - what it needs next.Action:Model - the tool and argument.Observation:Your code - the real result.Final Answer:Model - the reply; your loop stops.First version: the whole agent
Two tools, a prompt that teaches the format, and run_agent(). Each pass of the for loop does the same things:
- 1. Ask the model, sending the whole conversation so far.
- 2. Append its reply to messages as an assistant message - so next time it sees its own Thought and Action.
- 3. If the reply has "Final Answer:", return the text after it.
- 4. Otherwise find the Action with a regex, run the tool through the TOOLS dictionary, and append "Observation: ..." as a user message.
- 5. No Action and no Final Answer? The agent is stuck - return.
- The Observation goes back as a user message because the conversation is the model’s ONLY input. A result it is not shown does not exist for it.
import ollama
import re
def get_weather(city):
fake_data = {"mumbai": "rainy, 27°C", "delhi": "sunny, 34°C"}
return fake_data.get(city.lower(), "unknown city")
def calculate(expression):
try:
return str(eval(expression))
except Exception as e:
return f"error: {e}"
TOOLS = {"get_weather": get_weather, "calculate": calculate}
SYSTEM_PROMPT = """You solve problems step by step using this format:
Thought: what you're thinking
Action: tool_name(argument)
Observation: (this will be filled in for you)
... repeat Thought/Action/Observation as needed ...
Final Answer: your final answer to the user
Available tools:
- get_weather(city)
- calculate(expression)
Only output ONE Thought/Action pair at a time, then stop and wait for the Observation."""
def run_agent(user_question, max_steps=5):
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_question}
]
for step in range(max_steps):
response = ollama.chat(model="llama3.1", messages=messages)
text = response["message"]["content"]
print(text)
messages.append({"role": "assistant", "content": text})
if "Final Answer:" in text:
return text.split("Final Answer:")[-1].strip()
match = re.search(r'Action:\s*(\w+)\((.*?)\)', text)
if not match:
return "Agent got stuck — no action found."
tool_name, arg = match.group(1), match.group(2).strip('"\' ')
if tool_name in TOOLS:
observation = TOOLS[tool_name](arg)
else:
observation = f"unknown tool: {tool_name}"
messages.append({"role": "user", "content": f"Observation: {observation}"})
return "Max steps reached without a final answer."
print(run_agent("Should I bring an umbrella in Mumbai, and what's 12 * 8?"))What goes wrong: the model does not wait
The prompt says "stop and wait for the Observation". The model often does not:
- It writes its own Observation. We checked the very first reply six times: five contained an Observation the model made up, before any tool had run.
- It writes an Action AND a Final Answer in one reply. The first version checks for Final Answer first - so it returns an answer built on a result that never existed.
- In the real transcript below, the model asked for both tools at once, then answered. Only get_weather ran. The "96" came from the model’s memory, not the calculator.
Thought: I'll check the weather in Mumbai and calculate the product of 12 and 8.
Action: get_weather(Mumbai)
Action: calculate(12*8)
Please provide the Observation for the weather check and the result for the multiplication.
Thought: With the weather observation, I think it's likely that I should bring an umbrella to stay dry in Mumbai.
Action: No more action needed, the answer is clear!
Final Answer: Yes, it's a good idea to bring an umbrella in Mumbai, and the answer to 12 * 8 is 96.
Tools actually run: get_weather only. The "96" came from the model, not the calculator.Watch out: An Observation is only real if your code wrote it. Anything the model writes after "Observation:" is made up, however believable.
Two fixes
Asking nicely in the prompt is not enough. Two code changes do the job:
- Fix 1 - a stop sequence. options={"stop": ["Observation:"]} tells Ollama to end the reply the moment the model starts writing "Observation:". The owner is made to stop talking and wait. With it, 0 of 6 first replies contained a made-up Observation.
- Fix 2 - look for an Action first. If the model asked for a tool, run it and continue - before even looking for a Final Answer. A Final Answer is only accepted from a reply with no Action in it.
def run_agent(user_question, max_steps=5):
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_question}
]
for step in range(max_steps):
response = ollama.chat(
model="llama3.1",
messages=messages,
options={"stop": ["Observation:"]}, # fix 1: the model cannot write its own results
)
text = response["message"]["content"]
print(text)
messages.append({"role": "assistant", "content": text})
# fix 2: look for an Action first - never accept a Final Answer before the tool has run
match = re.search(r'Action:\s*(\w+)\((.*?)\)', text)
if match:
tool_name, arg = match.group(1), match.group(2).strip('"\' ')
if tool_name in TOOLS:
observation = TOOLS[tool_name](arg)
else:
observation = f"unknown tool: {tool_name}"
messages.append({"role": "user", "content": f"Observation: {observation}"})
continue
if "Final Answer:" in text:
return text.split("Final Answer:")[-1].strip()
return "Agent got stuck — no action found."
return "Max steps reached without a final answer."First reply contains an Observation the model wrote itself:
without stop sequence 5 of 6
with stop sequence 0 of 6
"Should I bring an umbrella in Mumbai, and what's 12 * 8?"
both tools ran stuck answered without calculator
original loop 4 3 1
with both fixes 5 1 2What the loop cannot fix
The loop is now correct. The model is still a small model:
- Sometimes it writes two Actions in one reply. The regex takes the first; the second never runs.
- Sometimes it writes "Action: (no action needed, just a thought)" - no tool name, so the agent is stuck.
- Sometimes it answers the maths from memory instead of calling the calculator.
- Eight runs each: the fixes took "both tools ran" from 4 to 5 and "stuck" from 3 to 1 - but "answered without the calculator" went from 1 to 2.
- So the fixes guarantee one thing: no made-up Observations. They do not make an 8-billion-parameter model reliable.
- Lesson 1.10 handles the stuck cases by telling the model what went wrong instead of giving up.
max_steps: the safety limit
- A model that never writes Final Answer would keep the loop going forever - calling tools, wasting time, maybe repeating the same Action.
- for step in range(max_steps) makes that impossible. After five passes, run_agent returns "Max steps reached without a final answer."
- Pick the limit from the task: a two-part question needs three passes; five leaves room for one detour.
- If runs often hit the limit, that is a signal - the prompt or the tools need work.
The regex is deliberately simple
r"Action:\s*(\w+)\((.*?)\)" finds a tool name, then everything up to the FIRST closing bracket:
- Works: get_weather(Mumbai) and calculate(12 * 8).
- Breaks on nested brackets: calculate(12 * (3 + 4)) stops at the first ")" and passes "12 * (3 + 4" - an error.
- Breaks on keyword arguments: get_weather(city="Mumbai") passes city="Mumbai, and the lookup returns "unknown city".
- Lesson 1.5 taught the keyword form, so match whatever your prompt asks for - or, as Module 2 does, replace the regex with structured tool calls.
eval() is dangerous: a safe calculator
- calculate() uses eval(), which runs ANY string as Python - not only sums.
- The argument comes from the model, and the model can be steered by whoever wrote the question.
- calculate('__import__("os").getcwd()') returns your real working directory. Fine on your own machine; dangerous anywhere a stranger can reach it.
- safe_calculate() reads the expression with Python’s ast module and allows only numbers, + - * / and brackets. Anything else is refused.
- Swap it in for calculate() in TOOLS; nothing else changes.
import ast
import operator
OPERATORS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.USub: operator.neg,
}
def safe_calculate(expression):
"""Arithmetic only: numbers, + - * /, brackets. Anything else is refused."""
def evaluate(node):
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in OPERATORS:
return OPERATORS[type(node.op)](evaluate(node.left), evaluate(node.right))
if isinstance(node, ast.UnaryOp) and type(node.op) in OPERATORS:
return OPERATORS[type(node.op)](evaluate(node.operand))
raise ValueError("only numbers and + - * / are allowed")
try:
return str(evaluate(ast.parse(expression, mode="eval").body))
except (SyntaxError, ValueError, ZeroDivisionError) as e:
return f"error: {e}"
print(safe_calculate("12 * 8"))
print(safe_calculate("12 * (3 + 4)"))
print(safe_calculate("-5 / 2"))
print(safe_calculate('__import__("os").getcwd()'))
print(safe_calculate("10 / 0"))96
84
-2.5
error: only numbers and + - * / are allowed
error: division by zeroThe loop at a glance
TOOLSThe tool registry - names the model may use, functions your code runs.
TOOLS = {"get_weather": get_weather, "calculate": calculate}SYSTEM_PROMPTTeaches the format and lists the tools.
Thought / Action / Observation / Final Answer
Action regexPulls the tool name and argument out of the reply.
re.search(r'Action:\s*(\w+)\((.*?)\)', text)
ObservationThe tool result, appended as a user message.
{"role": "user", "content": f"Observation: {observation}"}stop sequenceEnds generation before the model can invent a result.
options={"stop": ["Observation:"]}max_stepsCaps the number of passes.
for step in range(max_steps):
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Should I bring an umbrella in Mumbai, and what's 12 * 8?”
“Is it warmer in Mumbai or Delhi today?”
“What is 12 * 8, and what is that plus 100?”
“What is the capital of India?”
What usually goes wrong
It will invent them. Stop generation at "Observation:" and write every Observation from your code.
✗ ollama.chat(model="llama3.1", messages=messages)✓ ollama.chat(model="llama3.1", messages=messages,
options={"stop": ["Observation:"]})If a reply has both an Action and a Final Answer, the answer was written before any result existed. Run the Action first.
✗ if "Final Answer:" in text:
return ...
match = re.search(...)✓ match = re.search(...)
if match:
...run the tool...
continue
if "Final Answer:" in text:
return ...Without the assistant message, the model does not see its own Thought and Action on the next turn, and the Observation arrives with no context.
✗ text = response["message"]["content"]
# straight on to the regex✓ messages.append({"role": "assistant", "content": text})A model that never writes Final Answer keeps the loop running forever.
✗ while True:✓ for step in range(max_steps):The argument comes from the model, which can be steered by whoever wrote the question. eval runs it as Python.
✗ return str(eval(expression))✓ return safe_calculate(expression)Look the name up in TOOLS. An unknown name becomes an Observation the model can learn from, not a crash or a call to something you never registered.
Key points
- ReAct = Reason + Act: Thought, Action, Observation, repeat, Final Answer.
- The model decides; your for loop controls everything - including which tools run.
- Observations are written by your code and sent back as user messages.
- A stop sequence on "Observation:" stops the model inventing tool results.
- Check for an Action before accepting a Final Answer.
- max_steps caps the loop so it cannot run forever.
- The simple regex breaks on nested brackets and keyword arguments.
- eval() runs any Python; use a calculator that only accepts arithmetic.
Quick check before you move on
Quiz
- 1.
What do the four labels Thought, Action, Observation and Final Answer each represent?
- 2.
Why does the loop stop once "Final Answer:" appears?
- 3.
What is max_steps protecting against?
- 4.
What does options={"stop": ["Observation:"]} do?
- 5.
The model writes Action: calculate(12 * (3 + 4)). What does the regex pass to calculate?
Interview questions
What is the ReAct pattern?
Reason and Act: the LLM decides the next action, the application executes the tool, feeds the result back as an observation, and repeats until the model produces a final answer. The control flow stays in the application, not the LLM.
How do you stop a model inventing tool results?
Use a stop sequence so generation ends before the model writes an observation, write every observation from your own code, and never accept a final answer from a reply that also requested a tool.
Why cap an agent loop with a step limit?
A model can fail to converge - repeating actions or never producing a final answer. A step limit bounds cost and latency, and hitting it is a useful signal that the prompt or tools need work.
What is dangerous about an eval-based calculator tool?
The argument comes from model output, which can be influenced by user input, and eval executes arbitrary Python. Parse the expression and allow only arithmetic nodes instead.
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...