🎯 By the end of this module, you will:
The Agentic Loop: How Systems Adapt to Reality
In traditional programming, code follows a rigid script from line 1 to line 100 without pausing to re-evaluate whether reality changed. If step 2 throws an unexpected error, the entire program crashes.
An Agentic Loop runs an ongoing cycle: after every action, it pauses to Observe the real outcome. If a database query fails or a file is missing, the Reasoner pivots and attempts an alternate strategy.
Decides all 5 steps in advance. If step 2 encounters a locked table or schema mismatch, steps 3, 4, and 5 fail catastrophically. Zero runtime awareness.
Observes the board, calculates candidate moves, executes ONE move, and waits to observe how the opponent responds before calculating the next turn.
"Never allow an agent to assume its action succeeded! The Observation phase must always catch the real output from the operating system or API. If a file edit returned an error, that exact error string must become part of the agent's perception for the next turn!"
The 4 Operational Phases
Select a phase to inspect its code pattern and runtime responsibilities:
Evaluates missing information, formulates an internal plan, and selects the optimal tool call.
# Phase 2: Cognitive evaluation pass
thought = llm.generate_thought(context)
action = llm.decide_tool_call(context, thought)
# Output: {"tool": "fetch_stock_quote", "args": {"ticker": "AAPL"}}"A home thermostat senses current temperature (Perceive), compares it to 72°F (Reason), fires the furnace (Act), checks the thermometer again 5 minutes later (Observe), and turns off when the target is reached (Terminate)!"
The 4 Critical Stopping Conditions
Every autonomous loop must have ironclad exit conditions to prevent infinite loops, runaway API bills, and thread deadlock:
The agent evaluates observations and confirms all subtasks are resolved. Emits final synthesized answer to user and terminates.
A hard limit on cycle count (e.g. `max_iterations = 10`). Prevents the agent from endlessly cycling if a task is unsolvable.
Monitors cumulative tokens or dollar spend across cycles. If budget exceeds $0.50 or 50k tokens, halts and asks user for approval.
When tools report missing credentials, 401 unauthorized errors, or critical policy halts, the agent cleanly yields to a human operator.
"Every autonomous loop must have a guaranteed termination bound. Never ship a `while True:` loop in production agentic software. Always enforce `while step < max_iterations:`!"
Interactive 5-Phase Agentic Loop Simulator
Perceive ➔ Reason ➔ Act ➔ Observe ➔ Iterate: See how autonomous intelligence cycles until completion
Phase 1: Perception
Ingest current environment state, interaction history, user inputs, and available tools.
Cycle 1 • Perceive: Ingest User Request
PerceptionAgent receives user goal: 'Calculate 18% GST tax on 140,000 INR and generate customer receipt PDF.'
[Perception Input]: Prompt: "Calculate 18% GST on 140,000 INR and generate customer receipt PDF" Available Tools: [calculate_gst, generate_pdf_invoice] History: None (Initial Turn)
Agentic Loop Engine WorkbenchPython 3.11
Configure stopping boundaries, test flaky tool self-healing, and trigger safety limits
# Production Agentic Loop Engine in Python
class AutonomousAgent:
def __init__(self, tools: dict, max_iterations: int = 5):
self.tools = tools
self.max_iterations = max_iterations
self.state = {
"history": [],
"current_step": 0,
"is_complete": False,
"final_answer": None
}
def run(self, goal: str) -> str:
self.state["history"].append({"role": "user", "content": goal})
# Core Loop: Continues until termination condition or safety ceiling
while not self.state["is_complete"] and self.state["current_step"] < self.max_iterations:
self.state["current_step"] += 1
step = self.state["current_step"]
# Phase 1: PERCEIVE
context = self.perceive(self.state["history"])
# Phase 2: REASON
thought, action_plan = self.reason(context)
# Phase 3: ACT
raw_result = self.act(action_plan)
# Phase 4: OBSERVE
observation = self.observe(raw_result)
self.state["history"].append({"role": "tool", "content": observation})
# Phase 5: ITERATE (Exit Condition Check)
if self.is_goal_achieved(observation):
self.state["is_complete"] = True
self.state["final_answer"] = self.synthesize_response()
break
# Safety Gate: Triggered if max_iterations exceeded without completion
if not self.state["is_complete"]:
raise TimeoutError(f"Loop exceeded safety threshold of {self.max_iterations} iterations.")
return self.state["final_answer"]"In long multi-cycle loops, observations accumulate rapidly. If an agent calls search tools 8 times, the context window will balloon and slow down inference. Always truncate or summarize intermediate observations older than 3 cycles!"
When a tool returns a 404 Not Found error, a naive agent will repeatedly call the exact same tool with the exact same arguments indefinitely.
Fix: Implement duplicate action detection. If the agent repeats an action identically, inject a prompt constraint warning it to pivot.
Skipping the observation step and assuming that firing an API call means the state was successfully modified in the database.
Fix: Always require a verified return code or database select query before confirming task resolution to the user.
Summary Checklist
Module 1.7: Common Agentic Design Patterns
Master the architectural patterns: Prompt Chaining, Routing, Parallelization, Orchestrator-Workers, and Evaluator-Optimizer.