Compare ReAct for tightly coupled tool use with Plan-and-Execute for longer workflows with explicit planning and replanning.
Structured output gave the runtime a reliable shape for one model response. Agent architectures ask the next question: who decides the next step when one response isn't enough?
Agent architectures turn a one-shot model call into a stateful system that can request tools, observe results, and continue. ReAct and plan-and-execute patterns give you two control loops for multi-step product work.
A code assistant that inspects a failed CI job needs to read the error log, check the changed files, explain the failure, and open a rollback proposal if the release broke production. A plain LLM call is passive: it produces tokens, but it doesn't execute side effects on its own. Agent runtimes bridge that gap by treating the model as a reasoning engine that can choose tools, update state, and coordinate multi-step work.
Most product paths should stay deterministic. An agent becomes useful when the next safe step depends on live evidence that can't be enumerated cheaply in advance, and when your runtime can check its effects.
Before the patterns, one reality check that frames everything below. Anthropic's guidance on building effective agents draws a line between two kinds of systems[1]. A workflow is a system where LLMs and tools follow predefined code paths that you wrote. An agent is a system where the model dynamically directs its own process and tool use, deciding at runtime how to reach the goal. Both are useful. The guidance is blunt: find the simplest pattern that works and add complexity only when it demonstrably improves outcomes, because agentic systems trade latency and cost for flexibility. Stripped down, an agent is "just LLMs using tools based on environmental feedback in a loop." ReAct and Plan-and-Execute are two named shapes of that loop, not a special runtime category. A fixed prompt chain or a single tool-calling call is often the right answer.
Agent loop: An agent needs more than an LLM with tools. It's a loop with state, allowed actions, observations, and runtime boundaries. Some agents also need planning or long-term memory; don't add those components until the task requires them. If the steps are known in advance, a workflow is cheaper and easier to debug.
Two ideas you have already met become the agent loop. Chain-of-Thought prompting studied how intermediate reasoning steps in demonstrations can elicit multi-step reasoning before answers.[2] Function calling lets a model request an action using arguments that your code validates and executes. An agent runtime turns these ideas into a loop: request a next move, execute an allowed tool, record an observation, and repeat. Two useful loop shapes matter most here: ReAct, which decides one step at a time, and Plan-and-Execute, which drafts a roadmap before moving.
The ReAct (Reason + Act) pattern is an influential agent loop. Proposed by Yao et al. (2023), it interleaves reasoning traces with actions and observations on the paper's evaluated tasks.[3] A reasoning-only response can't inspect a live CI failure. An acting-only policy may issue tool calls without enough task context. ReAct combines a next-step decision with fresh environmental evidence.
A code agent resolving a failed release follows the same loop. It checks the CI failure (Observation), decides the error points at a migration (Reasoning), reads the migration diff (Action), then runs a targeted test before choosing the next step. ReAct applies this observe-decide-act pattern to AI.
The paper writes this pattern as Thought, Action, and Observation. Treat Thought: as explanatory notation, not as a production API contract. OpenAI's current reasoning documentation describes reasoning tokens as hidden output tokens rather than a raw trace returned to the application.[4] Store the observable state you can audit: validated tool requests, tool results, bounded decision notes when a user needs an explanation, and budget usage.
The analogy that fits best is an on-call engineer debugging from live evidence. They read one signal, form a hypothesis, run the next narrow check, and update the route from what came back. ReAct is that loop. It doesn't assume the whole incident path is known upfront. It adapts after every observation.
This visual shows that feedback loop: every observation becomes the state for the next reasoning step.
In practice, a user's request triggers repeated next-move decisions, tool execution, and observations until the model returns a final answer or the runtime stops the loop.
This paper-style ReAct trace asks the agent to triage a failed deployment. The Thought lines make the lesson legible; an application can implement the same control loop without storing private reasoning text.
1Question: Release 2026.06.20 failed after merging PR 1842. Determine the next safe action.
2
3Thought: I need the failing job and error first.
4Action: get_ci_failure(run_id="R1842")
5Observation: migration-test failed with duplicate column "team_id".
6
7Thought: I should inspect the migration changed by the PR.
8Action: read_file(path="db/migrations/20260620_add_team_id.sql")
9Observation: Migration adds team_id without IF NOT EXISTS.
10
11Thought: Idempotency is the likely cause. I need a targeted verification.
12Action: run_test(name="migration_replay")
13Observation: Replaying migrations on a seeded database reproduces the duplicate-column error.
14
15Thought: The release should not proceed until the migration is made idempotent.
16Action: open_patch(path="db/migrations/20260620_add_team_id.sql", change="guard ADD COLUMN")
17Observation: Patch D-2041 created and migration_replay passes.
18
19Thought: The safe next action is to review and merge the idempotency patch before retrying deploy.
20Answer: Release remains blocked. Patch D-2041 makes the migration idempotent and passes migration_replay; retry deploy after review.Notice what happens to state as the loop runs. After the first tool call, the runtime has the goal, the action, and the observation. After another call, it has another evidence record to make available to the next model turn. If every raw result is appended, context grows with the trajectory; long tasks need summaries, external state, or another control pattern. The exact token cost depends on your prompts, tools, and summarization policy.
A functional runtime validates each requested move before it executes anything. The model-facing schema in a hosted API can enforce the shape of NextMove; this dependency-free example focuses on application responsibilities: tool allowlisting, step limits, observation storage, and a final answer grounded in those observations.
1from dataclasses import dataclass, field
2from typing import Callable, Literal
3
4MoveKind = Literal["tool", "answer"]
5
6@dataclass(frozen=True)
7class NextMove:
8 kind: MoveKind
9 tool: str | None = None
10 arguments: dict[str, str] = field(default_factory=dict)
11 answer: str | None = None
12
13@dataclass
14class RuntimeState:
15 goal: str
16 observations: list[str] = field(default_factory=list)
17 tool_calls: int = 0
18
19def run_moves(
20 moves: list[NextMove],
21 tools: dict[str, Callable[[dict[str, str]], str]],
22 max_steps: int = 3,
23) -> tuple[str, RuntimeState]:
24 state = RuntimeState(goal="Triage failed release R1842")
25
26 for move in moves:
27 if move.kind == "answer":
28 if not state.observations or not move.answer:
29 raise ValueError("answer requires observed evidence")
30 return move.answer, state
31
32 if state.tool_calls >= max_steps:
33 return "Stopped: tool-call budget exhausted.", state
34 if move.kind != "tool" or move.tool not in tools:
35 raise ValueError("requested tool is not allowed")
36
37 result = tools[move.tool](move.arguments)
38 state.observations.append(f"{move.tool}: {result}")
39 state.tool_calls += 1
40
41 return "Stopped: no final answer.", state
42
43tools = {
44 "get_ci_failure": lambda args: "migration-test duplicate column team_id",
45 "read_file": lambda args: "migration adds team_id without IF NOT EXISTS",
46}
47moves = [
48 NextMove("tool", "get_ci_failure", {"run_id": "R1842"}),
49 NextMove("tool", "read_file", {"path": "db/migrations/20260620_add_team_id.sql"}),
50 NextMove("answer", answer="Block deploy until the migration is made idempotent."),
51]
52answer, state = run_moves(moves, tools)
53print("tool calls:", state.tool_calls)
54print("last observation:", state.observations[-1])
55print("answer:", answer)1tool calls: 2
2last observation: read_file: migration adds team_id without IF NOT EXISTS
3answer: Block deploy until the migration is made idempotent.The model proposes NextMove records. The runtime decides whether a tool is available, whether budget remains, and whether enough evidence exists to return an answer. No free-form private reasoning trace is needed in the audit log.
ReAct's tight interleaving of decisions and actions creates specific failure modes worth knowing:
Infinite loops. ReAct agents can get stuck repeating the same action when a tool returns unhelpful results. If a search returns no results, the agent might search again with the identical query instead of reformulating. Enforcing a maximum step count and tracking action hashes prevents this from running indefinitely.
Context overflow. Each step may append actions, observations, and summaries to the context window. For tasks requiring many steps, that context can eventually exhaust the model's limit. Strategies include summarizing older evidence, storing full results outside the prompt, or switching to a longer-context model.
Grounding failures. ReAct's key strength is grounding reasoning in actual observations rather than the model's internal beliefs. When a tool returns misleading or incomplete data, the agent can chase a false trail. Reliable implementations include sanity checks on tool outputs before feeding them back as observations.
Interface errors. If the model's requested action doesn't satisfy the expected tool schema, the runtime must reject it. JSON mode only gives valid JSON syntax; it doesn't validate correct tool fields. Use strict tool schemas where supported and validate the resulting arguments and policy in application code.[5]
Self-consistency samples multiple reasoning paths and selects a common answer, originally for reasoning tasks with a defined final response.[6] Applying that idea to an agent requires a boundary: candidate trajectories can inspect fixed, read-only evidence or run in a sandbox, but they shouldn't each open real pull requests, roll back services, or post incident updates. After selecting a proposal, the runtime still applies policy and executes at most one approved effect.
1from collections import Counter
2from typing import Protocol
3
4class RecommendationAgent(Protocol):
5 def recommend(self, evidence: dict[str, str]) -> str:
6 ...
7
8class ScriptedCandidates:
9 def __init__(self, proposals: list[str]):
10 self.proposals = iter(proposals)
11
12 def recommend(self, evidence: dict[str, str]) -> str:
13 assert evidence["ci_error"] == "duplicate column"
14 return next(self.proposals)
15
16def choose_proposal(agent: RecommendationAgent, evidence: dict[str, str], samples: int) -> str:
17 proposals = [agent.recommend(evidence) for _ in range(samples)]
18 return Counter(proposals).most_common(1)[0][0]
19
20facts = {"ci_error": "duplicate column", "migration": "missing idempotency guard"}
21candidates = ScriptedCandidates(["patch_migration", "rollback_release", "patch_migration"])
22selected = choose_proposal(candidates, facts, samples=3)
23print("selected proposal:", selected)
24print("real effects executed during vote:", 0)1selected proposal: patch_migration
2real effects executed during vote: 0Self-consistency multiplies model and read-only tool work by the number of samples. It can support a reviewable recommendation, but it isn't permission to repeat writes.
Self-consistency samples many trajectories in parallel and votes. Reflexion (Shinn et al., 2023)[7] takes the opposite approach across attempts: when a trajectory fails, the agent writes a short natural-language reflection on why it failed and stores that note in memory, then retries with the reflection added to its context. The original paper calls this "verbal reinforcement learning," because the agent improves through written self-critique rather than weight updates. On the HumanEval coding benchmark, Reflexion reported 91% pass@1, above the 80% GPT-4 baseline reported in the same paper.
The mechanism fits the deployment-debugging example directly. Suppose a ReAct attempt declares a release fixed after reading one stale CI log, and an evaluator flags it as wrong because the targeted test still fails. A Reflexion-style agent records a note such as "verify the current run before proposing a deploy retry," then carries that note into the next attempt. Reflexion works best when three conditions hold: you get a clear pass or fail signal, the notes stay short and task-specific, and retries are allowed. It's a memory technique layered on top of ReAct, not a replacement control loop.
1from dataclasses import dataclass, field
2
3@dataclass
4class AttemptMemory:
5 lessons: list[str] = field(default_factory=list)
6
7def record_evaluated_lesson(memory: AttemptMemory, passed: bool, lesson: str) -> None:
8 if not passed:
9 memory.lessons.append(lesson)
10
11def next_attempt_context(memory: AttemptMemory) -> str:
12 return memory.lessons[-1] if memory.lessons else "No prior evaluated failure."
13
14memory = AttemptMemory()
15record_evaluated_lesson(memory, passed=False, lesson="Verify current CI before retrying deploy.")
16record_evaluated_lesson(memory, passed=True, lesson="Ignore: successful trial.")
17print("stored lessons:", len(memory.lessons))
18print("next attempt reminder:", next_attempt_context(memory))1stored lessons: 1
2next attempt reminder: Verify current CI before retrying deploy.The failure signal comes from an evaluator or environment check, not from the agent deciding that its own unsupported story sounds convincing.
ReAct is useful, but it's local: it chooses the next action from the latest observation rather than from a committed global plan. For complex tasks such as "audit every failed workflow from yesterday and draft recovery actions," a ReAct agent might get lost in one flaky test and forget the overall release-readiness workflow.
If ReAct is like an on-call engineer resolving the next visible signal, Plan-and-Execute is like an incident runbook. First, the planner maps the recovery steps, then executors handle CI checks, log reads, owner lookups, patch drafting, and rollout decisions in order.
Plan-and-Execute decouples planning from execution. It's a practical runtime pattern related to plan-first prompting techniques such as Plan-and-Solve,[8] but it doesn't imply one standard protocol. A plan may be a linear checklist or a dependency graph:
These roles don't have to be different models. Small systems often use one model in separate planning and execution prompts, while cost-optimized systems route planning to a stronger model and execution to cheaper specialists.
This visual shows the key separation: a planner owns the global shape, executors own local work, and verifier/replanner steps keep the plan from going stale.
This architecture cleanly separates planning from execution. A planner drafts the initial steps, executors work through them, and a validation loop checks whether the remaining plan still makes sense. That global plan reduces goal drift on long tasks, but it doesn't eliminate it. A weak initial plan can still send every executor in the wrong direction.
Return to the R1842 example. A Plan-and-Execute agent would first emit a plan, then execute it:
11. Check the failed CI run.
22. Read changed migration files.
33. Run a targeted migration replay test.
44. Decide action: patch, roll back, or escalate.
55. Execute the approved action and confirm.1Step 1: get_ci_failure("R1842") -> "migration-test duplicate column team_id"
2Step 2: read_file("db/migrations/20260620_add_team_id.sql") -> "ADD COLUMN team_id"
3Step 3: run_test("migration_replay") -> "fails before patch"
4Step 4: decide_action(...) -> "patch migration idempotency"
5Step 5: open_patch("db/migrations/20260620_add_team_id.sql") -> "D-2041, replay passes"The executor for Step 4 might itself be a small ReAct agent that reasons about the inputs and picks the best action. That's a common hybrid pattern: a global planner keeps the big picture, while local ReAct loops handle individual decisions.
A useful plan records dependencies rather than pretending all five steps are sequential. In this release example, CI metadata, changed files, and deployment health can be fetched independently. The action decision must wait for all three.
1from dataclasses import dataclass
2
3@dataclass(frozen=True)
4class PlanStep:
5 id: str
6 action: str
7 depends_on: tuple[str, ...] = ()
8
9def ready_steps(plan: list[PlanStep], completed: set[str]) -> list[str]:
10 return [
11 step.id
12 for step in plan
13 if step.id not in completed and set(step.depends_on) <= completed
14 ]
15
16plan = [
17 PlanStep("ci", "get_ci_failure"),
18 PlanStep("diff", "read_changed_files"),
19 PlanStep("health", "check_deploy_health"),
20 PlanStep("decision", "choose_recovery", ("ci", "diff", "health")),
21 PlanStep("effect", "open_patch_or_rollback", ("decision",)),
22]
23print("ready first:", ready_steps(plan, set()))
24print("ready after facts:", ready_steps(plan, {"ci", "diff", "health"}))1ready first: ['ci', 'diff', 'health']
2ready after facts: ['decision']This representation exposes concurrency without overstating it. The first three reads can run together only if the runtime supports concurrent execution and the tools don't share a conflicting resource.
Choosing between ReAct and Plan-and-Execute requires balancing cost, task complexity, and reliability. ReAct is useful for short, evidence-dependent decisions, but it can drift on long tasks because it lacks an explicit global plan. Plan-and-Execute gives you that plan, but it can produce brittle execution if you don't pair it with validation and replanning.
| Feature | ReAct | Plan-and-Execute |
|---|---|---|
| Control Flow | Next move follows the latest observation | Global plan first, then localized execution |
| Use Case | Search, debugging, exploratory workflows, API navigation | Research, ETL, code migration, long-horizon tasks with decomposable subtasks |
| Failure Mode | Local loop or goal drift after many steps | Brittle initial plan or stale plan after the environment changes |
| Token Cost | Grows when the loop carries a large trajectory forward | Can bound each executor's context when outputs are externalized, but planning and replanning add calls |
| Latency | Sequential when every tool result gates the next move | Planner adds a serial step; independent executor work can run in parallel when dependencies allow |
| Error Recovery | Immediate pivot on the next step | Requires an explicit validation or replanning loop |
Read it as a gate, not a spectrum. First ask whether a fresh tool result can change next safe action. If not, planner overhead buys nothing and ordinary workflow code is better. If yes, then ask how much route is known upfront: ReAct for discovered paths, Plan-and-Execute for stable decomposition, hybrid when both appear in same task.
Use ReAct when:
Use Plan-and-Execute when:
Plan-and-Execute's main weakness is the brittleness of the initial plan. If the planner misinterprets the user's intent, the entire execution pipeline is misaligned. Worse, downstream executor steps often depend on outputs from earlier steps, so a wrong assumption in Step 1 can invalidate Steps 2 through N. A ReAct loop gets an earlier opportunity to react to new evidence, but it can still repeat a bad decision without runtime checks.
Production implementations address this by:
When evidence breaks an assumption, patch only unfinished work. The completed CI query remains an observation; a revised plan shouldn't issue the same write again.
1from dataclasses import dataclass
2
3@dataclass(frozen=True)
4class Step:
5 id: str
6 action: str
7
8def patch_remaining(steps: list[Step], completed: set[str], ci_api_down: bool) -> list[Step]:
9 remaining = [step for step in steps if step.id not in completed]
10 if not ci_api_down:
11 return remaining
12 return [
13 Step("cached_logs", "read_last_known_ci_logs"),
14 Step("mark_deferred", "flag_runs_for_retry"),
15 *[step for step in remaining if step.id not in {"fetch_ci_logs", "close_incident"}],
16 ]
17
18original = [
19 Step("load_runs", "query_failed_workflows"),
20 Step("fetch_ci_logs", "fetch_ci_logs"),
21 Step("close_incident", "close_recovered_incidents"),
22 Step("summary", "draft_summary"),
23]
24revised = patch_remaining(original, {"load_runs"}, ci_api_down=True)
25print("completed kept:", ["load_runs"])
26print("remaining actions:", [step.action for step in revised])1completed kept: ['load_runs']
2remaining actions: ['read_last_known_ci_logs', 'flag_runs_for_retry', 'draft_summary']Calling a tool is shorthand. The side effect still happens in your runtime (your Python or TypeScript code). At the API boundary, the model may emit raw JSON, a structured tool-call object, or another structured output rather than plain text.[5] Your application is the part that validates arguments, executes the external call, and feeds the result back into the next model turn.
To make this work, the LLM needs to know exactly what tools are available and how to use them. In practice, the runtime passes structured tool definitions either in the prompt or through the provider's tool-calling API. Those definitions are usually JSON-schema-like rather than the full JSON Schema spec, and the model uses the field descriptions, enums, and required keys to construct a valid request.[5]
Tool use connects model decisions to fresh, authorized evidence and controlled effects. A CI-status tool can return the latest failed step; a write tool can open a rollback proposal only after application policy approves it.
Tools need an argument contract so the LLM knows the allowed request shape. Tool-calling APIs can expose such schemas directly to the model. In a supported strict schema mode, the provider enforces the declared structure and types. The application still validates authorization, resource existence, semantic constraints, and policy, including whether this actor may inspect the requested CI run.
This example deliberately leaves include_logs optional because it's an application-level schema. If you submit a schema in OpenAI strict mode, every property must appear in required; represent a conceptually optional field with a nullable type instead.[5]
1ci_status_tool_schema = {
2 "name": "get_ci_status",
3 "description": "Get the current status for a CI run",
4 "parameters": {
5 "type": "object",
6 "properties": {
7 "run_id": {
8 "type": "string",
9 "description": "The CI run identifier"
10 },
11 "include_logs": {
12 "type": "boolean"
13 }
14 },
15 "required": ["run_id"],
16 "additionalProperties": False
17 }
18}
19
20def execute_ci_lookup(arguments: dict[str, object], authorized_runs: set[str]) -> str:
21 allowed_keys = {"run_id", "include_logs"}
22 if "run_id" not in arguments or set(arguments) - allowed_keys:
23 return "reject: invalid tool arguments"
24
25 run_id = arguments["run_id"]
26 include_logs = arguments.get("include_logs", False)
27 if not isinstance(run_id, str) or not isinstance(include_logs, bool):
28 return "reject: invalid tool arguments"
29 if run_id not in authorized_runs:
30 return "deny: run not authorized for actor"
31 return f"allow: return status for {run_id}"
32
33print(execute_ci_lookup({"run_id": "R1842"}, {"R1842"}))
34print(execute_ci_lookup({"run_id": "R1842", "include_logs": "yes"}, {"R1842"}))
35print(execute_ci_lookup({"run_id": "R9999"}, {"R1842"}))1allow: return status for R1842
2reject: invalid tool arguments
3deny: run not authorized for actorThe underlying mechanics of "Tool Use" involve a hidden round-trip handled by your application:
{"tool": "get_ci_status", "args": {"run_id": "R1842"}}"failed: migration-test duplicate column"."failed: migration-test duplicate column"This hidden round-trip relies entirely on your application code. The LLM doesn't execute the API request itself; it merely generates the structured request representing the intended call. The host application needs to securely execute the external call, manage connection timeouts, handle authentication, and then format the response back into a format that the LLM can ingest for its next reasoning step.
Common mistake: Treating schema validation as sufficient. Constrained outputs reduce syntax errors, but your runtime still needs to handle semantically bad arguments, missing auth, and tool timeouts.
A write needs another boundary: retrying the same agent turn must not create duplicate effects. Give each intended effect an idempotency key owned by your application, not invented afresh on every model retry.
1def open_rollback_once(
2 release_id: str,
3 idempotency_key: str,
4 applied: dict[str, str],
5) -> str:
6 if idempotency_key in applied:
7 return f"replay: {applied[idempotency_key]}"
8 proposal_id = f"RB-{len(applied) + 2041}"
9 applied[idempotency_key] = proposal_id
10 return f"created: {proposal_id} for {release_id}"
11
12effects: dict[str, str] = {}
13key = "approve-rollback:release-2026-06-20:policy-v3"
14print(open_rollback_once("release-2026-06-20", key, effects))
15print(open_rollback_once("release-2026-06-20", key, effects))
16print("rollback proposals created:", len(effects))1created: RB-2041 for release-2026-06-20
2replay: RB-2041
3rollback proposals created: 1An unconstrained loop can spend far beyond the intended request budget or issue duplicate writes. Production systems need runtime controls before an agent is allowed to affect deployments, repositories, or incident communications.
Agents operate in dynamic environments where external state can change between steps. When a tool returns an unexpected format, or an API call times out, a naive agent might blindly retry the exact same action or invent a response. Because an observation influences later moves, errors can compound. A single unsupported conclusion can derail the execution plan.
To build reliable agents, engineers need strong guardrails at the runtime layer. This means treating the LLM as an unreliable sub-component rather than a deterministic program. You need to validate all structured outputs, enforce hard step and token budgets, and return actionable error messages back to the model when a failure occurs.
1from dataclasses import dataclass
2
3@dataclass
4class Budget:
5 reads_left: int
6 writes_left: int
7
8def authorize_action(kind: str, budget: Budget) -> str:
9 if kind == "read" and budget.reads_left > 0:
10 budget.reads_left -= 1
11 return "allow read"
12 if kind == "write" and budget.writes_left > 0:
13 budget.writes_left -= 1
14 return "allow write"
15 return f"stop: {kind} budget exhausted"
16
17budget = Budget(reads_left=2, writes_left=1)
18print(authorize_action("read", budget))
19print(authorize_action("write", budget))
20print(authorize_action("write", budget))1allow read
2allow write
3stop: write budget exhausted| Failure Mode | Symptom | Cause | Fix |
|---|---|---|---|
| Infinite Loops | Agent repeats the same action (e.g., search("R1842 failure")) forever. | Tool returns an unhelpful result and the agent doesn't reformulate. | Cycle Detection: Detect repeated recent patterns without progress, then stop or change strategy. |
| Hallucinated Tools | Agent calls VideoGenerator() when no such tool exists. | Model invents a tool name that wasn't in the allowlist. | Allowlisted Tools: Reject unknown tool names before execution and return a bounded error observation. |
| Context Overflow | Conversation history exceeds token limit. | Every step appends raw observations or large summaries. | External State + Summary: Keep authoritative results outside the prompt and pass a bounded summary plus recent evidence. |
| Goal Drift | Agent forgets the original user intent after many steps. | Long trajectory pushes the original query out of the model's attention window. | Periodic Goal Restatement: Inject the original user query or a compact goal summary back into the next model call every K steps. |
| Interface Errors | Requested action fails its tool schema. | Model emits missing, invalid, or unsupported arguments. | Strict Tool Contract: Use provider strict schemas when available, then validate arguments and policy in runtime code. |
| Brittle Plans | Plan-and-Execute planner misinterprets intent, cascading failures through all steps. | Planner made a wrong assumption at T=0 and executors blindly followed it. | Plan Validation: Add a second-pass check that each plan step is achievable; trigger replanning early rather than waiting for executor failure. |
To prevent loops, track normalized actions in a short recent window. The detector below catches repeated single actions and short alternating patterns. A production detector also needs progress signals, because an agent can repeat a valid read while receiving new pages of results.
1def normalized(call: dict[str, object]) -> tuple[str, tuple[tuple[str, str], ...]]:
2 args = call.get("args", {})
3 assert isinstance(args, dict)
4 return str(call["tool"]), tuple(sorted((str(k), str(v)) for k, v in args.items()))
5
6def repeated_recent_pattern(history: list[dict[str, object]], max_period: int = 3) -> bool:
7 actions = [normalized(call) for call in history]
8 for period in range(1, min(max_period, len(actions) // 2) + 1):
9 if actions[-period:] == actions[-2 * period:-period]:
10 return True
11 return False
12
13same = [
14 {"tool": "get_ci_failure", "args": {"run_id": "R1842"}},
15 {"tool": "get_ci_failure", "args": {"run_id": "R1842"}},
16]
17alternating = [
18 {"tool": "get_ci_failure", "args": {"run_id": "R1842"}},
19 {"tool": "read_file", "args": {"path": "db/migrations/20260620_add_team_id.sql"}},
20 {"tool": "get_ci_failure", "args": {"run_id": "R1842"}},
21 {"tool": "read_file", "args": {"path": "db/migrations/20260620_add_team_id.sql"}},
22]
23progress = [
24 {"tool": "get_ci_failure", "args": {"run_id": "R1842"}},
25 {"tool": "read_file", "args": {"path": "db/migrations/20260620_add_team_id.sql"}},
26]
27print("same-action loop:", repeated_recent_pattern(same))
28print("alternating loop:", repeated_recent_pattern(alternating))
29print("progress loop:", repeated_recent_pattern(progress))1same-action loop: True
2alternating loop: True
3progress loop: FalseThe partial ReAct trace below comes from a different release. Three steps are shown, but the fourth step contains a mistake. Read the trace, identify what goes wrong, and decide what the agent should have done instead.
1Question: Release R2099 failed in production after a config change.
2
3Thought: I need the alert and affected service.
4Action: get_alert(alert_id="A2099")
5Observation: p95 latency is high in us-east for api-gateway.
6
7Thought: I should check whether the release reached all regions.
8Action: get_deploy_state(release_id="R2099")
9Observation: us-east runs commit abc123; eu-west runs previous commit def456.
10
11Thought: eu-west is healthy on an older commit, so I will close the incident as rollback complete.
12Action: close_incident(alert_id="A2099", resolution="rollback complete")
13Observation: Incident closed while us-east latency remains high.
14
15Thought: ???What went wrong? The agent compared a healthy region on an older commit with an unhealthy region on the new commit, but never verified that the affected region was rolled back or recovered. A different region's health doesn't prove the incident is resolved. The agent should have checked the service health in us-east after rollback or kept the incident open.
The fix: Add an enforced verify_region_recovered precondition before the close action. A prompt reminder is useful context, but it can't block a write when the model ignores it.
Assume the monitoring system returns current latency for the affected region. The runtime can block closure until the target region meets its recovery threshold.
1def incident_action(region_latency_ms: int, max_p95_ms: int) -> str:
2 if region_latency_ms <= max_p95_ms:
3 return "eligible for reviewed closure"
4 return "keep incident open"
5
6observed = {"us-east": 940, "eu-west": 120}
7affected_region = "us-east"
8print("healthy elsewhere:", observed["eu-west"] <= 200)
9print("affected recovered:", observed[affected_region] <= 200)
10print("action:", incident_action(observed[affected_region], max_p95_ms=200))1healthy elsewhere: True
2affected recovered: False
3action: keep incident openAnswer every question, then check your score. Score above 75% to mark this lesson complete.
10 questions remaining.
Building Effective Agents
Anthropic · 2024
Chain-of-Thought Prompting Elicits Reasoning in Large Language Models.
Wei, J., et al. · 2022 · NeurIPS
ReAct: Synergizing Reasoning and Acting in Language Models.
Yao, S., Zhao, J., Yu, D., Du, N., Shafran, I., Narasimhan, K., & Cao, Y. · 2023 · ICLR 2023
Reasoning models
OpenAI · 2026
Structured outputs
OpenAI · 2024
Self-Consistency Improves Chain of Thought Reasoning in Language Models.
Wang, X., et al. · 2022
Reflexion: Language Agents with Verbal Reinforcement Learning.
Shinn, N., et al. · 2023
Plan-and-Solve Prompting: Improving Zero-Shot Chain-of-Thought Reasoning by Large Language Models.
Wang, L., et al. · 2023
Questions and insights from fellow learners.