Core Concepts

AI Agent Architecture

A comprehensive guide to how modern AI agents are built — covering the perception-reasoning-action loop, short-term and long-term memory, RAG with vector databases, planning frameworks, tool integration, and multi-agent coordination.

Memory RAG Planning Tool Calling Multi-Agent

Contents

High-Level Overview

AI Agent Architecture Diagram

Hover over any component to learn what it does

👤
USER / TASK INPUT
Goal · Question · Event · API trigger
The starting point — a natural language goal, question, task, or event from a user, API, or another agent.
👁️
Perception Layer
Text · Images · Audio · Files · Tool results → tokenized context
Ingests all input modalities — text, images, audio, PDF files, and raw tool outputs — and converts them into tokens the LLM can process.
⚡ Context Window — Short-Term Memory
📋
System Prompt
Identity, rules, tools
The agent's persona, behavioral rules, tool schemas, and constraints. Set once and persists across the entire session.
🔍
RAG Retrievals
Top-k vector chunks
The most semantically relevant document chunks retrieved from the vector database for the current query. Injected fresh every turn.
💬
Chat History
Recent turns
The sliding window of recent conversation turns. Older messages are summarized or dropped as the context fills toward the token limit.
🔧
Tool Outputs
Observations
Results returned by tool calls in the current loop iteration — search snippets, code output, database rows — fed back as observations.
🧠
LLM — REASONING BRAIN
ReAct · CoT · Reflection · Plan-and-Execute · Tree of Thought
Gemini · GPT-4o · Claude · Llama
The large language model that reads the full context window and decides the next action. Applies planning patterns like ReAct (Thought→Action→Observation), Chain-of-Thought, and Reflection to reason step-by-step.
🗺️ Planning
Decompose goal into sub-tasks · Schedule execution order · Handle failures & replanning
The agent's planning layer converts a high-level goal into an ordered sequence of actions. Can re-plan dynamically if a step fails or returns unexpected results.
✏️ Memory Write
Store facts, observations & episode results to long-term memory for future retrieval
After each significant step, the agent writes key facts and observations to long-term vector storage so they can be retrieved in future sessions.
🔧 Tool Integration Layer (MCP / OpenAPI)
🌐
Web Search
Real-time web search via Tavily, Serper, or Brave API. Grounds responses in current information beyond the training cutoff.
💻
Code Exec
Execute Python, JavaScript, or shell code in a secure E2B Firecracker MicroVM or Pyodide (WASM) sandbox.
🗄️
Database
Query SQL, NoSQL, or vector databases. Read structured records, update state, or write new data.
📁
Files
Read and write files: PDFs, CSVs, JSON, code files, images, and documents from local or cloud storage.
🔗
APIs
Call external REST or GraphQL APIs — Stripe, Slack, GitHub, Salesforce, and any custom internal services.
🤖
Sub-Agent
Delegate to a specialized sub-agent as a tool call — the orchestration pattern for multi-agent systems.
↺ Loop back to
context window
if task continues
👁
Observe & Decide
Task complete? → Return answer
Need more steps? → Loop again
The agent evaluates whether the current output satisfies the original goal. If yes, it returns the final answer. If not, the tool result becomes a new observation and the loop continues.
→ Final answer
returned to user
when goal is met
FINAL OUTPUT
Answer · Report · Code · Action taken · Data written
The completed result — a natural language answer, generated code, report, structured data, or a side-effect action (email sent, record updated, file created).
🗄️ Long-Term Memory
📚 Semantic
Docs, FAQs, facts
Stores general factual knowledge as vector embeddings. Retrieved via semantic similarity search (RAG).
🕰️ Episodic
Past sessions
Records of prior conversations and action-result sequences the agent can learn from.
⚙️ Procedural
Saved workflows
Proven step sequences and successful plans stored for reuse on similar future tasks.
👤 User/Entity
Preferences, facts
Persistent, structured facts about specific users or entities — preferences, history, tier. Enables cross-session personalization.
Qdrant · Pinecone
pgvector · Mem0
🛡️ Safety & Guardrails
Input/output checks · Sandbox · HITL approval
Guardrails inspect every LLM input and output for jailbreaks, PII, and policy violations. High-stakes actions require Human-in-the-Loop approval before execution.
🔭 Observability
Traces · Logs · Eval · Token usage
Every step of the agentic loop is traced via OpenTelemetry. Platforms like LangSmith and Arize provide dashboards to debug, evaluate, and monitor agents in production.

1 What Is an AI Agent?

