Chapter 5: Agent Control Flow — ReAct, Reflexion, CodeAct & Execution Graphs
Agent control flow governs how an LLM alternates between thinking, acting, observing, and recovering across multi-step horizons. ReAct interleaves natural-language thoughts with discrete actions; Reflexion and CRITIC add episodic or tool-grounded verification loops; CodeAct unifies action spaces into executable Python code to express loops and composition in a single turn; and ReWOO/LLMCompiler decouple planning from execution via symbolic placeholders and parallel DAGs to slash latency and token costs.
The Closed-Loop Agent Formalism
A single forward pass is open-loop: once tokens are emitted, the model cannot inspect intermediate results or recover from an invalid assumption. An autonomous agent converts inference into a closed-loop control system interacting with an environment over discrete steps.
At step , the agent maintains an interaction history and samples an action from policy :
This simple while loop introduces two fundamental systems tensions that every control-flow pattern tries to optimize:
- Compounding Error Probability: If each step has independent success probability , the probability of completing a -step trajectory without unrecovered error decays exponentially as . Without verification and recovery, long-horizon reliability collapses.
- Quadratic Token & Latency Scaling: Re-sending a growing history at every turn causes total prefill tokens across a -step trajectory to scale as , while sequential round-trips sum every LLM inference latency and tool execution time.
ReAct: Interleaved Reasoning and Acting
Before ReAct (Yao et al., 2022), two baselines dominated multi-step tasks, each failing in a complementary way:
- Chain-of-Thought (Reasoning-Only): Generates internal rationales without environment queries, leading to fact hallucination and error propagation when world state changes or facts are absent from parametric weights.
- Act-Only Policies: Emit raw actions directly from observations without intermediate scratchpad tokens, losing track of subgoals, failing to synthesize observations across turns, and repeating invalid calls.
ReAct resolves this by augmenting the agent’s action space , where is the set of external environment/API actions and is the space of unconstrained natural-language thoughts (Thought):
- Thoughts () leave the external state unchanged () while updating the agent’s working context—decomposing goals, extracting facts from noisy observations, tracking progress, and formulating fallback plans on error.
- Actions () ground reasoning in real environment feedback ().
Thought 1: I need to find the latency SLA of service-A before checking its error logs.
Action 1: search_docs(query="service-A latency SLA")
Obs 1: service-A p99 SLA is 250ms; owner team is Core-Infra.
Thought 2: Now query metrics for service-A over the last hour to check p99 violations.
Action 2: query_metrics(service="service-A", metric="p99_latency", window="1h")
Obs 2: p99_latency=410ms (threshold exceeded at 14:20 UTC).
Thought 3: SLA is violated; I have enough evidence to summarize the incident.
Action 3: finish("service-A violated its 250ms p99 SLA at 14:20 UTC (410ms).")
Failure Modes of Naive ReAct
While ReAct remains the canonical single-agent baseline, production deployments quickly hit three failure modes:
- Context Window Poisoning: Verbose tool observations (HTML pages, stack traces, large JSON payloads) accumulate in , distracting attention heads and inflating cost.
- Action Loops: When a tool repeatedly returns an ambiguous error, the model often retries near-identical arguments until hitting
max_steps. - Sequential Bottleneck: Every single sub-operation requires a full autoregressive LLM round-trip, even when multiple queries are completely independent.
Self-Correction Loops: Reflexion vs. CRITIC
To overcome the compounding error trap, agents need structured mechanisms to detect mistakes and revise behavior. Two foundational patterns illustrate the critical difference between cross-episode verbal RL and in-episode tool verification.
Reflexion: Episodic Verbal Reinforcement Learning
Reflexion (Shinn et al., 2023) improves an agent across sequential trials without updating model weights . It wraps a standard ReAct/CoT loop in three distinct roles:
- Actor (): Generates a full trajectory conditioned on the task and episodic reflection memory .
- Evaluator (): Assigns a scalar or binary reward using an external oracle (unit tests, compiler exit code, exact match) or heuristic scorer.
- Self-Reflection (): When indicates failure, analyzes and compresses the root cause and concrete corrective rule into a short natural-language summary stored in bounded episodic memory .
On trial , the Actor conditions on —avoiding the exact mistake made in trial —effectively performing gradient-free policy improvement in text space.
The Intrinsic Self-Correction Caveat: Empirical studies (Huang et al., 2023) demonstrate that asking an LLM to “double-check and critique your own answer” without external feedback often degrades accuracy—models flip correct answers to wrong ones due to sycophancy or confirmation bias. Reflexion works reliably only when provides grounded external verification (such as failing unit tests or environment assertions).
CRITIC: Tool-Interactive Verification Within a Single Episode
Rather than waiting for an entire episode to fail before reflecting, CRITIC (Gou et al., 2024) performs in-episode, tool-grounded verification. Given an initial candidate output :
- The model invokes external verification tools—such as a Python interpreter to check math, a linter/type-checker to validate code, or a search API to fact-check claims.
- Tool execution returns deterministic feedback .
- The model conditions on to produce a corrected output , iterating until verification passes.
Reflexion vs. CRITIC: Reflexion learns between full task attempts using episodic memory of trajectory failures; CRITIC repairs a draft inside the current attempt using immediate external tool checks. In production coding agents, the two compose naturally: CRITIC runs pytest/linters per edit, while Reflexion summarizes broader architectural dead-ends across retries.
CodeAct: Unifying the Action Space into Executable Code
Standard JSON tool calling forces an agent to act through rigid, pre-declared single-turn schemas. Consider a simple data task: “Find all users in users.csv who signed up in 2026, group by plan tier, and compute the median session duration.”
With discrete JSON tools:
- Turn 1 calls
read_csvserializes 5,000 rows into LLM context tokens. - Turn 2 asks the LLM to filter rows in its head (error-prone and expensive) or call
filter_rows, thengroup_by, thenmedian—requiring 4–5 sequential LLM round-trips and passing raw intermediate data through the prompt at every boundary.
CodeAct (Wang et al., 2024) replaces JSON action schemas with executable Python code inside an isolated sandbox (such as a stateful Jupyter kernel or Docker microVM):
import pandas as pd
df = pd.read_csv("users.csv")
df_2026 = df[df["signup_year"] == 2026]
summary = df_2026.groupby("plan_tier")["session_duration_sec"].median()
print(summary.to_dict())
Why CodeAct Outperforms JSON Calling on Complex Workflows
- Native Control Flow in One Turn: Loops (
for,while), conditionals (if/else), recursion, andtry/excepterror handling run deterministically at CPU speed inside a single LLM turn instead of burning LLM round-trips. - Data-Plane vs. Control-Plane Separation: Large intermediate variables (
df, API responses, AST trees) stay in Python heap memory. Only conciseprint()summaries enter the LLM context window—drastically shrinking token usage. - Composable Tool Libraries: Any Python package or MCP tool exposed as a Python helper function can be imported, chained, and composed cleanly using standard programming syntax heavily represented in LLM pretraining corpora.
- In-Loop Self-Debugging: Stack traces (
KeyError,TypeError,AssertionError) provide crisp, exact feedback that CodeAct models immediately patch in the next turn.
Engineering Trade-Offs of CodeAct
- Mandatory Sandboxing: Arbitrary code execution requires strict OS/hypervisor isolation (Docker with dropped capabilities, gVisor, or Firecracker microVMs), CPU/RAM cgroup limits, execution timeouts, and restricted network egress.
- Not Ideal for Simple Single-Shot Mutations: For a UI agent clicking one button or calling a single strict CRM endpoint with human-in-the-loop approval, declarative JSON tool schemas remain easier to audit and policy-gate before execution.
Decoupling Planning from Execution: ReWOO & LLMCompiler
In ReAct, if a user asks “Compare the Q3 revenue of Nvidia, AMD, and Intel and compute the average,” a naive ReAct agent runs 3 sequential Thought → Action → Obs cycles—paying sequential LLM calls plus sequential network latencies. Two architectures break this sequential bottleneck by decoupling planning from execution.
ReWOO: Reasoning Without Observation
ReWOO (Xu et al., 2023) eliminates interleaved observation calls during planning through three modules:
- Planner: Given only the user query and tool specs, emits the entire multi-step plan upfront using symbolic variable placeholders (
#E1,#E2,#E3) to wire dependencies:Plan 1: Search Q3 revenue for Nvidia#E1 = Search[Nvidia Q3 revenue]Plan 2: Search Q3 revenue for AMD#E2 = Search[AMD Q3 revenue]Plan 3: Search Q3 revenue for Intel#E3 = Search[Intel Q3 revenue]Plan 4: Compute average#E4 = Calculator[(#E1 + #E2 + #E3) / 3]
- Worker: Executes each tool call, substituting resolved values into downstream
#Eplaceholders once dependencies complete. - Solver: Receives the full plan plus all resolved evidence
#E1..#E4in a single final LLM call to synthesize the answer.
- Benefit: Cuts LLM calls down to just 2 (Planner + Solver) regardless of how many tools are invoked, eliminating quadratic prompt re-transmission.
- Limitation: ReWOO is open-loop during execution—if
#E1returns an unexpected format or requires conditional branching based on search results, the static plan cannot adapt mid-flight.
LLMCompiler: Parallel DAG Execution with Adaptive Re-Planning
LLMCompiler (Kim et al., 2024) brings classic compiler instruction-level parallelism to agent tool calls while retaining ReAct’s ability to re-plan:
- Function Calling Planner: Streams a Directed Acyclic Graph (DAG) of tasks with explicit
$1,$2dependency edges. - Task Fetching Unit: Eagerly dispatches any task as soon as its upstream parent dependencies finish—achieving parallel fan-out across independent branches without waiting for unrelated tools.
- Joiner: Inspects the completed DAG outputs. If the task is solved, it synthesizes the final response; if a tool failed or observations revealed missing information, the Joiner triggers a re-plan cycle back to the Planner.
If task takes execution time , sequential ReAct latency is governed by the sum of all steps plus LLM planner calls:
Whereas LLMCompiler reduces wall-clock latency to the critical path of the DAG plus minimal planner/joiner passes:
Comparative Summary of Control-Flow Patterns
| Pattern | LLM Calls per Tools | Parallel Tool Execution | Grounding / Error Recovery | Cumulative Uncached Prefill | Best-Fit Workload |
|---|---|---|---|---|---|
| ReAct | (sequential) | No (unless multi-tool batching) | Dynamic per-step adjustment | Exploratory search, unpredictable branching | |
| Reflexion | across trials | No | Cross-episode episodic memory + oracle | Bounded per trial | Coding benchmarks, tasks with unit-test oracles |
| CRITIC | verification rounds | No | In-episode external tool check | Linear in revisions | Math, code linting, fact-checked generation |
| CodeAct | – (multi-op per turn) | Yes (via async/threads in Python) | Sandbox stack traces & assertions | Low (state stays in heap) | Data analysis, file manipulation, multi-step scripts |
| ReWOO | (Planner + Solver) | Yes (independent #E branches) |
Static (fails on unexpected branching) | Predictable multi-hop lookup + synthesis | |
| LLMCompiler | – (+ re-plan if needed) | Yes (eager DAG scheduler) | Dynamic Joiner re-planning | High-throughput parallel retrieval & aggregation |