Foundations to Frontier
Tests
F. NLP and Large Language Models › F11 Agents and Tool Use

ReAct and planning loops

An agent repeatedly decides what to do, does it, and looks at what happened. ReAct interleaves reasoning ('thoughts') with actions and observations; plan-and-execute writes a plan first and replans when something goes wrong; Reflexion retries a failed task with a written lesson. Closing the loop matters because errors compound: a plan executed blindly succeeds only if every step is right. In the exercises you write a ReAct parser, a minimal agent loop and a loop detector. You then simulate tasks of 4 to 16 steps, where each step is chosen correctly 90% of the time and actions fail visibly 10% of the time. On 16-step tasks open-loop execution succeeded 3% of the time. ReAct succeeded 83% with about 19 model calls. Plan-and-execute succeeded 67% with about 4 calls, losing the wrong steps it failed to notice. Reflexion with up to 3 attempts reached 99.5%, but only because a success check was available.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Driving with your eyes open

Planning a route and then driving it with your eyes closed fails at the first unexpected roadwork. Good drivers look, adjust and continue. Language-model agents work the same way: they think about the next step, act through a tool, read the result, and decide again. The demo shows why this matters: with no recovery, a long task fails almost surely; with a chance to notice and retry each step, success stays high.

Agent lab
10 steps at p = 0.9: success 34.9% with no recovery (red), 90.4% with 1 retry per step after seeing an error (green). Long tasks need error recovery.
Why engineers care

Agent loops are how coding assistants, research assistants and robot task planners turn one request into dozens of coordinated actions.

📝 Quick check (Level 0)
0/3 answered
  1. 1. ReAct interleaves…
  2. 2. Open-loop execution…
  3. 3. Long tasks need…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • ReAct: prompt format Thought → Action → Observation, repeated until a final answer; reasoning guides actions and observations ground reasoning.
  • Plan-and-execute: a planner writes the whole plan; an executor runs steps (possibly with a cheaper model); replan on failure. Fewer calls to the expensive model.
  • Reflexion: after a failed attempt, the agent writes a verbal lesson into memory and tries again; needs a success signal (tests, a checker, a reward).
  • Tree search over actions: LATS, tree of thoughts (F12-3) explore alternatives at more cost.
  • Stopping: final-answer detection, step budgets, loop detection (repeated actions), cost limits.
  • Scratchpad: the transcript grows every turn; trim or summarise old turns (F11-3).
  • Benchmarks: HotpotQA and ALFWorld (ReAct), WebArena, SWE-bench (F11-5), τ-bench.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Plan-and-execute saves…
  2. 2. Reflexion needs…
  3. 3. A loop detector looks for…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Building an agent loop

Exercise 1.

  • Parse ReAct-format output.
  • Run a thought-action-observation loop with a step limit.
  • Detect repeated actions.

Practice.

  • Frameworks: LangGraph, LlamaIndex agents, OpenAI Agents SDK, Claude Agent SDK, smolagents; or a 30-line loop with native tool calling.
  • Prefer native tool calling over parsing free text where available.
  • Set step and cost budgets; detect loops; return partial progress on timeout.
  • Make observations informative: include error messages and relevant state, not raw dumps.
  • Trace every turn (LangSmith, Langfuse, OpenTelemetry) to debug failures.
msgs = [{"role": "user", "content": task}]
for step in range(MAX_STEPS):
    resp = client.messages.create(model=MODEL, max_tokens=1000, tools=tools, messages=msgs)
    msgs.append({"role": "assistant", "content": resp.content})
    calls = [b for b in resp.content if b.type == "tool_use"]
    if not calls: break                                  # final answer
    msgs.append({"role": "user", "content": [
        {"type": "tool_result", "tool_use_id": c.id, "content": dispatch(registry, c.name, c.input)} for c in calls]})