An AI Agent is an autonomous system that perceives its environment, reasons about its goals, takes actions — including calling external tools — and iterates until a task is complete. Unlike a simple chatbot that responds to a single prompt, an agent can execute multi-step workflows across dozens of actions with minimal human intervention.

At its core, an agent combines four primitive capabilities:

🧠
Reasoning
LLM-powered logic that interprets context and decides the next action
🗄️
Memory
Layered storage from in-context buffers to persistent vector databases
🔧
Tool Use
APIs, code execution, web search, databases, and external services
🎯
Planning
Decomposing high-level goals into sequences of executable sub-tasks

Key distinction: An LLM generates text. An AI agent acts — it uses tool calls, reads results, updates its state, and loops until the goal is achieved or a stopping condition is met.

Evolution of AI Systems
💬
Chatbot
Single-turn Q&A, no memory, no tools
↓ adds tool calling
🤖
LLM + Tools
Can search or write code, but single-pass
↓ adds looping + memory
AI Agent
Iterative loop, persistent memory, multi-step planning
↓ adds collaboration
🕸️
Multi-Agent System
Orchestrated agents with specialized roles

2 The Perception-Reasoning-Action Loop

The agentic loop is the heartbeat of every AI agent. It repeats until the task is complete or a stopping condition is met.

P
Perceive
The agent receives input: user messages, tool output, file content, API responses, sensor data, or environment state. This forms the raw context that the LLM will reason about.
R
Reason
The LLM processes the context window — system prompt, conversation history, retrieved memories, and current observations — to determine the next best action. This is where CoT, planning, and reflection happen.
A
Act
The agent executes an action: calling a tool, writing to memory, sending a message, generating text, or calling another agent. The result becomes the next observation.
O
Observe
The output of the action is fed back into the context. The agent evaluates whether the goal is achieved or another loop iteration is needed.
The Agentic Loop — Pseudocode
# Simplified agent execution loop
def run_agent(task, max_steps=20):
    memory = AgentMemory()
    context = build_context(task, memory)

    for step in range(max_steps):

        # REASON: LLM picks next action
        response = llm.complete(context)

        if response.is_final_answer:
            return response.output

        # ACT: Execute tool call
        tool_result = execute_tool(
            response.tool_name,
            response.tool_args
        )

        # OBSERVE: Feed result back
        context = update_context(
            context, tool_result
        )
        memory.store(step, tool_result)

    return "Max steps reached"

3 Short-Term Memory

Short-term memory is the agent's active working context — everything present in the LLM's context window during the current task execution. It is the fastest and most accessible form of memory but is strictly bounded by the model's token limit.

What lives in the context window?

📋
System Prompt
The agent's identity, capabilities, rules, tool schemas, and behavioral constraints. Persists for the entire session.
💬
Conversation History
Recent user messages and agent responses. Older turns get truncated as the context fills — a sliding window keeps only the most recent exchanges.
🔍
Retrieved Memories (RAG Chunks)
Semantically-relevant documents retrieved from long-term vector storage and injected into the prompt for the current turn.
🔧
Tool Outputs (Observations)
Results from tool calls in the current loop — e.g., search snippets, code execution results, database records.

Context Window Constraint: Models have fixed context window sizes (e.g., 128K–2M tokens). As the context fills, older content must be selectively dropped or summarized. This is why long-term external memory is critical for extended tasks.

Context Window Anatomy
System Prompt
Agent persona, tool schemas, rules
~500–2000 tokens
RAG Retrievals
Top-k chunks from vector DB
~1000–8000 tokens
Conversation History
Recent turns (sliding window)
~2000–20000 tokens
Tool Outputs
Observations from current loop
~500–5000 tokens per call
Current Task State
Plan, progress, next action
~200–1000 tokens

4 Long-Term Memory

Long-term memory is persistent storage outside the context window that the agent can selectively read from and write to. This enables agents to recall facts, preferences, and past experiences across different sessions and even different users.

📚
Semantic Memory
General factual knowledge — documents, FAQs, product manuals, policies. Stored as embeddings in a vector database and retrieved via semantic similarity search.
Qdrant • Pinecone • pgvector
🕰️
Episodic Memory
Past agent experiences, prior conversations, and action-result sequences. Enables agents to remember "what worked" and avoid repeating past mistakes.
Mem0 • Zep • Redis
⚙️
Procedural Memory
Saved workflows, successful plans, and reusable step sequences. Agents retrieve proven procedures to speed up future tasks instead of re-planning from scratch.
PostgreSQL • MongoDB
👤
User / Entity Memory
Persistent facts about specific users, organizations, or entities — preferences, subscription tier, past issues. Enables true cross-session personalization.
KV Store • Graph DB
Memory Read/Write — Python Example
# Write to long-term memory after a task
async def save_to_memory(agent_id, content, memory_type):
    embedding = await embedder.embed(content)
    await vector_db.upsert({
        "id": uuid(), "vector": embedding,
        "payload": { "agent_id": agent_id, "content": content,
            "memory_type": memory_type, "ts": now() }
    })

