Module 05 · Lesson 5.1
ReAct-Style Reasoning and Acting Patterns
On this page
- What you will learn
- What is the ReAct pattern for AI agents?
- Your ask_agent loop is already a reason-and-act loop
- When the reason-and-act pattern works well
- The risks of the loop and the guardrails that contain them
- See the loop run: a trace in Python
- Conclusion and your next step
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Imagine you lost your house keys. You do not make a perfect plan first. You check the coat pocket. Nothing. You remember wearing the blue jacket yesterday, so you check that. Found them. Each result told you where to look next.
Many AI agents work this way when a job cannot be planned in advance. This lesson explains that pattern in plain words, shows that the agent you already built uses it, and teaches the code guardrails that stop it from wandering, looping or costing too much. Most of the lesson needs no coding. One short Python example prints a step-by-step trace.
What you will learn
- Explain the think, act, observe loop and where it comes from.
- Recognise that your
ask_agentloop already follows this pattern. - Decide when this pattern fits a task and name its main risks.
- Add guardrails in code: a step limit, a tool allowlist, stop conditions and a written trace.
Before you start
- The previous lesson, Practical Lab: Add Retrieval to a Support Agent, and the Module 2 lesson Task Decomposition and Planning Strategies.
- No coding experience is needed for most of this lesson.
- Optional: Python 3.10 or later, if you want to run the example yourself.
What is the ReAct pattern for AI agents?
ReAct is short for "reasoning and acting". It is a way of running an agent in small laps. In each lap the model decides what to do next, a tool does it, and the result goes back to the model so it can decide the lap after that.
The name comes from a 2022 research paper by Yao and colleagues, listed in the references below. This lesson gives you the idea in our own words and our own example. It does not copy the paper.
Compare it with finding your way in a new town without a map. You walk to the next corner, look at the street signs, then choose the next turn. You never knew the whole route at the start. You learned it step by step from what you saw.
- Think
Decide the next step
- Act
Your code runs a tool
- Observe
The result goes back to the model
- Repeat or answer
Another lap, or the final reply
The loop repeats until the model has an answer or a limit in your code stops it.
- Thought
- The model's decision about what to do next, based on everything it has seen so far.
- Action
- A request to use one tool with specific arguments, such as
read_docwithRS-04. - Observation
- What the tool returned. It is data, and it may be incomplete or wrong.
- Round
- One lap of the loop: one decision plus, if it asked for a tool, one tool call.
Your ask_agent loop is already a reason-and-act loop
You do not need to learn a new program. The ask_agent function from your first lab has the same shape. The model decides, your code acts, and the result goes back to the model. If you want to see that round trip again, read How Tool Calling Works.
| Loop part | In your `ask_agent` code | Who does it |
|---|---|---|
| Think | The model reads the question and chooses a tool or an answer | The model |
| Act | run_tool calls lookup_order or request_return | Your code |
| Observe | The result, or an error such as {"error": "..."}, is sent back | Your code |
| Stop | A final reply arrives, or MAX_ROUNDS is reached | The model or your code |
In the support agent the loop is short. One lookup, one reply. In a research job the loop may run many rounds, because each result changes what you need next.
When the reason-and-act pattern works well
Use the loop when you cannot know the steps in advance. The next step depends on what the last one found. Task lists were covered in Task Decomposition and Planning Strategies, where you met fixed plans, adaptive plans and no plan. The reason-and-act loop is the "adaptive" end of that range.
A Quillfeather research example
Quillfeather Cycles wants to know: Which battery should we stock next season, Battery Alpha or Battery Beta? The agent has a small set of documents (RS-01 to RS-06) and three tools.
| Tool | What it does | Kind |
|---|---|---|
search_docs(query) | Returns matching document IDs and titles | Read-only |
read_doc(doc_id) | Returns the text of one document, such as RS-04 | Read-only |
save_report(title) | Saves the finished report. A person must approve it first. | Write |
Which documents matter? Nobody knows until the agent looks. A search for "returns" might show a returns log. That log may point to the warranty terms. Each finding shapes the next search.
| Good fit | Poor fit |
|---|---|
| Research and exploring, where the next step depends on the last result | A fixed process with the same steps every time. Use a plain workflow. |
| Debugging a problem by trying one thing, then another | A job where the steps are known and can be written as a plan first |
| A task where one question can lead to several different paths | A job where a mistake is costly and every step needs a person's approval anyway |
The risks of the loop and the guardrails that contain them
Freedom to choose the next step is useful and risky. These are the common problems.
- Endless loops. The agent repeats the same search again and again.
- Wandering off the goal. A result looks interesting, and the agent follows it away from the question.
- Cost. Every round is another model call, and the history grows with each one.
- Acting on a wrong observation. A tool returns something out of date or mistaken, and the agent builds on it. Text inside a document can also try to give the agent orders, as the post on prompt injection explains.
Four guardrails you write in code
- A step limit.
MAX_ROUNDSends the loop after a fixed number of laps. You met this in Module 3. For a research agent you may allow more rounds than for a support agent, but never an unlimited number. - A tool allowlist. Your code runs a tool only if its name is on a short, written list. Anything else gets an error back. This keeps the agent to its job, as in Authentication, Secrets and Least-Privilege Access.
- Stop conditions. Stop when the model gives a final answer, when the limit is hit, when a tool returns the same error twice, or when the same action repeats. Hand over to a person or return a clear "could not finish" message.
- A written trace. Record each action and each observation as your code sees it. This is your evidence of what happened.
See the loop run: a trace in Python
The script below needs no AI model and no internet. A scripted stand-in plays the model's part. Its "thoughts" are fixed sentences we wrote, labelled as the stand-in's notes. The loop around it is real: it checks the allowlist, runs the tool, prints a numbered trace and stops at the step limit.
The question is: "Which battery had fewer returns for charging faults?" The script holds just two of the six documents to stay short.
DOCS = {
"RS-01": ("Battery Alpha spec sheet", "Battery Alpha: 500 Wh capacity, 2.9 kg, supplier price 420, delivery in 6 weeks."),
"RS-04": ("Returns log summary", "Last season, 6% of bikes with Battery Beta were returned for charging faults, compared with 2% for Battery Alpha."),
}
def search_docs(query):
return [{"id": i, "title": t} for i, (t, _) in DOCS.items() if query.lower() in t.lower()]
def read_doc(doc_id):
return {"id": doc_id, "text": DOCS[doc_id][1]}
TOOLS = {"search_docs": search_docs, "read_doc": read_doc} # the allowlist
SCRIPT = [ # stand-in for the model: a note, then a move
("I need return numbers, so I will search for returns.", {"tool": "search_docs", "args": {"query": "returns"}}),
("RS-04 looks right, so I will read it.", {"tool": "read_doc", "args": {"doc_id": "RS-04"}}),
("RS-04 has both numbers. I can answer.", {"answer": "Battery Alpha: 2% returned for charging faults, against 6% for Beta (RS-04)."}),
]
def run(max_rounds):
for n in range(1, max_rounds + 1):
note, move = SCRIPT[n - 1]
print(f"{n}. Thought (stand-in note): {note}")
if "answer" in move:
print(" Answer:", move["answer"])
return
name, args = move["tool"], move["args"]
print(f" Action: {name}({args})")
result = TOOLS[name](**args) if name in TOOLS else {"error": "tool not allowed"}
print(" Observation:", result)
print(f" Stopped: reached MAX_ROUNDS = {max_rounds}")
run(max_rounds=5)
print("--- again with a tight limit ---")
run(max_rounds=2)Runs offline with Python 3.10 or later. Save it and run python react_loop.py.
What each part does
DOCSis a dictionary: each document ID points to a title and a text.search_docsreturns the IDs and titles whose title contains the query. It is a read-only tool.read_docreturns the text of one document. It is also read-only.TOOLSis the allowlist: the only names the loop will run.SCRIPTstands in for the model. Each item is a note plus a move: either a tool request or a final answer.for n in range(1, max_rounds + 1)is the step limit. The loop can never run more laps thanmax_rounds.name in TOOLSis the allowlist check. A name that is not on the list gets{"error": "tool not allowed"}, and the tool never runs.- Each lap prints the Thought, the Action and the Observation. This printed trace is the record your code keeps.
- The second call uses
max_rounds=2, so the loop stops before the answer arrives.
1. Thought (stand-in note): I need return numbers, so I will search for returns.
Action: search_docs({'query': 'returns'})
Observation: [{'id': 'RS-04', 'title': 'Returns log summary'}]
2. Thought (stand-in note): RS-04 looks right, so I will read it.
Action: read_doc({'doc_id': 'RS-04'})
Observation: {'id': 'RS-04', 'text': 'Last season, 6% of bikes with Battery Beta were returned for charging faults, compared with 2% for Battery Alpha.'}
3. Thought (stand-in note): RS-04 has both numbers. I can answer.
Answer: Battery Alpha: 2% returned for charging faults, against 6% for Beta (RS-04).
--- again with a tight limit ---
1. Thought (stand-in note): I need return numbers, so I will search for returns.
Action: search_docs({'query': 'returns'})
Observation: [{'id': 'RS-04', 'title': 'Returns log summary'}]
2. Thought (stand-in note): RS-04 looks right, so I will read it.
Action: read_doc({'doc_id': 'RS-04'})
Observation: {'id': 'RS-04', 'text': 'Last season, 6% of bikes with Battery Beta were returned for charging faults, compared with 2% for Battery Alpha.'}
Stopped: reached MAX_ROUNDS = 2In the first run the stand-in searches, reads RS-04 and answers in three rounds. In the second run the limit stops the loop after two rounds, and the code reports that clearly. A real agent would then hand over to a person or return "could not finish".
Conclusion and your next step
The ReAct pattern is a loop: think, act, observe, repeat. Your ask_agent code already works this way. It fits open-ended work such as research, but it can loop, wander and cost a lot, so give it a step limit, a tool allowlist, stop conditions and a trace that your own code writes.
Your next step: run react_loop.py, then add a third tool name to the stand-in's script that is not on the allowlist, and watch the error appear in the trace. Then continue to Plan-and-Execute Workflows, where you write the steps down first and check them before anything runs.
For the first view of the loop, look at The Tool-Calling Loop: Reference Diagram, or see how the pattern fits among others in Chatbots vs. LLM Workflows vs. Tool-Using Agents.
Common errors and how to fix them
The agent repeats the same search many times.
Why it happens: Nothing stops repeated actions, and the result does not change what it decides.
Fix: Stop when the same action with the same arguments appears twice, and keep a MAX_ROUNDS limit.
The trace shows reasoning text but you cannot tell what was actually run.
Why it happens: You logged the model's visible text instead of the actions and results.
Fix: Log each action and observation from your own code. Treat the model's text as a hint only.
The agent follows an interesting result away from the question.
Why it happens: The goal is not repeated in the instructions, and nothing limits the topics.
Fix: State the question in the instructions, keep tools few, and set a low MAX_ROUNDS that you raise only when needed.
A wrong document leads to a wrong answer.
Why it happens: The agent trusted one observation without checking it.
Fix: Ask for a source ID with every claim, and for important answers require two sources or a person's review.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Add a stop condition for repeated actions
Take react_loop.py and change the loop so it stops with a clear message when the stand-in asks for the same action with the same arguments twice in a row. Then change the script so the stand-in repeats search_docs and check that your guardrail catches it.
You will need
- The
react_loop.pyfile from this lesson. - A new
SCRIPTwhere the second item repeats the first search. - The research question: "Which battery had fewer returns for charging faults?"
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- Keep a variable called
lastthat holds the previous action as a pair of name and args. - Compare it with the new action before you run the tool.
- Put the check before the tool call, not after.
Show a model answer
Before the loop, set last = None. Inside the loop, after reading name and args, add: if (name, args) == last: print(" Stopped: repeated action") and return. Then, after the tool call, set last = (name, args). The comparison works because a tuple of a string and a dictionary can be compared with ==. In the normal script, no two neighbouring actions match, so it still ends with the answer. In the changed script, the second search matches the first, so the loop stops with the message and the tool never runs a second time. This is a stop condition written in code, which the model cannot skip.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. The model only asks for an action. Your code decides whether it is allowed and runs it. The first option is a common mistake: if the model ran tools itself, your step limit and allowlist could not stop it.
Show the answer and explanation
Answer: B. Your code saw every action and result, so its trace is reliable. The model's shown reasoning is tempting to trust, but it may be missing or may not match what happened. The final answer says nothing about the path taken.
Show the answer and explanation
Answer: B. Research has steps that cannot be known in advance. A fixed nightly job is better as a plain workflow, and it would waste model calls in a loop that has nothing to decide.
Frequently asked questions
What does ReAct mean in AI?
It stands for reasoning and acting. An AI agent decides its next step, uses a tool, reads the result and decides again. The name comes from a 2022 research paper, and today the idea is a common way to build agents that use tools.
How is ReAct different from a normal chatbot?
A chatbot only replies with text. A reason-and-act agent can also ask your code to run tools, such as searching documents, and then use the results to decide what to do next.
How do I stop an AI agent from looping forever?
Set a step limit in your code, such as MAX_ROUNDS. Also stop when the same action repeats or the same error comes back twice. Then return a clear message or pass the job to a person.
Should I show the agent's reasoning to users?
You can show a short summary of what it did, such as which documents it read. Do not treat the model's own explanation as proof. Show the actions and sources your code recorded, because those are facts you can check.
- Written by
- PromptFable Editorial
- Last updated 18 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- ReAct: Synergizing Reasoning and Acting in Language Models(opens in a new tab)
Yao et al., arXiv · The 2022 research paper that named the pattern. Read it for the original description.
- Building effective agents(opens in a new tab)
Anthropic · Official documentation · Describes when a simple workflow is enough and when an agent loop is worth its cost.
- How tool use works(opens in a new tab)
Anthropic · Official documentation · The request, run and return cycle that the loop is built on.
- LLM06:2025 Excessive Agency(opens in a new tab)
OWASP · Official documentation · Why an agent should have only the tools and permissions its job needs.
- Function calling with the Gemini API(opens in a new tab)
Google · Official documentation · How a model asks your code to run a function and how the result is returned.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.