Course
AI · Module 06: Tool Calling, MCP & AI AgentsTutorial 18 of 21
AI Course·~1.5 hrs

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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:

1. WORKFLOWS (CODE OWNS CONTROL FLOW)Chaining · Routing · Parallel Fan-Out · Evaluator-LoopPredictable cost, latency & 99% debuggable!✓ Use for 85% of structured business features2. AUTONOMOUS AGENTS (LLM OWNS LOOP)while not done: Reason → Act (Tool) → ObserveHandles open-ended coding & research!⚠️ Requires max_steps, budget & approval gates
Figure: Start with the simplest deterministic workflow that solves the problem; graduate to open-ended Agent loops only when step count cannot be known upfront.
  • Workflows (Deterministic Code Owns the Control Flow): Use when you already know the stages upfront:
    1. Prompt Chaining: Draft SQL → Validate syntax in Postgres → Format chart config.
    2. Routing: Classify ticket → Dispatch to specialized Billing, Auth, or Bug pipeline.
    3. Parallelization (Sectioning / Voting): Run Security Review, Style Review, and Perf Review concurrently via asyncio.gather.
    4. Evaluator–Optimizer: Generator drafts code → Deterministic pytest runs → Optimizer fixes failing assertions (capped at 3 iterations).
  • Autonomous Agents (The LLM Owns the while Loop): 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:

PYTHON
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:

Interactive Agent Loop & Circuit-Breaker Simulator
Toggle Loop Guardrails ON vs OFF to see why production `while` loops require step, budget & duplicate-call breakers
Loop Iterations
3 turns
Request Cost
$0.0042 ✓
Exit Condition
Circuit Breaker tripped: identical tool_call + args repeated 2×!
Turn 1 → fetch_crm('cust_404') → HTTP 503 Upstream Down
Turn 2 → fetch_crm('cust_404') → HTTP 503 Upstream Down
🛑 GUARDRAIL TRIPPED: Duplicate (tool, args) hash detected! Returned graceful fallback to user.

4. The 5 Non-Negotiable Guardrails Every Production Agent Needs

  1. Hard max_steps Cap (e.g., 6–12 turns): Never write while True:. On step == max_steps - 1, strip tools=[] and ask the model to summarize its best findings so far gracefully!
  2. Cumulative Token / Dollar Budget (max_cost_usd = 0.10): Track running input_tokens + output_tokens across loop turns and abort immediately if a turn exceeds budget.
  3. 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 arguments 2× in a row, inject a system warning ("You already called X with those exact arguments; try a different approach or conclude") or break!
  4. 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.
  5. Action Tiering (Read = Auto · Write = Scoped · Destructive/External = Human Approval): Pause the loop and emit an approval_required UI state before executing delete_*, send_email, or refund_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!):

Tracing Context Isolation in an Orchestrator–Worker Architecture
Interactive LLM Pipeline Tracer · Step 1 of 3 (1. Single-Agent Context Bloat Problem)
1→plan = await orchestrator("Audit auth, billing, and search modules")
2# Spawn 3 isolated workers in parallel — each has a FRESH context window!
3summaries = await asyncio.gather(*[run_worker(task) for task in plan.tasks])
4# Orchestrator receives 3 crisp 150-token summaries (450 tok vs 60,000 tok!)
5report = await orchestrator_synthesize(summaries)
Why One Monolithic Agent Degrades on Large AuditsCONTEXT POLLUTION
Reading 15 files sequentially stuffs 60,000 raw code tokens into 1 context window -> Lost-in-the-Middle errors + 15 sequential waits!
What's Happening: Sub-agents aren't about cute 'personas' (PM, QA, CEO) — their real engineering superpower is **Context Window Isolation + Parallel Wall-Clock Execution**!

6. Production Code: Framework-Free Guarded Agent Loop in 40 Lines

SDK:
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)

  1. "Roleplay Multi-Agent Theater" (PM Agent talking to Dev Agent talking to QA Agent): Giving 4 agents cute job titles that chat back-and-forth in prose burns 20× 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).
  2. Hard Cutoff Returning an Empty Crash on step == max_steps: Simply raising an exception at step 8 throws away 7 turns of valuable work and shows the user a 500 error! On max_steps - 1, pass tools=[] and prompt: "Tool budget reached — provide the clearest answer possible using the evidence gathered so far."
  3. Destructive Actions Without Dry-Run / Human Confirmation: An agent asked to "Clean up stale staging branches" misinterprets release-2026 as stale and runs git push origin --delete! Gate destructive tools behind explicit user confirmation.

Module 6.3 Mastery Check — Agentic Workflows & Guardrails

Q1.When should you choose a deterministic Workflow (Chaining / Routing / Parallelization) OVER an open-ended autonomous ReAct Agent loop?
Q2.What is the REAL architectural reason senior engineers spawn isolated Sub-Worker agents in coding/research systems?
Q3.Why should your agent loop pass `tools=[]` (or `tool_choice='none'`) on the final allowed iteration (`step == max_steps - 1`) instead of raising an exception?
Q4.What specific failure mode does hashing `(tool_name, sorted_json_args)` inside an agent loop prevent?

Keep Exploring: Related Lessons & Tools

All Courses →