6.2.5AI Agents & Tool Use

Memory systems for agents

4,092 words19 min readdifficulty · medium1 backlinks

What Is Agent Memory?

The Three-Layer Memory Architecture

Modern agent memory systems use a three-tier hierarchy, inspired by human memory:

1. Working Memory (Short-Term)

2. Episodic Memory (Mid-Term)

3. Semantic Memory (Long-Term)

Memory Operations: The Four Primitives

All memory systems implement four core operations:

Derivation: When to Forget?

Problem: Infinite memory → cost explosion + noise (irrelevant old data).

Solution: Implement a forgetting policy.

Approach 1: Recency-Based (Sliding Window) Keep(e)={1if tnowte<Twindow0otherwise\text{Keep}(e) = \begin{cases} 1 & \text{if } t_{\text{now}} - t_e < T_{\text{window}} \\ 0 & \text{otherwise} \end{cases} Where tet_e is timestamp of episode ee, TwindowT_{\text{window}} is retention period (e.g., 30 days).

WHY: Older data is less likely to be relevant. Simple implement.

Approach 2: Importance-Based Importance(e)=w1AccessCount(e)+w2Recency(e)+w3UserFeedback(e)\text{Importance}(e) = w_1 \cdot \text{AccessCount}(e) + w_2 \cdot \text{Recency}(e) + w_3 \cdot \text{UserFeedback}(e) Keep top-K by importance score.

WHY THIS STEP? AccessCount → frequently used facts are valuable. UserFeedback → user-starred items should persist.

Approach 3: Semantic Redundancy If new episode enewe_{\text{new}} has embedding vnew\mathbf{v}_{\text{new}} and existing episode eolde_{\text{old}} has vold\mathbf{v}_{\text{old}}: cosine_sim(vnew,vold)>0.95    Merge or Delete eold\text{cosine\_sim}(\mathbf{v}_{\text{new}}, \mathbf{v}_{\text{old}}) > 0.95 \implies \text{Merge or Delete } e_{\text{old}}

WHY: Avoid storing near-duplicate information. Saves space + reduces retrieval noise.

Retrieval Strategies: How to Find the Right Memory

Derivation from First Principles:

  1. WHY RELEVANCE? If the agent is discussing "Python errors," retrieving memories about "dinner recipes" wastes context. Semantic similarity ensures topical match.

  2. WHY RECENCY? Information decays. The user's preference from yesterday is more reliable than from a year ago. Exponential decay eλte^{-\lambda t} models human forgetting curve.

  3. WHY IMPORTANCE? Some facts are evergreen. "Our company policy on X" should persist even if not recently accessed. Access frequency signals this.

  4. HOW TO COMBINE? Linear combination is simple, interpretable, and fast. Normalize each term to [0,1], then weight.

Step-by-step scoring:

Relevance(mi,C)=vmivCvmivC[0,1]Recency(mi)=e0.1days_ago[0,1]Importance(mi)=access_count(mi)maxjaccess_count(mj)[0,1]Score(mi,C)=0.7Relevance+0.2Recency+0.1Importance\begin{align} \text{Relevance}(m_i, C) &= \frac{\mathbf{v}_{m_i} \cdot \mathbf{v}_C}{\|\mathbf{v}_{m_i}\| \|\mathbf{v}_C\|} \quad \in [0, 1] \\ \text{Recency}(m_i) &= e^{-0.1 \cdot \text{days\_ago}} \quad \in [0, 1] \\ \text{Importance}(m_i) &= \frac{\text{access\_count}(m_i)}{\max_j \text{access\_count}(m_j)} \quad \in [0, 1] \\ \text{Score}(m_i, C) &= 0.7 \cdot \text{Relevance} + 0.2 \cdot \text{Recency} + 0.1 \cdot \text{Importance} \end{align}

Memory Architectures in Practice

Pattern 1: Conversation Buffer Memory

Pattern 2: Summary Memory

Pattern 3: Vector Store Memory

Pattern 4: Hybrid Memory (Combining All Three)

Common Mistakes & How to Avoid Them

Connections

  • Retrieval-Augmented Generation (RAG): Memory systems use RAG principles to fetch relevant context.
  • Vector Databases: Episodic and semantic memory often stored in vector DBs (Pinecone, Chroma).
  • LM Context Window Management: Working memory fits within context window constraints.
  • Knowledge Graphs: Semantic memory often structured as knowledge graphs (entities + relations).
  • Prompt Engineering: Memory retrieval results must be formatted into effective prompts.
  • Agent Planning and Reasoning: Memory provides the "experience" that planning relies on.
  • Multi-Agent Systems: Agents can share semantic memory (common knowledge base) while maintaining separate episodic memory.

Recall Explain to a 12-Year-Old

Imagine you're building a robot assistant for your homework. Every time you ask it a question, it answers, then forgets everything. So next time you ask "What was my math homework?", it goes "I don't know, I just woke up!" That would be annoying, right? Memory systems are like giving your robot a notebook:

  • Working memory = the page the robot is writing on right now (today's homework)
  • Episodic memory = the old pages in the notebook (what homework you did last week)
  • Semantic memory = a cheat sheet the robot made of useful facts (like "math homework is always on page 45")

When you ask a question, the robot:

  1. Looks at the current page (working memory)
  2. Flips back through old pages to find related stuff (episodic memory)
  3. Checks the cheat sheet for general rules (semantic memory) This way, the robot remembers what you talked about before, learns from past mistakes, and gets smarter over time. It's like having a study buddy who actually pays attention!

Flashcards

#flashcards/ai-ml

What are the three layers of agent memory systems? :: Working memory (short-term, current context), Episodic memory (mid-term, past interactions), Semantic memory (long-term, general knowledge).

Why do agents need memory beyond just conversation history?
To maintain state across interactions, learn from experience, build long-term context, and avoid repeating questions or mistakes.
What is working memory in agent systems?
The immediate context for the current task, stored within the LM's context window, typically the last few conversation turns plus active reasoning steps.
What is episodic memory?
A store of past interaction sequences (episodes) that can be retrieved via semantic search, temporal lookup, or entity-based queries. Archives "what happened when."
What is semantic memory in agents?
Long-term storage of general facts, procedures, and world knowledge independent of specific episodes. Structured as knowledge graphs or key-value stores.
What are the four core memory operations?
Write (store), Read (retrieve), Update (modify), Forget (delete).
Why is forgetting important in memory systems?
To manage storage costs, reduce retrieval noise from irrelevant old data, improve performance, and respect privacy requirements.
What is the memory retrieval scoring formula?
Score(m, C) = α·Relevance(m, C) + β·Recency(m) + γ·Importance(m), where α, β, γ are weights (typically 0.7, 0.2, 0.1).
What is conversation buffer memory?
The simplest memory type that keeps the last N messages in working memory using a FIFO queue.
What is summary memory?
A memory system that stores compressed summaries of conversations instead of raw messages, saving space at the cost of detail.
What is vector store memory?
Memory stored as embedings in a vector database, enabling semantic search via nearest-neighbor retrieval.
What is hybrid memory architecture?
A system combining working memory (buffer), episodic memory (vector store), and semantic memory (knowledge graph) with smart retrieval routing.
What is the capacity constraint for working memory?
Working Memory Size ≤ Context Window - System Prompt - Output Buffer
How does recency-based forgetting work?
Keep(e) = 1 if t_now - t_e < T_window, else 0. Deletes memories older than the retention window.
How does importance-based memory ranking work?
Importance(e) = w1·AccessCount(e) + w2·Recency(e) + w3·UserFeedback(e). Keeps top-K items by importance score.
What is the relevance component in retrieval scoring?
Relevance(m, C) = cosine_similarity(embed(m), embed(C)), measuring semantic similarity between memory and current context.

What is the recency component in retrieval scoring? :: Recency(m) = e^(-λ(t_now - t_m)), an exponential decay modeling human forgetting curves.

What is semantic redundancy pruning?
If cosine_sim(v_new, v_old) > threshold (e.g., 0.95), merge or delete the old memory to avoid storing duplicates.
Why not stuff all history into the LM prompt?
Context windows are limited, irrelevant history adds noise and degrades performance, and costs scale linearly with input token count.
Why use hybrid scoring instead of just embedding similarity?
Pure mises recency (outdated info) and importance (rare but critical facts). Hybrid scoring balances semantic match with temporal and usage signals.
What happens if memories never get updated?
Stale facts persist (user preferences change, APIs update, facts become outdated), causing the agent to contradict itself or provide wrong information.

Concept Map

transforms stateless calls into

organized as

inspired by

tier 1

tier 2

constrained by

managed via

stores

recalled via

holds timestamp, summary, facts

Agent Memory

Stateful Context-Aware Agents

Three-Layer Architecture

Working Memory Short-Term

Episodic Memory Mid-Term

LM Context Window

Sliding Window / Token Budget

Episode Record

Semantic Search Retrieval

Human Memory

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, agent memory ka core idea bilkul human conversation jaisa hai. Socho ki agar tum kisi se baat kar rahe ho aur har 5 second baad tum sab kuch bhool jaao, toh kya hoga? Tum baar-baar same cheez repeat karoge, context miss karoge, aur kaam aage nahi badhega. AI agents ke saath bhi exactly yahi problem hai. Bina memory ke, har agent call ek fresh start hota hai—jaise har baar naya banda aa raha ho. Memory system agent ko yeh power deta hai ki woh past interactions yaad rakhe, experience se seekhe, overall goal ka context banaye, aur multi-step task mein apni position track kare. Isse agent ek simple "tool" se badalkar ek real "partner" ban jaata hai.

Ab yeh memory kaam kaise karti hai? Iska architecture human brain se inspired hai aur teen layers mein bata hai. Pehli hai Working Memory (short-term)—yeh current task ka immediate context hold karti hai, jaise abhi ka user query, tool outputs aur recent 3-5 exchanges. Problem yeh hai ki LM ka context window limited hota hai (maano 8K tokens), toh system ko formula se calculate karna padta hai ki kitna working memory bache ga after system prompt aur output buffer nikaal ke—roughly 6500 tokens. Doosri hai Episodic Memory (mid-term)—yeh past conversations ko "episodes" ki tarah store karti hai with timestamp, user_id, summary aur outcome. Jab kuch chahiye toh agent semantic search (cosine similarity), temporal lookup ya entity-based search se relevant episode nikaal leta hai, usually vector database (Pinecone, Chroma) use karke.

Yeh why-it-matters isliye hai kyunki real applications mein context bahut zaroori hota hai. Jaise customer support agent ka example lo—Day 1 pe user billing error report karta hai aur refund issue hota hai. Day 5 pe jab woh puchta hai "Is my refund processed?", toh agent apni episodic memory se woh purana episode retrieve karta hai, working memory mein load karta hai, aur seedha relevant answer deta hai. Bina memory ke, agent poora context dobara maangta aur user frustrate ho jaata. Toh basically, yeh multi-layer architecture agent ko smart, consistent aur genuinely helpful banata hai—jo asli intelligence ki nishaani hai.

Go deeper — visual, from zero

Test yourself — AI Agents & Tool Use

Connections