Library

Volume 2 · Agentic AI Systems

Notebook
Sign in

Section 29

Memory Architecture

1,131 words · about 5 min

29.1 The Memory Hierarchy

Production agents need several distinct memory types, each with a different storage backend and retention policy:

┌─────────────────────────────────────────────────┐
│                Agent Memory System               │
│                                                   │
│  ┌───────────────────────────────────────────┐   │
│  │ Working Memory (Immediate Context)         │   │
│  │ - Current conversation / current task       │   │
│  │ - Active tool results                       │   │
│  │ Storage: LLM context window                │   │
│  └───────────────────────────────────────────┘   │
│                                                   │
│  ┌───────────────────────────────────────────┐   │
│  │ Short-Term Memory (Session)                │   │
│  │ - Conversation history this session         │   │
│  │ - Recent actions and outcomes               │   │
│  │ Storage: In-memory / Redis                  │   │
│  └───────────────────────────────────────────┘   │
│                                                   │
│  ┌───────────────────────────────────────────┐   │
│  │ Long-Term Memory (Persistent)              │   │
│  │ - Past interaction summaries                │   │
│  │ - Learned user/domain preferences           │   │
│  │ - Successful resolution patterns            │   │
│  │ Storage: Vector DB + structured DB          │   │
│  └───────────────────────────────────────────┘   │
│                                                   │
│  ┌───────────────────────────────────────────┐   │
│  │ Episodic Memory (Experience)               │   │
│  │ - Past task execution traces                │   │
│  │ - Failures and reflections (Reflexion)      │   │
│  │ - Successful strategies                     │   │
│  │ Storage: Vector DB with temporal index      │   │
│  └───────────────────────────────────────────┘   │
│                                                   │
│  ┌───────────────────────────────────────────┐   │
│  │ Semantic Memory (Domain Knowledge)         │   │
│  │ - Domain facts, taxonomies, rules           │   │
│  │ - Organizational knowledge graph            │   │
│  │ Storage: Knowledge Graph + Vector DB        │   │
│  └───────────────────────────────────────────┘   │
└─────────────────────────────────────────────────┘

29.2 Context Window Management — Sliding Window with Summarization

class ConversationManager:
    def __init__(self, llm, max_tokens: int = 8000):
        self.llm = llm
        self.messages: list[dict] = []
        self.summary: str = ""
        self.max_tokens = max_tokens

    def add_message(self, message: dict):
        self.messages.append(message)
        if self._count_tokens() > self.max_tokens:
            self._compress()

    def _compress(self):
        """Summarize the older half of the conversation, keep the rest verbatim."""
        midpoint = len(self.messages) // 2
        old_messages = self.messages[:midpoint]
        new_summary = self.llm.summarize(old_messages)
        self.summary = f"{self.summary}\n{new_summary}".strip()
        self.messages = self.messages[midpoint:]

    def _count_tokens(self) -> int:
        return sum(len(m["content"]) // 4 for m in self.messages)  # rough heuristic

    def get_context(self) -> list[dict]:
        return [
            {"role": "system", "content": f"Previous context summary:\n{self.summary}"},
            *self.messages,
        ]

Rather than replaying the full conversation on every LLM call, maintain a compact, typed state object and pass that:

class TaskState:
    def __init__(self, task_id: str, goal: str):
        self.task_id = task_id
        self.goal = goal
        self.status = "in_progress"
        self.completed_steps: list[str] = []
        self.current_step: str | None = None
        self.key_findings: list[str] = []
        self.pending_steps: list[str] = []
        self.errors: list[str] = []

    def to_prompt_context(self) -> str:
        return (
            f"Goal: {self.goal}\n"
            f"Status: {self.status}\n"
            f"Completed: {', '.join(self.completed_steps) or 'none'}\n"
            f"Current step: {self.current_step}\n"
            f"Key findings so far:\n" + "\n".join(f"- {f}" for f in self.key_findings)
        )

Example serialized state passed between agent invocations:

{
  "task_id": "task_001",
  "goal": "Analyze Q3 sales data and produce an executive summary",
  "status": "in_progress",
  "completed_steps": ["data_retrieval", "trend_analysis"],
  "current_step": "competitor_comparison",
  "key_findings": [
    "Revenue up 15% YoY",
    "APAC region showed 30% growth"
  ],
  "pending_steps": ["executive_summary", "visualization"],
  "errors": []
}

29.4 Retrieval-Augmented Memory (Episodic Recall)

Instead of stuffing every past action into the prompt, store agent actions/observations in a searchable index (vector DB with a temporal/task index) and retrieve only what’s relevant to the current step:

class EpisodicMemory:
    def __init__(self, vector_store):
        self.vector_store = vector_store

    def record(self, task_id: str, event: dict):
        text = f"{event['action']} -> {event['observation']}"
        self.vector_store.upsert(
            id=f"{task_id}:{event['step']}",
            text=text,
            metadata={"task_id": task_id, "timestamp": event["timestamp"]},
        )

    def recall(self, query: str, task_id: str | None = None, top_k: int = 5):
        filt = {"task_id": task_id} if task_id else None
        return self.vector_store.search(query, top_k=top_k, filter=filt)

29.5 Checkpoint & Resume

For long-running agents (multi-hour incident investigations, multi-day claim audits), persist full state periodically so execution can survive process restarts and support hand-off between shifts/operators:

class CheckpointStore:
    def save(self, task_id: str, state: dict):
        self.db.upsert("agent_checkpoints", {"task_id": task_id, "state": state,
                                              "saved_at": now()})

    def load(self, task_id: str) -> dict | None:
        row = self.db.get("agent_checkpoints", task_id)
        return row["state"] if row else None

Section 29 — Interview Q&A

Q1: How do you manage context for an agent handling a task with 50+ reasoning steps over several hours? Four complementary strategies: (1) a compact structured state object instead of full transcript replay, (2) hierarchical summarization — every N steps, summarize into a paragraph, and periodically summarize the summaries while always preserving current hypothesis/key findings/attempted actions, (3) retrieval-augmented memory — index all actions/observations and pull back only what’s relevant to the current step, (4) checkpoint-and-resume — persist full state to durable storage periodically so a crash or shift change doesn’t lose progress.

Q2: What’s the difference between episodic and semantic memory, and why do agents need both? Semantic memory is general domain knowledge — facts, rules, taxonomies — that’s true regardless of any specific task (e.g., coding rules, payer policies, a service dependency graph). Episodic memory is task-specific experience — what happened in a specific past run, including failures and their reflections. Semantic memory answers “what is generally true”; episodic memory answers “what worked last time in a similar situation.” Both are typically vector-indexed, but episodic memory needs a temporal/task index and generally has a retention/decay policy, while semantic memory is closer to a stable knowledge base or knowledge graph.

Q3: Working memory vs. short-term memory vs. long-term memory — how do you decide storage backend for each? Working memory lives entirely in the LLM’s context window for the current turn — no separate storage. Short-term (session) memory needs fast read/write and TTL expiry — Redis or in-process cache is typical. Long-term memory needs durability and semantic search across sessions/users — a vector DB paired with a structured DB (for exact-match lookups like user ID or account ID) is the standard combination.