Library

Volume 2 · Agentic AI Systems

Notebook
Sign in

Section 26

Agent Foundations (ReAct, Plan-and-Execute, Tree of Thoughts, Reflexion)

1,110 words · about 5 min

26.1 What is an AI Agent?

An AI agent is an autonomous system that uses an LLM as its reasoning engine to perceive its environment, make decisions, and take actions toward a goal. Unlike a simple chatbot, an agent can:

  • Plan — break a complex goal into sub-tasks
  • Act — execute tools, APIs, and functions
  • Observe — interpret the results of its actions
  • Reflect — evaluate progress and adjust strategy
  • Remember — maintain context across interactions and sessions

26.2 The Agentic AI Spectrum

Not every AI system needs to be “agentic.” Understanding where a solution sits on this spectrum is the first architectural decision:

Simple Chatbot ──── RAG Assistant ──── Tool-Using Agent ──── Multi-Agent System ──── Autonomous System
     │                    │                   │                      │                       │
  Static Q&A         Grounded Q&A       Can take actions      Collaborating agents    Self-improving
  No memory          No actions          Single task focus     Complex workflows       Minimal human
  No tools           Retrieval only      Human approval        Orchestration            oversight

26.3 Agent vs. Workflow — The Key Architectural Distinction

Aspect Workflow (Deterministic) Agent (Autonomous)
Control flow Pre-defined DAG LLM decides next step
Flexibility Fixed paths Adapts to inputs
Predictability High Variable
Complexity handling Simple branching Complex reasoning
Debugging Easy (trace the DAG) Hard (LLM reasoning is opaque)
When to use Well-understood, repeatable processes Novel or ambiguous problems

Production reality: Most enterprise “agentic” systems are hybrid — structured workflows with agentic decision points embedded at specific nodes. Pure, fully autonomous agents are too unpredictable for most enterprise use cases. The architectural skill is identifying the 20% of decision points that genuinely benefit from LLM reasoning and keeping the other 80% deterministic.

26.4 The Core Agent Loop

Regardless of framework, nearly every agent implements some variant of a Reason → Act → Observe loop:

                    ┌──────────────────┐
                    │   User Goal /    │
                    │   Trigger Event  │
                    └────────┬─────────┘
                             │
                    ┌────────▼─────────┐
            ┌──────│     REASON        │◀─────────┐
            │      │  (LLM Planning)   │          │
            │      └────────┬──────────┘          │
            │               │                      │
            │      ┌────────▼──────────┐          │
            │      │      ACT          │          │
            │      │  (Tool Execution) │          │
            │      └────────┬──────────┘          │
            │               │                      │
            │      ┌────────▼──────────┐          │
            │      │     OBSERVE       │──────────┘
            │      │  (Parse Results)  │
            │      └────────┬──────────┘
            │               │
            │      ┌────────▼──────────┐
            └─────▶│   GOAL MET?       │
                   │  Yes → Respond    │
                   │  No  → Loop       │
                   └───────────────────┘

26.5 ReAct (Reasoning + Acting) — Most Common in Production

Interleaves explicit reasoning traces with actions: Thought → Action → Observation → Thought → … This is the dominant pattern in production frameworks (LangChain, LangGraph, LlamaIndex) because the reasoning trace is auditable — you can see why the agent chose an action.

Worked example — customer/case investigation:

User: "Claim/Order #78901 was flagged. Investigate and recommend next steps."

THOUGHT: I need to look up the record to understand why it was flagged.
ACTION: lookup_record(id="78901")
OBSERVATION: Record #78901 — Status: Flagged, Reason Code: CO-4
             (procedure/line item inconsistent with modifier)

THOUGHT: The flag concerns a modifier/attribute mismatch. Let me check the
supporting documentation.
ACTION: get_supporting_document(id="ENC-45678")
OBSERVATION: Document confirms a distinct qualifying condition that
supports the missing modifier.

THOUGHT: The documentation supports the correction. Historical resolution
rate for this exact pattern is high — I should check.
ACTION: check_resolution_success_rate(reason_code="CO-4", correction="modifier_25")
OBSERVATION: Historical success rate for this pattern: 78%.

THOUGHT: High confidence. Draft the correction/appeal for human review.
ACTION: draft_correction(id="78901", argument="modifier_supported")

