Pathubs Logo Mark
PATHUBSFREE CAREER ROADMAPS
HomeExploreDiscoverCompare ⚖️My Progress 📊Support
Student Support & Feedback

Have Questions or Need Help?

Have questions, feedback, or suggestions for new roadmaps and interactive tools? Reach out to our team — we review every message to make practical learning better for everyone.

supportpathubs@gmail.com
Pathubs

Pathubs is an interactive learning platform that combines structured career roadmaps, topic-by-topic learning, and hands-on practice — 100% free with no paywalls.

Popular Careers

  • Frontend Development
  • Backend Development
  • AI & LLM Engineering
  • Full Stack Web Dev
  • Data Analytics

Platform Tools

  • Career Discovery Quiz
  • Compare Careers

Contact & Info

  • About Us
  • supportpathubs@gmail.com
  • Support Pathubs

© 2026 Pathubs. All Rights Reserved. Structured learning, practical content, and hands-on practice for learners worldwide.

AboutPrivacy PolicyTerms & ConditionsSitemapRobots
Home/AI Engineering/AI Agents & Agentic Architectures
MODERN AI STACK AUTONOMOUS SYSTEMS

AI Agents & Agentic Architectures

Master the architecture of autonomous LLM decision loops. Move beyond single-turn prompt-response patterns into stateful systems that plan, invoke tools, observe environment ground truth, recover from failures, respect hard stopping limits, and operate within strict human-in-the-loop guardrails.

Estimated Time: 75 mins
Level: Advanced AI Engineering
Track: Generative AI & Systems
Mode: Textbook & Interactive Workbench

Curriculum Outline

• 1. Mental Model: What is an AI Agent?• 2. Deterministic Workflows vs. Agents• 3. Anatomy of an Agent (9 Subsystems)• 4. The Agent Loop (Interactive Tool 1)• 5. Planning & Replanning (Interactive Tool 2)• 6. State vs. Context (Interactive Tool 3)• 7. Environment Ground Truth & Tools• 8. Stopping Limits (Interactive Tool 4)• 9. Human-in-the-Loop (Interactive Tool 5)• 10. Guardrails & Security (Interactive Tool 6)• 11. Error Recovery & Self-Healing• 12. Observability & Tracing Telemetry• 13. Cost & Latency (Interactive Tool 7)• 14. Model Context Protocol (MCP)• 15. Capstone Learning Agent (Tool 8)• 16. Production Incident Debugging Lab• 17. What You Should Know Now• 18. Knowledge Assessment Quiz
01

What is an AI Agent? The Core Mental Model

De-hyping autonomous systems: why an agent is not simply "an LLM connected to tools."

In modern AI Engineering, an AI Agent is an autonomous computational system where a foundation model (LLM) is embedded in a continuous decision loop. Rather than generating a single static response to a user prompt, the agent receives a goal, formulates subsequent actions, invokes external tools, observes empirical results from the environment, updates its internal state, and decides what to do next until its objective is completed or an explicit stopping limit is reached.

Architectural Evolution: LLM vs. Tool Calling vs. Autonomous Agent
1. Standard LLM (Single-Turn)
Input → Model → Static Output

Static generation. Closed-world knowledge cut-off. Cannot interact with external systems or query live databases.

2. Tool Calling (Single Decision)
Input → Model → Tool → Result → Response

Linear invocation. The model or developer triggers 1 tool, reads the result once, and terminates execution.

3. Autonomous Agent (Model-Directed Loop)
Goal → [Decide → Act → Observe → Update State]↺ → Finish

Dynamic multi-turn loop. Subsequent actions adapt autonomously depending on intermediate observations.

The Defining Characteristic

An agent is not simply "an LLM + 10 tools". The defining trait of an agent is the model-directed control flow: the model inspects intermediate results and decides whether to try a different query, call a secondary tool, ask the user for clarification, or conclude the run.

02

Workflows vs. Autonomous Agents

The critical engineering rule: use the simplest architecture that reliably solves the problem.

One of the costliest mistakes engineering teams make is deploying an unpredictable autonomous agent when a deterministic workflow would achieve 100% reliability with lower latency and 1/10th of the token costs.