# Retrieve relevant memories before a task step
async def retrieve_memories(query, agent_id, top_k=5):
    q_vec = await embedder.embed(query)
    results = await vector_db.search(
        vector=q_vec, filter={"agent_id": agent_id}, limit=top_k
    )
    return [r.payload["content"] for r in results]

5 RAG & Vector Databases

Retrieval-Augmented Generation (RAG) is the technique of grounding LLM responses with real, retrieved knowledge — preventing hallucinations and enabling agents to answer questions about private or up-to-date data without retraining the model.

The 5-Step RAG Pipeline

Ingest & ChunkSplit documents into semantic chunks (e.g., 512 tokens with 50-token overlap)
EmbedConvert each chunk to a high-dimensional vector using an embedding model (e.g., text-embedding-3-small, Gemini text-embedding)
IndexStore vectors + metadata in a vector database indexed with HNSW or IVF for fast ANN search
RetrieveEmbed the user's query, run ANN search to find top-k semantically closest chunks
GenerateInject retrieved chunks into the LLM prompt as grounding context and generate the final answer

Advanced RAG Patterns

Hybrid Search
Combines dense vector search with sparse BM25 keyword search to ensure exact entity matches are not missed by pure semantic retrieval.
Self-RAG / Agentic RAG
Agents decide when to retrieve, and can iteratively refine their search query across multiple rounds if initial results are insufficient.
GraphRAG
Supplements vector search with a knowledge graph for multi-hop reasoning across entity relationships — dramatically improves accuracy for complex questions.
Re-Ranking
Applies a cross-encoder model to re-score top-k retrieved chunks by relevance to the specific query before injecting into the prompt.
Vector DB Landscape
Qdrant
Rust-native, sparse+dense, payload filtering
Open Source
Pinecone
Managed cloud, serverless, production scale
Managed
pgvector
PostgreSQL extension, HNSW, hybrid SQL+vector
Extension
Weaviate
Multimodal embeddings, GraphQL API
Open Source
Chroma
Dev-friendly, local-first, LangChain native
Dev-First
HNSW — How ANN Search Works

HNSW (Hierarchical Navigable Small World) is the standard indexing algorithm. It builds a layered graph:

  • Upper layers: sparse, long-range connections for fast navigation
  • Lower layers: dense, local connections for precision
  • Search: enter at top, greedily descend toward the query vector

Result: sub-millisecond ANN search across millions of vectors.

6 Planning & Reasoning Patterns

Planning converts a high-level goal into a sequence of executable actions. Modern agents use several established patterns — often combining them within a single workflow.

🔄
ReAct
Reason + Act
The foundational agentic loop: the LLM alternates between a Thought (internal reasoning), an Action (tool call), and an Observation (tool output). Ideal for dynamic lookup tasks.
Thought: I need to search for the GDP
Action: web_search("GDP USA 2025")
Observation: "US GDP is $29.9T..."
Answer: The US GDP in 2025 is...
Best for: dynamic lookup, API-dependent tasks
⛓️
Chain-of-Thought (CoT)
Step-by-step reasoning
The LLM explicitly writes out reasoning steps before answering. Zero-shot CoT uses "Let's think step by step." Few-shot CoT provides worked examples. Significantly improves accuracy on math and logic.
Q: If 12 eggs cost $3, how much for 8?
Step 1: $3 / 12 = $0.25 per egg
Step 2: 8 x $0.25 = $2.00
Answer: $2.00
Best for: math, logic, structured reasoning
📋
Plan-and-Execute
Decompose → Execute
A Planner agent creates a high-level execution plan upfront. An Executor then carries out each step. Decoupling planning from execution is ideal for long-horizon, multi-stage workflows.
Plan:
1. Search for market data
2. Analyze competitors
3. Draft summary report
Execute each step sequentially →
Best for: complex research, multi-stage pipelines
🪞
Reflection / Self-Critique
Generate → Critique → Revise
After generating output, the agent (or a separate critic model) evaluates it against criteria: correctness, completeness, citations. Identified gaps trigger a revision loop — significantly reducing hallucinations.
Generate: "Revenue grew 15%"
Critique: "Missing source citation"
Revise: "Revenue grew 15% [Forbes 2025]"
Best for: writing, code generation, fact-checking
🌳
Tree of Thought (ToT)
Explore + Prune branches
Instead of a single chain, the agent generates multiple candidate paths simultaneously, evaluates each branch, and prunes unpromising ones. Used in LATS. Boosts performance on complex problem-solving significantly.
Goal: Solve coding problem
├─ Approach A → score: 0.7
├─ Approach B → score: 0.3 ✗
└─ Approach C → score: 0.9 ✓
Best for: optimization, creative problems, code
🎛️
Context Engineering
Intelligent context assembly
The practice of dynamically assembling the context window with only the most relevant information for each step — compressing old history, selectively retrieving memories, pruning irrelevant tool outputs to maximize signal-to-noise within token limits.
Context Assembler:
• Summarize old history
• Retrieve top-3 memories
• Include only relevant tools
Best for: long sessions, large codebases

