The Agentic AI Codex
Ch 08 · AI Agents — Core Patterns
Chapter 08 · The agent loop

AI Agents — the seven patterns

An agent is not a chatbot with a fancy prompt. It is a loop with five components: a goal, an LLM acting as controller, a set of tools, a memory, and a stopping condition. Master those and the rest is taste.

8.1 · Definition (the one we keep using)

Agent
A software entity that pursues a goal by repeatedly choosing actions (often tool calls) from a policy produced by an LLM, while maintaining state and stopping when the goal is reached or a budget is exhausted.

8.2 · Anatomy — five organs

Goal

What the user wants. Sometimes given, sometimes inferred.

Controller (LLM)

The brain that decides each action.

Tools

Functions, APIs, retrievers, code execution, file I/O.

Memory

Short-term (the running conversation) and long-term (vector store, files).

Policy

The prompt + framework that turns the LLM into an actor.

Stop condition

Done-signal, step cap, token cap, cost cap, time cap.

8.3 · The canonical agent loop

Goal→ Observe state→ Think (LLM)→ Act (tool)→ Update memory→ Done?

This loop is the entire agentic stack reduced to one diagram. Frameworks differ in how they orchestrate it, not in what it is.

8.4 · The seven design patterns — with examples

1 · Router

Pick one specialist per request

Definition. The LLM reads the user message and outputs a single label that decides which downstream agent / tool / prompt handles it.

Example. Customer support — a router classifies incoming messages as billing, technical, or sales, then dispatches to the right specialist.

2 · ReAct

Think → Act → Observe → repeat

Definition. The agent alternates reasoning and tool-calls in a visible trace until it reaches an answer.

Example. "Convert $250 to PKR" → think "need rate" → call currency.get → observe 281.4 → think → call calc → answer Rs 70,350.

3 · Plan-and-Execute

Strategy first, then tactics

Definition. A planner LLM writes a numbered checklist; an executor (possibly with its own ReAct loop) runs the steps.

Example. "Write a market-research report" → plan: (1) define segments (2) gather sources (3) summarise (4) draft. Each step then ran in turn.

4 · Reflection

Draft, critique, revise

Definition. After producing a draft, the agent grades its own output against an explicit rubric and rewrites the weakest parts.

Example. A coding agent writes a function, runs tests, sees a failure, reads the error, rewrites the function — without leaving the loop.

5 · Tool-use with retries

Recover from tool failures

Definition. When a tool returns an error or unexpected schema, the agent reads the error message and retries with corrected arguments — bounded by a retry budget.

Example. Calendar tool returns "invalid_date" → agent reformats "next Tuesday" to "2026-05-19" → retry succeeds.

6 · Hierarchical / Supervisor

One boss, many specialists

Definition. A supervisor agent orchestrates a team of specialist sub-agents, each with its own tools and prompt.

Example. Claude Code spawns scoped sub-agents (Explore, Plan, Review) that work in isolation and report back, so the main context stays clean.

7 · Self-Ask / Decomposition

Break hard questions into easy ones

Definition. The agent splits a multi-hop question into sub-questions, answers each (often using a tool), then composes the final answer.

Example. "Was the founder of the company that bought GitHub born in the US?" → sub-Qs: who bought GitHub? → who founded that company? → where were they born?

8.5 · ReAct — the foundational pattern

Thought:  I need today's exchange rate to answer.
Action:   currency.get(pair="USD/PKR")
Observation: 1 USD = 281.4 PKR
Thought:  Now I can convert $250 → 250 * 281.4
Action:   calc(expr="250 * 281.4")
Observation: 70350
Thought:  I have the answer.
Final:    $250 ≈ Rs 70,350 at today's rate.

Three properties make ReAct dominant:

  • Interpretable — every trace is a story you can read.
  • Composable — add a tool, the agent uses it.
  • Recoverable — observations let the model correct itself.

8.6 · Plan-and-Execute

Separate strategy from tactics. A "planner" LLM writes a checklist; an "executor" works through each item, perhaps using its own ReAct loop.

Plan:
  1. Find the latest sales figures for Q4 2025
  2. Compare against forecast in /docs/forecast.pdf
  3. Draft a 1-page memo highlighting deltas > 5%
Then execute step by step.

Why this helps: planning is cheap, execution is where errors cluster. Reviewing a plan once is far cheaper than recovering from twelve bad sub-actions.

8.7 · Reflection

After producing a draft, the model critiques itself against an explicit rubric, then revises. Use sparingly — two rounds of reflection saturate the gain on most tasks.

Draft: ...
Critique:
  - Section 2 misses the cost analysis required by the rubric.
  - Tone in section 3 is too informal.
Revise accordingly. Return only the revised draft.

8.8 · Levels of autonomy revisited

LevelPatternHuman checkpoint
L1 Co-pilotSuggestions, completionsEvery keystroke
L2 AssistantReAct on a single taskPer task
L3 AgentPlan-and-ExecutePer artefact / plan
L4 WorkerSelf-reflecting loops, scheduled runsPer day / per metric
L5 OrganisationMulti-agent teams (Ch 12)Audits, alerts

8.9 · The five agent failure modes

  1. Loops — the agent calls the same tool forever. Cap steps; add a "no-progress" detector.
  2. Tool misuse — wrong arguments, wrong format. Validate tool inputs.
  3. Hallucinated tools — agent invents a function that doesn't exist. Constrain the tool registry.
  4. Context overflow — running memory blows past the window. Summarise, truncate, paginate.
  5. Confident wrong answers — looks valid, isn't. Add evaluators and ground-truth checks.

8.10 · How to test an agent

  • Trace-level tests — record golden traces and replay; assert which tools were called.
  • End-to-end evals — for each task, score with an LLM-as-judge against a rubric.
  • Adversarial prompts — try to make the agent leak its system prompt or skip tools.
  • Cost/latency budgets — fail the test if a run exceeds N tokens or M seconds.
  • Drift checks — run the same eval each week; alarm when scores drop.
A simple production rule
Never deploy an agent to production until you have (a) 20 frozen tasks, (b) a scoring rubric, and (c) a way to re-run them after every prompt change.

8.11 · Self-check

Q1 · What separates an "agent" from a chatbot?
Better prompts
A loop of tool calls toward a goal
Streaming responses
A larger model
Q2 · A user reports the agent is making 80 tool calls before answering. Most likely cause?
The model is too small
A planning / no-progress loop bug
Cold cache
Temperature is too low