6.3 Agentic Workflows, ReAct Loops & Production Guardrails
Know when NOT to build an autonomous agent! Master the 5 foundational agentic patterns, write a clean framework-free ReAct agent loop in 35 lines of Python, and prevent $500 runaway loops with circuit breakers.
1. The Most Valuable Rule in Agent Engineering: Workflows vs. Agents
Every week, teams wrap a simple 3-step business pipeline inside a heavy multi-agent framework — turning a reliable 800 ms feature into an unpredictable 14-second mystery box that fails 15% of the time!
Following Anthropic's Building Effective Agents taxonomy, draw a razor-sharp line between Workflows and Autonomous Agents:
- Workflows (Deterministic Code Owns the Control Flow): Use when you already know the stages upfront:
- Prompt Chaining: Draft SQL → Validate syntax in Postgres → Format chart config.
- Routing: Classify ticket → Dispatch to specialized Billing, Auth, or Bug pipeline.
- Parallelization (Sectioning / Voting): Run Security Review, Style Review, and Perf Review concurrently via
asyncio.gather. - Evaluator–Optimizer: Generator drafts code → Deterministic
pytestruns → Optimizer fixes failing assertions (capped at3iterations).
- Autonomous Agents (The LLM Owns the
whileLoop): Reserve strictly for open-ended problems where the sequence and number of steps cannot be predicted upfront (e.g., debugging an unfamiliar repository bug across unknown files, or multi-source investigative research)!
2. What an "AI Agent" Actually Is in Code (Zero Magic!)
Strip away every buzzword and framework logo — an autonomous ReAct (Reason + Act) Agent is literally a while loop around Tool Calling:
for step in range(MAX_STEPS):
resp = call_llm(messages, tools)
if not resp.has_tool_calls:
return resp.final_text # Done!
results = execute_tools_with_guardrails(resp.tool_calls)
messages.extend(results)
raise MaxStepsExceededError("Halted safely at step budget!")
That's it! Writing that 10-line loop directly on official SDKs gives you 100% visibility into every prompt, token count, retry, and error — without fighting opaque framework abstractions when debugging production traces!
3. Hands-On Lab: Test Agent Circuit Breakers Against Runaway Loops
Select Infinite Retry Loop Bug! below and toggle Guardrails: ENABLED vs DISABLED to see how a single upstream 503 error turns into a $14.80 disaster without a duplicate-call circuit breaker:
4. The 5 Non-Negotiable Guardrails Every Production Agent Needs
- Hard
max_stepsCap (e.g., 6–12turns): Never writewhile True:. Onstep == max_steps - 1, striptools=[]and ask the model to summarize its best findings so far gracefully! - Cumulative Token / Dollar Budget (
max_cost_usd = 0.10): Track runninginput_tokens+output_tokensacross loop turns and abort immediately if a turn exceeds budget. - Duplicate
(tool_name, canonical_args)Circuit Breaker: Hash(name, json.dumps(args, sort_keys=True)). If the model calls the exact same tool with the exact same arguments2×in a row, inject a system warning ("You already called X with those exact arguments; try a different approach or conclude") or break! - Observation Compaction / Scratchpad Pruning: If Step 2 read a 300-line file, don't re-send all 300 raw lines across Steps 3..12! Summarize or prune stale tool outputs once consumed.
- Action Tiering (Read = Auto · Write = Scoped · Destructive/External = Human Approval): Pause the loop and emit an
approval_requiredUI state before executingdelete_*,send_email, orrefund_charge.
5. Wire-Level Trace: Orchestrator–Workers Pattern for Complex Tasks
When a single agent's context gets polluted by reading 15 files, split into an Orchestrator (plans subtasks) + isolated Sub-Workers (each runs in a fresh clean context window and returns only a 150-word summary!):
Reading 15 files sequentially stuffs 60,000 raw code tokens into 1 context window -> Lost-in-the-Middle errors + 15 sequential waits!
6. Production Code: Framework-Free Guarded Agent Loop in 40 Lines
import hashlib, json
from openai import OpenAI
client = OpenAI()
def run_guarded_agent(goal: str, tools: list[dict], dispatch: dict, max_steps: int = 6) -> str:
items: list[dict] = [{"role": "user", "content": goal}]
seen_calls: dict[str, int] = {}
total_tokens = 0
for step in range(max_steps):
# On final step, remove tools so the model MUST synthesize a graceful wrap-up!
active_tools = tools if step < max_steps - 1 else []
resp = client.responses.create(model="gpt-4o-mini", input=items, tools=active_tools)
total_tokens += resp.usage.total_tokens
if total_tokens > 40_000:
raise RuntimeError("Token budget breaker tripped (40k tokens)!")
items += resp.output
fn_calls = [o for o in resp.output if o.type == "function_call"]
if not fn_calls:
return resp.output_text
for call in fn_calls:
sig = hashlib.sha256(f"{call.name}:{call.arguments}".encode()).hexdigest()[:16]
seen_calls[sig] = seen_calls.get(sig, 0) + 1
if seen_calls[sig] > 2:
out = "CircuitBreaker: Duplicate tool call blocked. Synthesize final answer now."
else:
out = json.dumps(dispatch[call.name](**json.loads(call.arguments)))
items.append({"type": "function_call_output", "call_id": call.call_id, "output": out})
return "Max steps reached."7. What Breaks in Production (War Stories)
- "Roleplay Multi-Agent Theater" (
PM Agenttalking toDev Agenttalking toQA Agent): Giving 4 agents cute job titles that chat back-and-forth in prose burns20×the tokens while playing a game of telephone! Only spawn sub-agents for parallel speed or context isolation (keeping noisy 30k-token file reads out of the main coordinator). - Hard Cutoff Returning an Empty Crash on
step == max_steps: Simply raising an exception atstep 8throws away 7 turns of valuable work and shows the user a500error! Onmax_steps - 1, passtools=[]and prompt: "Tool budget reached — provide the clearest answer possible using the evidence gathered so far." - Destructive Actions Without Dry-Run / Human Confirmation: An agent asked to "Clean up stale staging branches" misinterprets
release-2026as stale and runsgit push origin --delete! Gate destructive tools behind explicit user confirmation.
Module 6.3 Mastery Check — Agentic Workflows & Guardrails
Keep Exploring: Related Lessons & Tools
All Courses →Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.