Architectural DimensionDeterministic WorkflowAutonomous AI Agent
Control FlowDefined by code (if / else, DAG pipelines).Dynamically driven by the model at runtime.
Execution PathPredictable and repeatable for identical inputs.Exploratory; may take 2 steps or 8 steps depending on observations.
Latency & CostLow & bounded (fixed number of LLM invocations).Variable & higher (scales with iteration depth and retries).
Failure ModesEasy to pinpoint; step 3 failed due to specific schema error.Complex trajectory drift, hallucinated tools, or infinite loops.
Best Used ForInvoice processing, data extraction, fixed customer support flows.Open-ended research, multi-system root-cause triage, complex coding.

The 5 Key Agentic Workflow Patterns (Anthropic Taxonomy)

Before reaching for an autonomous loop, production AI engineers evaluate five structured workflow patterns:

1. Prompt Chaining

Decompose task into fixed sequential steps: Step 1 generates outline → Step 2 drafts body → Step 3 verifies citations.

2. Routing

A lightweight classifier model categorizes user intent and directs traffic to specialized prompts or tools.

3. Parallelization

Sectioning tasks concurrently (e.g. summarizing 5 documents simultaneously) and aggregating results.

4. Orchestrator-Workers

A central coordinator model breaks down tasks and delegates discrete subtasks to worker models.

5. Evaluator-Optimizer

One model generates code/content while an independent evaluator critiques it until quality thresholds are satisfied.

03

Anatomy of an AI Agent: The 9 Core Subsystems

The essential modular building blocks required to build a resilient, production-ready agent.

1. Foundation Model (The Decider)

The reasoning engine (e.g. Claude 3.7 Sonnet, GPT-4o, Gemini 2.0 Flash) capable of multi-step planning, strict schema generation, and understanding structured tool calls.

2. System Instructions (The Constitution)

The immutable persona, behavioral boundaries, tool usage policies, response formatting guidelines, and safety guardrails provided in the system prompt.

3. Tool Registry (The Capabilities)

Callable functions with well-defined JSON Schemas, parameter types, and descriptions (e.g., calculator, SQL query executor, vector search API).

4. State & Context Manager

Tracks the active task status, accumulated observations, pending subtasks, error counters, and intermediate artifacts across iterations.

5. Loop Orchestrator (The Driver)

The backend code that manages the execution cycle: prompts the model, parses tool invocations, runs tools, updates state, and checks termination criteria.

6. Guardrails & Safety Filters

Input/output validators that prevent prompt injections, redact PII, restrict tool permissions, and enforce resource boundaries.

7. Human-in-the-Loop (HITL) Gate

Pauses execution and solicits explicit human approval before triggering consequential, destructive, or costly actions.

8. Observability & Tracing System

Structured telemetry logging Run IDs, step latencies, token consumption, tool inputs/outputs, and decision summaries.

9. Evaluation Harness

Test suites measuring task completion rate, trajectory efficiency, unnecessary tool call counts, and safety compliance.

04

The Agent Execution Loop (The Core Runtime)

Deconstructing the 8 sequential phases executed by an autonomous runtime on every iteration.

At the heart of every agent is a cyclic engine: Goal Ingestion → Context Evaluation → Decision → Tool Execution → Observation → State Update → Stopping Check → Synthesis. Experiment with the interactive simulator below to see how state transitions unfold at each phase.

Interactive Tool 1: The Core Agent Loop Visualizer
Interactive Simulator

Step through the internal phases of an autonomous agent execution loop. Type your own custom goal or select a realistic scenario preset.

Test Scenarios:
Step 1
Goal Ingestion
Step 2
Context & State Evaluation
Step 3
Decision & Tool Selection
Step 4
Environment Execution
Step 5
Ground Truth Observation
Step 6
State Update & Reflection
Step 7
Stopping Condition Check
Step 8
Final Output Synthesis
Current Phase 1 of 8: Goal IngestionState: In Progress

Receive high-level user goal into memory.

Target Goal Context: "Find why API latency spiked after v2.4 deployment"
05

Planning, Explicit Decomposition & Dynamic Replanning

How agents handle real-world surprises when empirical observations contradict initial hypotheses.

In AI agent architectures, planning occurs in three primary styles:

A. Implicit Planning