RESPONSE: Record #78901 was flagged for a missing modifier. Documentation
supports the correction, with a 78% historical success rate for this exact
pattern. I've drafted the correction for your review.

26.6 Plan-and-Execute — Better for Complex Multi-Step Tasks

Step 1: CREATE PLAN
  Given the goal, produce a complete, numbered list of steps.

Step 2: EXECUTE EACH STEP
  For each step:
    - Execute the step
    - Evaluate the result
    - If the step fails or produces unexpected output → re-plan remaining steps

Step 3: SYNTHESIZE
  Combine all step results into a final answer.

When to use: tasks with 5+ steps, where step ordering matters, where partial-failure recovery is required, and for complex research/analysis/audit tasks that span multiple systems.

26.7 Tree of Thoughts (ToT) — For Ambiguous Problems

Explore multiple reasoning paths in parallel, score each branch using a heuristic or reflection model, and prune unpromising branches. Best suited when multiple candidate root causes exist and committing prematurely to one path leads to compounding errors.

flowchart TD
    Problem["Problem Statement / Root Cause Triage"]

    Problem --> A["Approach A: Network Latency"]
    Problem --> B["Approach B: DB Connection Saturation"]
    Problem --> C["Approach C: Memory Leak / GC Pause"]

    A --> A1["A1: Check VPC Flow Logs\n(Dead End)"]
    A --> A2["A2: Check NAT Gateway Metrics\n(Score: 8.5/10 - Packet Drops Detected)"]

    B --> B1["B1: Check Slow Query Logs\n(Score: 3.0/10 - Normal)"]
    C --> C1["C1: Inspect JVM Heap\n(Score: 5.0/10 - Stable)"]

    A2 --> Decision["Selected Best Path: Pursue A2\n(Mitigate NAT Gateway Port Exhaustion)"]

26.8 Reflexion — Self-Improving Agents

The agent evaluates its own execution results against expected criteria, generates natural-language self-critiques upon failure, and persists that critique into memory so successive attempts avoid repeat mistakes.

flowchart TD
    subgraph Attempt1["Iteration 1 (Failure)"]
        T1["Execute Task via Tool Actions"] --> E1{"Evaluate Output"}
        E1 -->|Mismatch / Error| R1["Self-Reflection:\n'I assumed schema was v2 without checking;\nnext time query metadata endpoint first.'"]
        R1 --> Mem[("Episodic Memory / Scratchpad")]
    end

    subgraph Attempt2["Iteration 2 (Success)"]
        Mem --> Prompt["Augment Context with Memory Reflection"]
        Prompt --> T2["Execute Task with Lesson Applied\n(Calls metadata first)"]
        T2 --> E2{"Evaluate Output"}
        E2 -->|Success| Out["Final Validated Result"]
    end

Section 26 — Interview Q&A

Q1: When would you choose Plan-and-Execute over ReAct?

A: ReAct is reactive and lightweight—ideal for open-ended, exploratory tasks where the next action is heavily conditional on the prior observation (e.g., ad-hoc triage, tool discovery). Plan-and-Execute front-loads an explicit multi-step plan, which excels when:

  • The task contains 5+ deterministic stages whose dependencies are known up front.
  • A human-in-the-loop requires review and approval of the plan prior to execution.
  • Sub-tasks are independent and can be executed concurrently. In production, enterprise architectures frequently combine both: Plan-and-Execute at the macro workflow level, with ReAct powering individual step execution.

Q2: How do you decide how many reasoning frameworks to support in a single platform?

A: Standardize on one default—typically ReAct, because its step-by-step traces are the simplest to audit and debug. Escalate to Plan-and-Execute or Tree of Thoughts only for domain-specific workloads with proven justification (e.g., complex compliance audits or multi-hypothesis triage). Supporting too many reasoning engines introduces unnecessary testing and observability overhead.

Q3: What is the architectural risk of “pure” autonomous agents in an enterprise setting, and how do you mitigate it?

A: Unbounded agents operating across open action spaces exhibit non-deterministic behaviors that resist auditing and introduce severe security risks. Production mitigations include:

  • Enforcing strict tool allowlists with fine-grained RBAC.
  • Constraining agentic loops inside deterministic workflow DAGs (e.g., using LangGraph or Temporal).
  • Mandating human-in-the-loop approvals before any state-mutating or write operations are dispatched.