Agent Architectures: ReAct, Planning and Loops
What actually makes a system an agent
The word agent is applied loosely enough to have lost most of its meaning, so it helps to name the minimum bar. An agent is a loop: a model observes some state, decides on an action, executes it against the world, reads the result, and decides again â with a goal that persists across those iterations. A chatbot that answers once has no loop, no memory of consequences, and no way to discover that its first plan was wrong.
Three capabilities separate real agents from prompt chains. Feedback: the result of an action changes what the model sees next, so errors can be corrected mid-flight. Persistence: the goal survives across steps even as the working context is rewritten. Tool access: actions reach beyond text generation into APIs, databases, and files. Remove any one and you have a pipeline with extra steps, which is often the right choice â agents earn their complexity only when the path to the goal cannot be predicted in advance.
The loop, component by component
Every agent framework is a variation on the same four functions. Writing them out plainly keeps the machinery legible.
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any
@dataclass
class Step:
thought: str
action: str | None = None
action_input: dict = field(default_factory=dict)
observation: str | None = None
done: bool = False
class Agent(ABC):
def __init__(self, llm, tools: dict, memory, max_steps: int = 8):
self.llm = llm
self.tools = tools
self.memory = memory
self.max_steps = max_steps
def perceive(self) -> str:
"""Assemble current state: goal, history, last observation."""
return self.memory.render()
@abstractmethod
def think(self, state: str) -> Step:
...
def act(self, step: Step) -> str:
if step.action is None:
return ""
tool = self.tools.get(step.action)
if tool is None:
return f"Unknown tool: {step.action}"
try:
return str(tool(**step.action_input))
except Exception as exc:
return f"Tool error: {exc}"
def run(self, goal: str) -> str:
self.memory.set_goal(goal)
for _ in range(self.max_steps):
step = self.think(self.perceive())
if step.done:
return step.thought
step.observation = self.act(step)
self.memory.append(step)
return self.memory.final_answer() or "Stopped: max steps reached"
Two details carry most of the reliability. The unknown-tool and exception paths return strings instead of raising, because a model that can read its own error message can correct course, while an exception that kills the loop cannot. And max_steps is mandatory: an unbounded loop is a cost incident waiting to happen.
ReAct: thought and action interleaved
ReAct is the default agent pattern, and for good reason: it writes reasoning and observations into one shared transcript so each step is conditioned on everything learned so far.
import re
REACT_TEMPLATE = """Answer the question using the tools available.
Question: {question}
{history}
Produce exactly one block in this format:
Thought: what you should do next
Action: tool name, or FINISH
Action Input: JSON object, or the final answer if FINISH
"""
class ReActAgent(Agent):
PATTERN = re.compile(
r"Thought:\s*(?P<thought>.*?)\s*"
r"Action:\s*(?P<action>[\w-]+)\s*"
r"Action Input:\s*(?P<input>.*)",
re.S,
)
def think(self, state: str) -> Step:
raw = self.llm.generate(REACT_TEMPLATE.format(question=self.memory.goal,
history=state))
match = self.PATTERN.search(raw)
if not match or match.group("action").upper() == "FINISH":
return Step(thought=raw.strip(), done=True)
try:
payload = json.loads(match.group("input"))
except json.JSONDecodeError:
payload = {"raw": match.group("input")}
return Step(thought=match.group("thought"),
action=match.group("action"),
action_input=payload)
The failure mode to watch is the model narrating a plan without emitting a parseable action. Keep the parser tolerant, feed parse failures back as observations, and log every unparseable step â that rate is the clearest signal that your prompt or model needs attention.
Plan-and-execute for longer horizons
ReAct re-plans constantly, which is cheap for short tasks and wasteful for long ones. Plan-and-execute spends one expensive call producing a step list, then runs cheap execution calls against it, re-planning only when something goes off the rails.
class Planner:
def __init__(self, llm):
self.llm = llm
def make_plan(self, goal: str) -> list:
raw = self.llm.generate(
f"Break this goal into 3 to 7 ordered steps as a JSON array "
f"of short strings.\nGoal: {goal}"
)
try:
steps = json.loads(raw)
except json.JSONDecodeError:
steps = [goal]
return steps if isinstance(steps, list) else [goal]
class PlanExecuteAgent(Agent):
def run(self, goal: str) -> str:
plan = Planner(self.llm).make_plan(goal)
results = []
for index, step in enumerate(plan, start=1):
state = f"Overall goal: {goal}\nStep {index}: {step}\nPrior: {results}"
outcome = self.llm.generate(state)
results.append(f"Step {index}: {outcome}")
if self.something_failed(outcome) and self.should_replan():
plan = self.replan(goal, results)
return self.llm.generate(f"Summarise final result: {results}")
def something_failed(self, outcome: str) -> bool:
return "ERROR" in outcome or "failed" in outcome.lower()
def should_replan(self) -> bool:
self._replans = getattr(self, "_replans", 0) + 1
return self._replans < 3
Bounded replanning is the important line. Replanning on every failure produces oscillation, where the agent abandons a nearly finished plan because one step hiccuped; three attempts before declaring defeat is a workable compromise.
Memory beyond the context window
Working memory is the transcript the loop renders each turn, and it saturates quickly once tool output enters the picture. Two supporting stores fix that. Short-term memory is a bounded summary: keep the goal, the last few steps verbatim, and a compressed digest of everything older. Long-term memory is external â a vector store or a set of files â written explicitly when the agent learns something worth keeping and read back by relevance when a new task looks similar.
The design mistake to avoid is letting raw tool output accumulate. A single 40 KB HTML page from a web tool can evict the goal statement from the window, and the agent will cheerfully continue on a truncated objective. Summarise at the boundary where observations enter memory, not somewhere later in the prompt.
What belongs in an observation
The observation is the interface between the world and the model's next decision, and most agent failures can be traced to something lost or duplicated at that boundary. A useful observation is short, structured, and written for the next step rather than for the human reading the log.
Four properties separate a good observation from a bad one. Completeness: it carries every field the next decision needs, including identifiers that would otherwise have to be re-fetched. Boundedness: it is truncated to a stated budget, with the truncation announced inside the text so the model knows more exists. Actionability: failures are described in terms of what to try differently, not as raw tracebacks. Provenance: it names the tool and arguments that produced it, which lets the model reason about staleness when two sources disagree.
def render_observation(tool_name, args, result, budget=1500):
body = result if isinstance(result, str) else json.dumps(result, default=str)
truncated = len(body) > budget
if truncated:
body = body[:budget] + f"\n[truncated, {len(body) - budget} chars omitted]"
return (
f"Observation from {tool_name}({json.dumps(args, default=str)}):\n"
f"{body}\n"
f"{'More data exists; ask for another page if needed.' if truncated else 'Complete.'}"
)
An agent that receives honest, bounded observations corrects itself. One that receives a wall of HTML does not â it simply re-reads the same wall until the step limit saves you from the bill.
Measuring an agent in production
Agent metrics differ from chatbot metrics because the unit of work is a task, not a message. Task success rate is the headline: the fraction of goals completed without human intervention. Steps-to-success tells you whether the loop is efficient or wandering. Cost per completed task is the number finance actually asks about, and it is the product of step count, tokens per step, and price â so a small prompt optimisation often beats a clever tool change.
Watch the abandonment paths too. The rate at which runs hit the step cap, the rate of tool errors, and the rate of parse failures each point at a different layer of the system.
| Metric | Healthy signal | Warning signal | First fix |
|---|---|---|---|
| Task success | rising or stable | falling after a model change | replay failed traces |
| Steps to success | flat | climbing over versions | tighten tool descriptions |
| Cap hits | under 5 percent | over 15 percent | check prompts and schemas |
| Tool error rate | under 2 percent | any sustained spike | return actionable errors |
Evaluate offline before you trust any of this in production: keep a fixed set of tasks with known solutions, run it on every prompt or model change, and treat a success-rate drop as a release blocker.
Choosing an architecture
| Pattern | Horizon | Cost profile | Replans | Use when |
|---|---|---|---|---|
| Single call | 1 step | Lowest | n/a | Task is fully specified up front |
| Chain with tools | 2 to 4 steps | Low | Never | Order of operations is known |
| ReAct | 3 to 10 steps | High per step | Every step | Path depends on observations |
| Plan-and-execute | 5 to 30 steps | High once, then low | On failure | Steps are predictable in advance |
| Multi-agent | Long, parallel | Highest | Per sub-agent | Tasks split cleanly by domain |
A useful discipline: start from the bottom of this table and move down only when a concrete failure forces it. Most production "agent" requests are satisfied by a chain of two or three tool calls with deterministic branching, and that version ships weeks earlier.
Common Mistakes
Running the loop with no step limit
Fix: Set max steps and a token budget; alert when either is hit, because it means the agent is stuck.
Letting raw tool output flood the context
Fix: Summarise observations as they enter memory so the goal and recent steps are never evicted.
Building a ReAct agent for a task with a fixed order of operations
Fix: Use a deterministic chain; agents pay for flexibility you will not use.
Swallowing tool exceptions
Fix: Return the error text as an observation so the model can adapt instead of silently looping.
Best Practices
- Log every step â thought, action, input, observation â because post-mortems without traces are guesswork.
- Make tool schemas explicit and descriptions unambiguous; most bad actions start as a misunderstood parameter.
- Give the agent a FINISH path and reward short successful trajectories over exhaustive exploration.
- Evaluate agents on task success rate and steps-to-solution together, so speed and reliability are both visible.
Key Takeaways
- An agent is a loop with feedback, persistent goals, and tool access; without those it is a prompt chain.
- ReAct interleaves reasoning and observation in one transcript, which suits tasks whose path depends on results.
- Plan-and-execute front-loads reasoning and re-plans only on failure, which is cheaper over long horizons.
- Bounded steps, bounded replans, and summarised observations are what keep agents from burning budget in circles.
- Add architectural complexity only when a concrete failure requires it; most tasks want a plain tool chain.