The model chooses the next tool call ad-hoc on every turn without generating an upfront multi-step plan. Fast, but prone to wandering on long-horizon tasks.

B. Explicit Planning

The system forces the model to generate a structured step-by-step checklist (Plan-and-Solve) before executing the first tool. Provides clear visibility and accountability.

C. Dynamic Replanning

When a tool returns unexpected observations (e.g. 404, missing files, server crash), the agent mutates its original plan to take alternate investigative branches.

Interactive Tool 2: Dynamic Replanning Simulator
Replanning Engine

Simulate an environmental failure during agent investigation and observe how the agent updates its execution plan.

Simulate Environment Surprise (HTTP 403 on Metrics API):
Initial Plan (Before Tool Run)
  1. Query metrics endpoint for latency by route.
  2. Identify slow endpoint (e.g. /api/checkout).
  3. Inspect slow endpoint database queries.
  4. Recommend SQL index optimization.
Mutated Plan (After HTTP 403 Observation)
  1. Query metrics endpoint (Blocked: 403 Forbidden).
  2. Pivot: Fallback to reading raw NGINX access logs from disk.
  3. Compute P99 response time from raw log timestamps.
  4. Inspect recent deployment git commit diffs.
06

State & Context Management: State ≠ Conversation History

Why dumping 50 raw tool messages into the prompt fails, and how structured state solves context fatigue.

In a naive agent implementation, developers simply append every raw tool output to a chat messages array. At step 8, the context window contains 100,000 tokens of raw HTML, huge JSON arrays, and redundant outputs. This causes context fatigue, needle-in-a-haystack amnesia, and massive API costs.

Interactive Tool 3: Agent State & Working Memory Inspector
Live State Engine

Inspect the evolving JSON state schema of an active agent run. Inject custom observations to see how state adapts.

{
  "run_id": "agent_run_8f92b4",
  "iteration": 2,
  "status": "IN_PROGRESS",
  "goal": "Ingest customer refund request and verify authorization",
  "active_hypothesis": "Checking refund balance threshold",
  "completed_actions": [
    {
      "step": 1,
      "tool": "verify_jwt",
      "status": "SUCCESS"
    },
    {
      "step": 2,
      "tool": "check_account_balance",
      "status": "SUCCESS"
    }
  ],
  "working_memory": {
    "user_id": "usr_882",
    "account_balance": 450,
    "risk_score": 0.12,
    "injected_observation": "Auth token valid; balance: $450.00; risk score: low"
  },
  "error_count": 0,
  "token_usage": {
    "input": 2480,
    "output": 620,
    "total": 3100
  }
}
07

Environment Ground Truth & Tool Execution

Binding LLMs to reality: how tool outputs serve as grounded empirical facts for subsequent reasoning.

Foundation models are probabilistic text predictors. Without grounding, they hallucinate plausible-sounding falsehoods. Tools serve as the bridge to external reality. When an agent queries a SQL database, scrapes a webpage, or invokes a bash script, the resulting stdout or JSON is an indisputable ground truth observation.

Tool Schemas as Immutable Contracts

Tools must always be registered with strict parameter schemas (JSON Schema, Zod, or Pydantic). Never allow arbitrary string inputs when typed enums or bounded numeric ranges can prevent hallucinated parameters before runtime dispatch.

TypeScript • Strict Tool Definition
export const queryDatabaseTool = {
  name: "query_database",
  description: "Execute a read-only SELECT query against the analytics PostgreSQL replica.",
  parameters: {
    type: "object",
    properties: {
      sql: { type: "string", description: "Standard PostgreSQL SELECT query" },
      limit: { type: "integer", minimum: 1, maximum: 50, default: 20 }
    },
    required: ["sql"]
  }
};
08

Stopping Conditions: Preventing Infinite Loops

Hard programmatic safeguards required to prevent recursive financial and computational exhaustion.

An autonomous agent must never be allowed to run indefinitely. If an external service is down or an instruction is slightly ambiguous, the LLM will happily re-query and retry until your cloud account hits credit limits.

Interactive Tool 4: Agent Loop Safeguards & Limits Lab
Safety Sandbox

Configure maximum iteration thresholds and observe how the runtime halts runaway execution before budget depletion.