7 Tool Integration Layer

Tools are the hands of the agent — the interface between the reasoning LLM and the outside world. When a tool is called, the agent's loop pauses, the tool executes, the result is returned as an observation, and reasoning continues.

🌐 Web Search
Tavily, Serper, Brave — real-time grounding
💻 Code Executor
E2B, Pyodide — run code in a secure sandbox
🗄️ Database Query
SQL, NoSQL, vector — read/write structured data
📁 File System
Read, write, parse PDFs, CSVs, JSON
🔗 REST / GraphQL APIs
Stripe, Slack, GitHub, Salesforce
🤖 Sub-Agent Call
Delegate to a specialized agent as a tool

MCP (Model Context Protocol): Anthropic's open standard for connecting agents to tools and data sources. Provides a universal, language-agnostic interface so any agent can use any tool. Learn MCP →

Tool Definition — JSON Schema
# Define a tool for the agent
tools = [{
    "name": "web_search",
    "description": "Search the web for
        real-time information",
    "parameters": {
        "type": "object",
        "properties": {
            "query": {
                "type": "string",
                "description": "Search query"
            },
            "max_results": {
                "type": "integer",
                "default": 5
            }
        },
        "required": ["query"]
    }
}]

# LLM emits this structured call:
# { "name": "web_search",
#   "arguments": {"query": "GDP 2025"}}

8 Multi-Agent Architecture

Complex tasks often exceed the capabilities of a single agent. Multi-agent systems distribute work across specialized agents that collaborate, check each other's work, and operate in parallel — increasing both capability and reliability.

👑
Orchestrator–Worker
An Orchestrator receives the goal, decomposes it into sub-tasks, and delegates each to specialized Worker agents. Workers report results back, and the Orchestrator synthesizes the final output. Most common pattern in production.
Orchestrator
├─ research_agent.run(query)
├─ analyst_agent.run(data)
└─ writer_agent.run(analysis)
🔄
Generator–Critic
A Generator produces output (code, text, plans), and a separate Critic independently evaluates it against criteria. The critique feeds back to the Generator for revision. Separating roles avoids confirmation bias.
code = generator.write(spec)
issues = critic.review(code)
code = generator.fix(issues)
critic.approve(code) ✓
🌐
Peer-to-Peer / Swarm
Agents work in parallel with no central coordinator. Each handles part of the work and can hand off tasks to peers when encountering a domain outside its specialty. Enables massive parallelism but requires careful state management.
Agent_A → handoff → Agent_B
Agent_B → handoff → Agent_C
All share: message bus + state
Multi-Agent Communication Protocols
A2A (Agent-to-Agent)
Google's open protocol for agents to discover and communicate across frameworks. Agents publish an "Agent Card" describing their capabilities. Learn A2A →
MCP (Model Context Protocol)
Standard for tool and resource connectivity. Agents act as MCP clients, calling MCP servers that expose tools, prompts, and resources through a standardized API.
Message Queues (Kafka / Redis)
For async, event-driven multi-agent systems. Agents publish events to a message bus; other agents subscribe and react. Enables decoupled, scalable architectures.

9 Production Considerations

