Skip to main content
LearnMLAcademy
Advanced10 min read

Planning, ReAct & Reflection

Implement AI agent planning loops, ReAct reasoning, and self-reflection, with workflow diagrams, tool-use traces, and safety-focused exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Turn a goal into actions that can be checked

Planning turns a goal into manageable steps; ReAct is the observable decide → act → observe pattern that lets a model choose the next action using fresh evidence; reflection evaluates a result and changes the approach when the evidence shows a problem. These are control strategies, not access to a model's hidden chain-of-thought.

What You Will Learn

  • Choose among plan-first, stepwise ReAct, and reflection strategies.
  • Evaluate observable actions and evidence instead of hidden reasoning.
  • Use verifier results to revise a plan only when needed.
  • Stop on success, no progress, exhausted budgets, or required escalation.

Planning, acting, and checking are different jobs

A plan states intended steps before they run. ReAct chooses one action, observes real evidence, and then chooses again. Reflection or an evaluator checks whether the result meets explicit criteria and may request a bounded revision. These techniques can be combined, but every extra loop adds latency and cost.

Do not treat private chain-of-thought as evidence. Production traces should record observable decisions, selected tools, validated arguments, tool results, verifier scores, and stop reasons. Those are the artifacts a developer can test and a reviewer can audit.

Match the control strategy to the task

Match the control strategy to the task
StrategyBest fitBenefitFailure modeStop condition
Plan-firstKnown dependencies and ordered subtasksMakes coverage and sequence explicitBrittle when evidence changesPlan complete or replan trigger
Stepwise / ReActUncertain environments and tool feedbackAdapts after each observationLoops or repeated weak actionsSuccess, no progress, max steps or budget
Reflection / evaluatorOutputs with checkable quality criteriaFinds specific defects before finalizingEndless polishing or self-confirmationVerifier passes or revision limit reached

Plan, act, observe and decide whether to continue

  1. Decompose the goal into a short plan when dependencies are known, or begin with one safe step when the environment is uncertain.

  2. Choose one typed, permitted action from the current evidence.

  3. Execute the action and record the observable result as an observation.

  4. Compare the observation with success criteria; continue the plan, replan after feedback, or use a verifier/reflection pass.

  5. Stop when evidence is sufficient, progress has stalled, a budget is reached, or human help is required.

Instructional figure

Planning, ReAct, and reflection in one bounded loop

What happens before, during, and after an agent action?

Short plan
dependencies and success
Decide + act
one permitted action
Observe
record evidence
Verify / reflect
pass, revise, or replan
↺ Stop on verified success, no progress, max steps, budget, or escalation
The plan suggests structure, ReAct adapts to observations, and a verifier checks explicit criteria. Success, no progress, or a budget limit ends the loop.

Worked Example: A bounded ReAct trace uses observations to revise once

The required output is a two-field product brief: current price and warranty period. The runtime permits four tool steps and logs only observable goals, actions, results, verifier decisions, and budget—not hidden reasoning.

  1. Step 1 searches approved source A. Its catalog entry supplies the $640 price but no warranty. The verifier compares the observation with the two required fields and reports one gap.
  2. Step 2 changes action rather than repeating the failed search: it queries approved warranty source B. Record W-92 supplies a two-year warranty, so the verifier now finds both claims supported.
  3. The agent stops with one step still available because success—not budget exhaustion—is the correct terminal condition. If it proposed the identical source A query again, a no-progress rule would stop or escalate the run.

What the result means: The useful reasoning evidence is the change in validated action after a named evidence gap, followed by a verifier pass and explicit stop reason. More looping would add cost without improving the answer.

Observable trajectory for a product brief

Observable trajectory for a product brief
StepCurrent goalValidated actionObservationVerifierBudget leftNext decision
1Find price and warrantysearch_catalog(source A, model X)Price = $640; warranty field absentIncomplete: 1 required field missing2 of 4 tool stepsUse a different approved source
2Fill the warranty gapsearch_warranty_registry(source B, model X)Warranty = 2 years; record W-92Pass: both fields have evidence1 of 4 tool stepsStop and write supported brief
No-progress branchWarranty still missingDuplicate detector sees the same source A queryNo new evidence would be producedFail: repeated ineffective action1 of 4 tool stepsStop or escalate instead of looping