Executed Loops: 0 / 4
09

Human-in-the-Loop (HITL) Approval Gates

Tiered risk policies that pause autonomous execution before irreversible operations take effect.

The agent should never be the final authority for sensitive actions. Production systems categorize tools into risk tiers and enforce approval gates before high-risk execution.

Interactive Tool 5: Human Approval & Risk Policy Simulator
Governance Engine

Act as the Human Gatekeeper. Approve or reject proposed agent actions based on risk classifications.

Proposed Action Pending ApprovalRisk Level: LOW
calculate_discount(order_id="ord_99")
Description: Deterministic read-only calculation
Recent Decision Log:
search_knowledge_base("latency")[AUTO_EXECUTED]
10

Agent Guardrails & Defense-in-Depth

Protecting systems against prompt injections, unauthorized tool calls, and credential leakage.

Agentic systems introduce severe security attack surfaces that static LLM apps do not have. An attacker can use Indirect Prompt Injection: embedding malicious instructions inside a customer email or webpage that the agent reads via a search tool.

Interactive Tool 6: Agent Security Shield & Guardrail Simulator
Security Firewall

Test custom adversarial payloads against 3 active guardrail layers to verify automated interception.

1. Input GuardrailActive

Filters prompt injections, jailbreaks, and unauthorized privilege escalation directives.

STATUS: BLOCKED (Suspicious SQL)
2. Tool GuardrailActive

Validates argument bounds, enforces least-privilege tokens, and checks schema sanity.

STATUS: ENFORCING SCHEMA
3. Output GuardrailActive

Scans outgoing responses to prevent leaking internal database schemas, API keys, or raw PII.

STATUS: REDACTING SECRETS
11

Error Recovery & Self-Healing Trajectories

Building resilient agents that gracefully handle unexpected API drops, invalid schemas, and network retries.

Unlike static code where an unhandled exception terminates the process, an autonomous agent can self-correct. When a tool fails (e.g. database connection refused or invalid parameters), the runtime captures the error and feeds it straight back to the model as an observation.

Never Mask Tool Errors as Generic Nulls

If a tool returns nullon failure, the LLM assumes there was no data. Always return the precise runtime error string (e.g. "Table 'users_temp' does not exist. Available tables: [users, orders]"). This allows the model to inspect its mistake and self-heal on the very next turn.

12

Observability, Telemetry & Tracing

Why traditional APM tools fail for stochastic agents, and how OpenTelemetry traces capture multi-step reasoning.

Traditional software observability tracks HTTP status codes and CPU load. For stochastic AI agents, you need Trajectory-Level Observability: tracing the full chain of thought, tool arguments, raw return payloads, token expenditures per step, and confidence metrics across multi-turn sessions.

Telemetry PrimitiveData TrackedDiagnostic Purpose
Run ID / Trace IDUUID assigned at initial user request.Correlates all subsequent sub-calls, tool invocations, and retries.
Span LatencyMilliseconds spent inside LLM vs. external tool network I/O.Discovers performance bottlenecks (e.g. slow Postgres query vs slow model).
Cumulative TokensPrompt tokens + completion tokens consumed per iteration.Prevents budget overruns and identifies runaway context inflation.
Trajectory EvalsSuccess flag, step count, redundant tool invocation count.Measures whether the agent solved the problem through the most optimal path.
13

Agent Cost & Latency Economics

Understanding the compounding multi-step token expense of agentic architectures.

A single standard LLM query costs 1 API request and ~1,000 tokens. In contrast, an autonomous agent making 6 iterations accumulates prompt tokens repeatedly: step 1 prompt is resent in step 2, step 3, etc. This creates a compounding quadratic token curve unless prompt caching and observation pruning are applied.

Interactive Tool 7: Agent Cost & Latency Economics Calculator
ROI Analyzer

Tweak LLM call counts, token volumes, and tool latencies to analyze compounding resource economics.

Total Tokens Consumed
10,750
vs. ~1,500 tokens for single-turn Q&A
Estimated API Cost
$0.0400
At $2.50/1M input & $10/1M output
Total Wall-Clock Latency
5.00s
Model generation + synchronous tool overhead
14

Model Context Protocol (MCP) & 2026 Frameworks