🔭
Observability
Trace every step of the agentic loop using OpenTelemetry. Log tool calls, LLM tokens, and execution time. Platforms like LangSmith, Arize, and Braintrust provide agent-specific tracing dashboards.
🛡️
Safety & Guardrails
Apply input guardrails (jailbreak detection) and output guardrails (PII, harmful content, policy) on every LLM call. Use sandboxed code execution to prevent untrusted code from damaging systems.
⏸️
Human-in-the-Loop
For high-stakes actions (deleting data, sending emails, making payments), pause the agent and require explicit human approval before proceeding. LangGraph supports checkpoint-based HITL natively.
💰
Cost & Rate Limits
Set max step limits to prevent infinite loops. Implement token budgeting per session. Use cheaper models for simple steps; save powerful models for complex reasoning. Cache repeated retrievals.
Full Architecture — Component Summary
Layer Responsibility Common Technologies Failure Mode
Perception Ingest multimodal input (text, images, audio, files) Gemini, Claude, GPT-4o Missing input modalities
Short-Term Memory Active context: history, retrievals, observations Context window (128K–2M tokens) Context overflow, truncation loss
Long-Term Memory Semantic, episodic, procedural, entity storage Qdrant, Pinecone, Mem0, Zep Stale data, irrelevant retrieval
Planning Decompose goals, sequence actions, handle failures ReAct, CoT, ToT, LangGraph Infinite loops, hallucinated plans
Tool Layer Interface with external APIs, DBs, code execution MCP, OpenAPI, E2B Tool timeouts, invalid arguments
Safety Guardrails, sandboxing, HITL, rate limiting Guardrails AI, NeMo, custom Prompt injection, cost overruns
Observability Trace, log, evaluate every agent step LangSmith, Arize, OTEL Silent failures, undetected regressions

10 FAQ

What is the difference between an AI agent and an LLM?
An LLM is a model that generates text given an input prompt — it's stateless, single-pass, and has no ability to interact with the world. An AI agent wraps an LLM with a loop, memory, and tools. The agent can iteratively call tools (web search, databases, APIs), observe results, store information across sessions, and continue looping until a goal is achieved. Think of the LLM as the "brain" and the agent architecture as the "body" that lets it act.
Why use a vector database instead of SQL for agent memory?
SQL databases are optimized for exact matches (WHERE name = 'Alice'). Vector databases are optimized for semantic similarity — finding content that means the same thing even if it uses different words. When an agent needs to recall "past conversations about customer churn," a vector search finds relevant memories containing "retention," "cancellations," or "monthly drop." SQL would require exact keyword matching, which is too brittle for natural language retrieval. In production, many systems use both: vector search for retrieval + SQL for metadata filtering (user ID, date range).
What is RAG and when should I use it vs. fine-tuning?
RAG retrieves relevant knowledge at inference time and injects it into the prompt. Use RAG when: (1) data changes frequently, (2) data is proprietary, (3) you need explainable citations. Fine-tuning bakes knowledge into model weights during training. Use fine-tuning when: (1) you want to change the model's behavior or style, (2) data is static and large, (3) you need faster inference with smaller context. In production, RAG + a lightly fine-tuned model often outperforms either approach alone.
How do you prevent an AI agent from running forever?
Multiple safety mechanisms: (1) Max step limit: hard cap on loop iterations (e.g., 20 steps). (2) Token budget: abort if total tokens consumed exceeds a threshold. (3) Timeout: wall-clock time limit per task. (4) Stopping criteria: explicitly define what constitutes a "final answer" state. (5) Loop detection: detect repeated identical tool calls. LangGraph implements these as graph-level conditions that trigger early exit.
What is the ReAct pattern and why is it so widely used?
ReAct (Reasoning + Acting) is the foundational pattern because it is simple, auditable, and highly effective. The agent alternates between writing a Thought (visible reasoning), an Action (tool call), and reading the Observation (tool result). Because thoughts are written out, each step is traceable — unlike black-box systems. It was popularized by the 2022 Google Research paper "ReAct: Synergizing Reasoning and Acting in Language Models" and remains the default in LangChain, LangGraph, and OpenAI's Agents SDK.
How do multi-agent systems avoid duplicating work?
Coordination mechanisms: (1) Shared state store (Redis, PostgreSQL): single source of truth for task assignment and progress. (2) Message queues (Kafka): agents claim tasks from a queue, preventing duplicate processing. (3) Orchestrator ownership: a dedicated Orchestrator assigns each sub-task to exactly one worker. (4) Idempotent operations: tool calls are designed so running the same operation twice is safe. (5) State machine (LangGraph): formal task states (PENDING → IN_PROGRESS → DONE) prevent concurrent assignment.
Go Deeper

Related Tutorials

Deep dives into each layer of the AI agent architecture