Instructional figure

An observable ReAct trajectory ends on evidence—not hidden reasoning

How does a missing field cause one revised action and then a verified stop?

1 · Search source A
Observation: price found; warranty missing
Verify: incomplete
2 of 4 tool steps remain
2 · Search source B
Observation: warranty = 2 years
Verify: pass → STOP
all required fields supported
If source A would be searched again with the same query: duplicate-action detector → NO PROGRESS → escalate or stop
Only inspectable artifacts are shown: chosen action, validated tool, observation, verifier result, remaining budget, and stop reason. Repeating the same ineffective action triggers no-progress escalation.

A Realistic Example: A comparison that changes its plan after new evidence

The agent lists the product facts it must verify, searches an approved source, and discovers that prices use different currencies. It adds a currency lookup, validates the converted values, and writes the comparison only when every required claim has evidence.

Read the Mechanism in Code

Use the label and note to understand what this block represents before reading each line.

Conceptual pseudocode
for step_number in range(MAX_STEPS):
    decision = planner.next_action(goal, evidence)
    if decision.is_final and verifier.supports(decision.answer, evidence):
        return decision.answer

    observation = execute_validated(decision.tool_call)
    evidence.append(observation)

    if no_progress(evidence):
        return escalate("The plan is not gaining new evidence")
Learner note: Conceptual planning/verification loop. planner, verifier, and execute_validated are application abstractions.

Hands-On Runnable Python Lab: Track Evidence Gaps and Remaining Actions

Use a four-action ceiling and two approved observations: a catalog price of $640 and a warranty page stating two years. The example exposes decisions and facts, not private chain-of-thought.

complete = (price_usd ≤ 700) AND (warranty_years ≥ 2); remaining = 4 − actions
The price and warranty tests come from the user’s task. The action ceiling comes from application policy. After two searches, two actions remain; success means stopping now, not spending the rest.
  1. Initially both price and warranty are missing, so query the catalog.
  2. After receiving price=640, the verifier still identifies a warranty gap.
  3. Query the warranty source and test both conditions against the accumulated evidence.
  4. Stop at action 2 with remaining=2. An unsupported case stops when evidence cannot be improved or the action limit is reached.

Evidence increases while the available action budget decreases

Known required fields increase from zero to two while remaining tool actions fall from four to two; the run stops on verified success.Before searchFields known0 / 2Actions left4 / 4After catalogFields known1 / 2Actions left3 / 4After warrantyFields known2 / 2Actions left2 / 4Both criteria pass → STOP with 2 left
Green cells count known required fields; purple cells count actions left. A successful run stops with two actions unspent.

Green cells count known required fields; purple cells count actions left. A successful run stops with two actions unspent.

Complete Python ExercisepythonRunnable
observations = [
    ("catalog", {"price_usd": 640}),
    ("warranty page", {"warranty_years": 2}),
]
required = {"price_usd", "warranty_years"}
evidence = {}
limit = 4
for step, (source, facts) in enumerate(observations, start=1):
    if step > limit:
        break
    missing_before = sorted(required - evidence.keys())
    before = dict(evidence)
    evidence.update(facts)
    missing_after = sorted(required - evidence.keys())
    print(f"action {step}: {source}; missing before={missing_before}")
    print(f"  missing after={missing_after}; remaining={limit - step}")
    if evidence == before:
        print("STOP: no progress")
        break
    if not missing_after:
        passed = evidence["price_usd"] <= 700 and evidence["warranty_years"] >= 2
        print("verifier:", "PASS" if passed else "FAIL")
        print("STOP: criteria checked")
        break
else:
    print("STOP: approved observations exhausted")