The standardized "USB-C for AI" protocol connecting models, tools, and external datasets.

Announced by Anthropic in late 2024 and widely standardized by 2026, the Model Context Protocol (MCP) replaces fragmented, custom tool integrations with an open standard based on JSON-RPC 2.0.

Model Context Protocol (MCP) Architecture
MCP Host (Client Application)

The user-facing application (e.g. Claude Desktop, Cursor, Next.js server) that initiates sessions and enforces permissions.

Transport Layer

Communicates via Stdio (local subprocesses) or HTTP with Server-Sent Events (SSE) for remote services.

MCP Server

Exposes three core primitives: Tools (executable actions), Resources (passive read data), and Prompts (templates).

2026 Agent Framework Landscape (Comparative Breakdown)

FrameworkPrimary Orchestration StyleKey StrengthsIdeal Use Case
OpenAI Agents SDKAgent handoffs, function tools, sessions.Production guardrails, built-in tracing, native sandbox execution.Enterprise multi-agent support workflows with strict compliance.
Hugging Face smolagentsCodeAgent (writes Python code) & ToolCallingAgent.Extremely lightweight (~1,000 lines), Hub integration, sandbox safety.Code-as-action research, data analysis, open-source LLMs.
LangGraphStateful graph-based DAG with cycles.Fine-grained state transitions, persistence, time-travel debugging.Complex enterprise workflows mixing deterministic steps and agent loops.
Google Agent Development KitMulti-modal tool calling & Gemini thinking models.Native multi-modal input processing (audio, video, text), Vertex integration.Real-time voice agents and multi-modal document reasoning.
15

Capstone Mini-Project: "Pathubs Learning Agent"

Run a complete, safe autonomous agent that inspects real curriculum data and outputs a tailored learning roadmap.

Capstone Tool 8: Pathubs Autonomous Learning Agent
Live Runtime Workbench

The agent interacts with synthetic Pathubs tools (get_roadmap, search_courses, calculate_learning_hours) to formulate advice without hallucinating curriculum content.

Quick Scenarios:
16

Production Incident Debugging Lab

Triage 5 realistic failure modes encountered when deploying autonomous agents into enterprise production.

Runaway Infinite Loop & Budget ExhaustionLoop Control / Stopping Condition

Symptom: Agent incurred $240 in OpenAI API charges on a single user query by repeatedly calling search_docs("metrics") 84 times in 3 minutes.

Observed Failure Trace:
[Turn 82] Tool Call: search_docs(query="metrics") -> Output: "Found 0 matches" [Turn 83] Thought: "I need to find the metrics docs. Let me search again." [Turn 83] Tool Call: search_docs(query="metrics") -> Output: "Found 0 matches" [Turn 84] Thought: "Searching again..."
Diagnostic Hint

Look at the while loop condition in the agent runner. Is there any check on max iterations or duplicate actions?

17

What You Should Know Now (Competency Checklist)

Verify your technical fluency in autonomous agent architectures before advancing.

The Core Agent Mental Model

You understand that an agent is a continuous loop of Goal → Decide → Act → Observe → Update State → Done? where subsequent actions dynamically adapt based on empirical environment ground truth.

Workflows vs. Agents Tradeoff

You know when to choose a deterministic workflow (Prompt Chaining, Routing, Orchestrator-Workers) for 100% predictability versus an autonomous agent for open-ended exploration.

Stopping Conditions & Loop Safeguards

You know never to allow infinite loops; every production runtime must enforce iteration limits, tool ceilings, wall-clock timeouts, and token budgets.

Human-in-the-Loop & Defense-in-Depth

You know how to gate consequential actions (financial transfers, database mutations) with approval modals, and how to protect against Indirect Prompt Injection via layered guardrails.

Model Context Protocol (MCP)

You understand the client-host-server architecture of MCP and the distinct roles of Tools (doing), Resources (reading), and Prompts (guiding).

18

Knowledge Assessment Quiz

Test your understanding of agent loops, state management, guardrails, and production safeguards.

Question 1 of 8Score: 0

What is the fundamental architectural distinction between an LLM Workflow and an Autonomous AI Agent?

← Previous TopicVector DatabasesNext Phase (Phase 07) →REST APIs for AI Applications