Lesson 2 of 5 · Planning
Reasoning Before Acting
How AI agents reason before acting: chain-of-thought, the ReAct loop, reasoning models, and checking assumptions with read-only tools before risky actions.
- 6 min read
- Advanced
- Reviewed
- Explain chain-of-thought reasoning and why it helps
- Run a ReAct loop of thought, action and observation
- Relate ReAct to native tool calling and reasoning models
- Check assumptions with read-only tools before an irreversible action
- Know why written reasoning is not proof that an answer is right
Think, then act
Ask a person a tricky question and they'll often work through it out loud. Language models benefit from the same thing: writing out intermediate steps before the final answer makes multi-step problems more likely to come out right.
For agents, reasoning has a second job. Before each action the agent should be able to say what it knows, what it still needs and why this action gets it. After each result, it should say what the result means for the plan.
The ReAct loop
Here's a complete ReAct loop. The model is scripted so it runs the same way every time, but the loop around it (parse the action, run the tool, append the observation, cap the steps) is the real thing:
import re
# ---- Tools the agent can use (read-only lookups in a small fake database) ----
ORDERS = {"1042": {"customer_city": "Porto", "item": "desk lamp"}}
NEAREST = {"Porto": ["Porto North", "Lisbon East"]} # warehouses, nearest first
STOCK = {("Porto North", "desk lamp"): 0, ("Lisbon East", "desk lamp"): 14}
TOOLS = {
"get_order": lambda arg: ORDERS.get(arg, "no such order"),
"warehouses": lambda arg: NEAREST.get(arg, []),
"check_stock": lambda arg: STOCK.get(tuple(x.strip() for x in arg.split(",")), 0),
}
# ---- A scripted stand-in for the model: it writes a Thought, then an Action ----
SCRIPT = [
"Thought: I need the customer's city and the item first.\nAction: get_order[1042]",
"Thought: The customer is in Porto. Which warehouses are nearest?\nAction: warehouses[Porto]",
"Thought: Check the nearest one, Porto North, for the lamp.\nAction: check_stock[Porto North, desk lamp]",
"Thought: Porto North has none. Try the next nearest, Lisbon East.\nAction: check_stock[Lisbon East, desk lamp]",
"Thought: Lisbon East has 14. I can answer.\nFinal Answer: Ship order 1042 from Lisbon East (Porto North is out of stock).",
]
def model(transcript, step):
return SCRIPT[step] # a real agent sends the transcript to an LLM here
# ---- The ReAct loop: Thought -> Action -> Observation, repeated ----
transcript = "Question: Which warehouse should ship order 1042?\n"
for step in range(8): # always cap the number of steps
reply = model(transcript, step)
transcript += reply + "\n"
if "Final Answer:" in reply:
break
match = re.search(r"Action: (\w+)\[(.*)\]", reply)
if not match or match.group(1) not in TOOLS:
transcript += "Observation: invalid action, use one of " + ", ".join(TOOLS) + "\n"
continue
tool, arg = match.groups()
transcript += f"Observation: {TOOLS[tool](arg)}\n"
print(transcript)Read the trace from top to bottom. Each Thought explains the next action, each Observation is real tool output, and the fourth thought changes course because Porto North has no stock. That adaptation is what reasoning between actions buys you.
Notice the safety details in the loop: the step limit, and the “invalid action” observation. A bad reply from the model becomes feedback rather than a crash, so the model gets a chance to correct itself.
ReAct with today's APIs
The original ReAct paper parsed text like Action: check_stock[...]. Modern model APIs do the parsing for you with native tool calling: the model returns a structured tool call, and any text it writes before the call plays the role of the thought (see the Tool Calling course). The loop is the same: call the model, run the tools it asks for, add the results, repeat.
Many models can also reason internally before they reply. These reasoning models (sometimes called thinking models) work through the problem first and then answer, and some APIs let you set how much reasoning to allow. They are especially useful for planning and for decisions with several conditions, at the cost of extra tokens and waiting time.
Look before you leap
The most valuable reasoning happens before actions you can't undo. The agent lists the assumptions its action depends on, then checks each one with read-only tools:
# Look before you leap: check every assumption with read-only tools before an action you can't undo.
PAYMENTS = {"A-881": {"paid": 120.0, "refunded": 120.0, "status": "cancelled"}}
def check_refund(order_id, amount):
p = PAYMENTS.get(order_id)
checks = {
"order exists": p is not None,
"amount <= amount paid": p is not None and amount <= p["paid"],
"not already refunded": p is not None and p["refunded"] == 0,
}
for name, ok in checks.items():
print(f" {'OK ' if ok else 'FAIL'} {name}")
return all(checks.values())
print("Plan: refund 120.00 for order A-881")
if check_refund("A-881", 120.0):
print("Refund sent.")
else:
print("Stopped before acting: an assumption was wrong. Tell the user what was found.")The plan to refund looked reasonable, but one check failed: the order was already refunded. Refunding again would have paid out 120 euros twice. Checks like these are cheap lookups, and they turn a costly mistake into a clear message to the user.
Common mistakes
Parse a ReAct-style model reply into the tool to call and its argument, the step the agent loop does on every turn.
import re reply = "Thought: I should look up the order.\nAction: get_order[A-881]" # Use re.search to find the tool name and the argument in the Action line, # then print them in the form tool=<name> arg=<argument>
In a ReAct loop, what is an observation?
Summary
- Chain-of-thought reasoning makes multi-step problems more likely to come out right.
- ReAct interleaves thought, action and observation, so the agent can change course when results surprise it.
- Today's APIs use native tool calls and reasoning models for the same loop.
- Before irreversible actions, check every assumption with read-only tools.
- Written reasoning isn't proof: verify what matters.
Next: self-correction, catching and fixing mistakes.
Finished reading? Tick it off to track your progress.