Run with Python 3 using only its standard library. No API key, paid service or model download is required. Model proposals and external observations are explicitly simulated; the application logic really executes.
Output from This Exact ProgramOutput
action 1: catalog; missing before=['price_usd', 'warranty_years']
  missing after=['warranty_years']; remaining=3
action 2: warranty page; missing before=['warranty_years']
  missing after=[]; remaining=2
verifier: PASS
STOP: criteria checked
Captured with Python 3.12. Fixture timings, prices and evaluation results are teaching inputs, not provider benchmarks.

What This Run Shows

  1. The missing-field list changes from two fields to one to none, making progress directly observable.
  2. The verifier checks constraints, not just the presence of text. A $900 price would produce FAIL even with both fields present.
  3. Remaining budget is recorded alongside each observation, so a reviewer can see exactly why the run stopped.

A trajectory helps diagnose whether failure came from planning, a tool, missing evidence or an incorrect final synthesis. Evaluate these stages separately instead of scoring only the final paragraph.

From the Exercise to an Application

From the Exercise to an Application
SituationPractical choiceImportant qualification
Missing evidenceChoose an action targeted at that gapDo not repeatedly issue an unchanged query.
Contradictory evidencePreserve both sources and resolve authorityA majority of model votes does not establish truth.
Criteria verifiedStop and report evidenceUnused budget is a saving, not unfinished work.
Experiment: Change warranty_years from 2 to 1.

The evidence is complete but the verifier returns FAIL. This distinction matters: obtaining all requested facts is not the same as satisfying the user’s requirements.

Summary / Key Takeaways

  • Planning decomposes work, ReAct adapts one action at a time using observations, and reflection checks whether the current result should be revised.
  • Plan-first approaches fit tasks with known dependencies; stepwise action is useful when the environment changes as the agent works.
  • Observable actions, tool results, evidence, and verifier outputs are what a production system should evaluate—not hidden chain-of-thought.
  • New observations can justify replanning; a good plan is not a rigid script.
  • Reflection is useful when success criteria can be checked, but unlimited self-review loops can waste tokens and reinforce weak behavior.
  • Stop rules should include success, no measurable progress, step/time/cost limits, and cases that require human help.
  • More reasoning steps are not automatically better; the value of extra planning or reflection must be measured.

Verified Further Reading

These primary research papers and current official specifications support the concepts and implementation guidance in this lesson. The explanations, analogies, exercises, and code above remain original teaching material.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Planning, ReAct & Reflection"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5practical selection
When is a plan-first strategy most appropriate?
Question 2 of 5conceptual
What does the 'observe' step contribute to a ReAct-style loop?
Question 3 of 5conceptual
Why should a production system evaluate observable actions and results rather than rely on hidden chain-of-thought?
Question 4 of 5debugging/diagnostic
An agent reflects five times but each revision makes no measurable improvement. What should happen?
Question 5 of 5application/scenario
A new tool result invalidates the second step of a four-step plan. What is the best action?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1When is a plan-first strategy most appropriate?▼

Correct Answer: When dependencies among several subtasks are known before execution

A plan is most useful when dependencies can be mapped before execution and then revised if evidence changes.

2What does the 'observe' step contribute to a ReAct-style loop?▼

Correct Answer: It brings the result of the previous action back as evidence for the next decision

The observation updates the agent with what actually happened so the next action can adapt.

3Why should a production system evaluate observable actions and results rather than rely on hidden chain-of-thought?▼

Correct Answer: Observable behavior can be logged, tested, and verified without requiring private internal reasoning

Production evaluation can inspect tool calls, results, state, and outputs while avoiding claims about inaccessible hidden reasoning.

4An agent reflects five times but each revision makes no measurable improvement. What should happen?▼

Correct Answer: Trigger a no-progress/step-budget stop or escalation

Reflection should be bounded by progress criteria and budgets; unlimited loops add cost without value.

5A new tool result invalidates the second step of a four-step plan. What is the best action?▼

Correct Answer: Replan the affected steps using the new evidence

Plans are guidance, not rigid scripts. New observations should update future steps when assumptions change.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next