🐍 Exercise 1: a minimal ReAct agent
Parse ReAct output, run the loop with observations and a step limit, and detect repeated actions.
📝 Quick check (Level 2)
0/3 answered
  1. 1. An agent framework:
  2. 2. Every agent loop needs…
  3. 3. Useful observations include…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Open loop. If each step is chosen correctly with probability p and executes without failure with probability 1 − f, a blind n-step plan succeeds with (p(1 − f))^n: 0.81^16 ≈ 3%.

Closed loop. With observations, failures are retried, so a step costs on average 1/(p(1 − f)) turns. Success is then limited by harmful wrong actions, getting stuck, and the budget, not by the product over steps.

Plan-and-execute. Execution checks observations, so visible failures trigger replanning, but a wrong planned step is only caught if the executor notices it. Unnoticed wrong steps make the result wrong. It trades some reliability for many fewer planner calls.

Retries with lessons. With a success check, k attempts succeed with 1 − Π(1 − q_i); written lessons raise later q_i. Without a reliable check, retries cannot tell success from failure.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Blind n-step success:
  2. 2. Closed-loop expected turns per step:
  3. 3. Plan-and-execute fails on…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How much does closing the loop help as tasks get longer, and what do planning and retries trade off?

History.

  • S. Yao et al., “ReAct: synergizing reasoning and acting in language models” (ICLR 2023).
  • N. Shinn et al., “Reflexion: language agents with verbal reinforcement learning” (NeurIPS 2023).
  • L. Wang et al., “Plan-and-solve prompting” (2023); A. Zhou et al., “Language agent tree search” (2024).

Exercise 2. Tasks of n subgoals; 2000 episodes per setting; budget 3n + 4 turns.

  • Step model: right action 90% of the time; a right action fails visibly 10% of the time; a wrong action undoes a subgoal 30% of the time; the agent gets stuck 1% per turn.
  • Plan-and-execute: one call plans the remaining steps; failures and 80% of wrong steps are noticed and trigger replanning.
  • Reflexion: up to 3 ReAct attempts; after a failure, accuracy rises to 95%.
method success n = 4 n = 8 n = 16 LLM calls at n = 16
open loop 0.426 0.174 0.030 1
ReAct 0.943 0.892 0.826 18.7
plan-and-execute 0.894 0.835 0.671 3.7
Reflexion, 3 attempts 1.000 0.999 0.995 22.6
  • Open loop collapses with length, as (0.81)^n predicts.
  • ReAct kept most of its success at 16 steps; its losses were harmful wrong actions, getting stuck and the budget.
  • Plan-and-execute used 5 times fewer calls but lost the unnoticed wrong steps, which compound with length.
  • Reflexion nearly always succeeded, but it assumes failures can be detected and the task retried, which is not true of irreversible actions or tasks without a checker.
  • Seeds 1 and 2: ReAct at n = 16 0.809 and 0.836; plan-and-execute 0.674 and 0.672.
  • Caveat: all rates are assumptions; plan-and-execute’s calls are long planning calls while ReAct’s are short turns, so call counts are not costs.
🐍 Exercise 2 (research): how much does closing the loop help as tasks get longer, and what do planning and retries trade off?
Simulate open-loop, ReAct, plan-and-execute and Reflexion agents on tasks of 4 to 16 steps.

Agent loops in AI, robotics and aerospace

  • Robot task planning: language-model planners (SayCan, Inner Monologue) close the loop with success detectors and scene descriptions after each skill.
  • Operations automation: agents that query telemetry, run diagnostics and draft reports, with human approval before commands.
  • Engineering workflows: agents that run simulations, check results against requirements and iterate on parameters.

References

  1. S. Yao et al. (2023). “ReAct: synergizing reasoning and acting in language models.” ICLR.
  2. N. Shinn et al. (2023). “Reflexion: language agents with verbal reinforcement learning.” NeurIPS.
  3. W. Huang et al. (2022). “Inner monologue: embodied reasoning through planning with language models.” CoRL.
  4. A. Zhou et al. (2024). “Language agent tree search unifies reasoning, acting, and planning in language models.” ICML.