Cybersecurity

The Five Types of Agent Memory

Python JavaScript LLMs RAG Prompt Engineering AI Agents Authentication Databases SQL Java Embeddings Vector Search Semantic Search Credentials Passwords Hashing
2,115 words
Key Takeaway: AI agents need different types of memory for different purposes. Conversation history remembers what was said, working memory tracks the current task, persistent memory stores preferences and patterns, vector memory enables semantic search over past knowledge, and structured state manages multi-step task progress. Choosing the right memory type determines how well an agent can reason, adapt, and maintain context.

When you use an AI coding agent, it seems to "remember" what you said three messages ago, track which file it is editing, recall your project conventions, and search through documentation for relevant examples. But that memory is not one system — it is five distinct mechanisms working together.

This tutorial explains each type of agent memory, how they differ, when to use each, and the privacy risks that come with storing agent knowledge.

The Five Types of Agent Memory

Agent Memory Architecture:

┌─────────────┐  ┌─────────────┐
│ 💬 History  │  │ 📝 Working  │
│ (ring buffer)│  │ (scratchpad)│
└──────┬──────┘  └──────┬──────┘
      │                  │
      └────────┬─────────┘
              │
              ▼
         ┌────────┐
         │  🧠   │
         │  LLM  │
         └────────┘
            │
    ┌───────┼───────┐
    │       │       │
┌───▼───┐ ┌──▼──┐ ┌──▼─────┐
│💾 Pers.│ │🔍 Vec│ │⚙️ State│
│(store) │ │(search)│ │(tasks) │
└───────┘ └─────┘ └────────┘

Type 1: Conversation History

💬 What It Does

Stores the sequence of user and assistant messages. This is what gives an AI chatbot the feeling of "remembering" what you said earlier in the conversation.

Conversation history is typically implemented as a ring buffer — a fixed-size list that drops the oldest messages when full:

# Ring buffer: keeps last N message pairs messages = ["user: Find the bug", "assistant: Reading auth.py...", ...] max_turns = 10 # 20 messages total # When full, oldest messages are dropped if len(messages) > max_turns * 2: messages = messages[-max_turns * 2:]
PropertyValue
ScopeCurrent session only
PersistsNo — cleared when session ends
SearchFIFO (first in, first out)
Size limitContext window (4K–1M tokens)
Use caseMulti-turn conversation, follow-up questions
Privacy riskLow — stays in session, not stored

When it fails: If the conversation is long, early context is dropped. The agent "forgets" what you said 20 messages ago.

Type 2: Working Memory

📝 What It Does

A per-task scratchpad that tracks current progress: which file is being edited, what bugs were found, what the current plan is. Cleared when the task finishes.

# Working memory: task-scoped scratchpad working_memory = { "current_file": "auth.py", "bug_line": 42, "test_failures": ["test_login", "test_token"], "plan": ["Read file", "Find bug", "Fix", "Test"] } # Cleared when task completes working_memory.clear()
PropertyValue
ScopeCurrent task only
PersistsNo — cleared between tasks
SearchKey lookup (fast)
Size limitSmall (few hundred tokens)
Use caseTracking current debugging state, file being edited, errors encountered
Privacy riskLow — ephemeral

When it fails: If the task is long, the scratchpad can overflow. The agent may forget which step it was on.

Type 3: Persistent Memory

💾 What It Does

Stores information across sessions: user preferences, project conventions, known patterns, frequently used configurations. Survives between conversations.

# Persistent memory: survives between sessions persistent = { "preferences": {"theme": "dark", "lang": "en"}, "patterns": {"api_style": "REST with /api/v1 prefix"}, "known_issues": {"rate_limit": "Hits on /search endpoint"} } # Loaded at start of every new session
PropertyValue
ScopeCross-session, long-term
PersistsYes — stored in database or file
SearchKey/category lookup
Size limitModerate (megabytes)
Use caseUser preferences, project style, past decisions
Privacy riskMedium — stored data may contain sensitive information
⚠️ Privacy consideration: Persistent memory stores data that survives sessions. If it contains user information, project secrets, or access patterns, it must be encrypted at rest and access-controlled. Never store API keys, passwords, or credentials in persistent agent memory.

Type 4: Vector Memory

🔍 What It Does

Enables semantic search over past knowledge. Instead of exact keyword matching, it finds conceptually similar content using embedding vectors. This is the foundation of RAG (Retrieval-Augmented Generation).

Vector memory works by converting text into numerical vectors and finding the closest matches:

# Vector memory: semantic search documents = [ "Python uses dynamic typing", "Flask is a lightweight Python web framework", "JavaScript runs in the browser", "Django provides an ORM for Python", "PostgreSQL is a relational database", ] # Query: "Python web framework" # Results (by cosine similarity): # 0.6124 — Flask (Python web framework) # 0.2041 — Django (Python ORM) # 0.0000 — PostgreSQL (no match)
PropertyValue
ScopeCross-session, large corpus
PersistsYes — stored in vector database
SearchSemantic (embedding similarity)
Size limitLarge (millions of entries)
Use caseRAG, documentation search, knowledge retrieval
Privacy riskHigh — stored embeddings can leak information
⚠️ Privacy risk: Vector embeddings are derived from text. In some cases, embeddings can be inverted to reconstruct approximate original text. Treat vector stores containing sensitive data with the same care as the raw data itself. Encrypt at rest, restrict access, and audit queries.

Type 5: Structured State

⚙️ What It Does

Tracks multi-step task progress with typed fields: task ID, status, steps completed, results, errors. This is what allows an agent to manage complex workflows across many iterations.

# Structured state: typed task tracker task = { "id": "auth-fix-001", "goal": "Fix authentication bug", "status": "completed", "steps": [ "Read auth.py — found missing validation", "Added token check", "Ran tests — 12/12 pass" ], "errors": [] }
PropertyValue
ScopeCurrent task, typed
PersistsDuring task execution
SearchBy task ID or status
Size limitDepends on task complexity
Use caseMulti-step workflows, debugging, refactoring
Privacy riskLow — task-scoped

How the Five Types Work Together

In a real agent loop, all five memory types cooperate:

# Agent receives: "Fix the failing test in auth.py" # 1. CONVERSATION HISTORY — "I remember you asked about auth bugs earlier" history.add("user", "Fix the failing test in auth.py") # 2. WORKING MEMORY — tracks current task state working.set("current_file", "auth.py") working.set("plan", ["Read", "Find bug", "Fix", "Test"]) # 3. PERSISTENT MEMORY — recalls project conventions style = persistent.recall("code_style") # → {indent: 4, line_length: 88} # 4. VECTOR MEMORY — searches for similar past fixes docs = vector.search("authentication token validation") # 5. STRUCTURED STATE — tracks iteration progress task = state.create_task("fix-auth", "Fix failing test")

Memory and the Context Window

All memory types must ultimately fit into the LLM's context window. The challenge is choosing what to include:

StrategyWhat Goes in ContextToken CostQuality
EverythingFull history + working + persistentHighComplete but expensive
Recent onlyLast N messages + workingLowMay miss important context
RAG-retrievedRelevant past docs + working + recentMediumBalanced, relevant
SummarizedSummary of history + working + relevantMediumMay lose details
Context engineering insight: The most effective agents use a hybrid strategy: keep working memory and the last few messages in context, retrieve relevant documents via vector search, and summarize older conversation history. This balances token cost with context quality.

Privacy Risks by Memory Type

Memory TypeData StoredPrivacy RiskMitigation
HistoryMessages, code snippetsLow-MediumClear on session end, encrypt in transit
WorkingTask state, file pathsLowEphemeral, clear between tasks
PersistentPreferences, patternsMediumEncrypt at rest, access control
VectorEmbeddings, document chunksHighEncrypt, restrict access, audit
StructuredTask progress, resultsLowTask-scoped, clear after completion
⚠️ Key principle: "Never assume agent memory is safe simply because it is stored locally." Embeddings can leak information. Persistent stores can be accessed. Logs can contain sensitive data. Apply the same security controls to agent memory that you would apply to any data store.

Memory vs Context vs State

These terms are often confused. Here is the precise distinction:

TermMeaningLifetimeExample
ContextWhat the LLM sees right nowPer requestThe prompt sent to the API
StateAccumulated information about progressPer task/sessionSteps completed, current file
MemoryPersisted knowledge across sessionsCross-sessionUser preferences, past documents

Context is a snapshot. State is a record. Memory is a store.

Implementing Agent Memory: Practical Patterns

Pattern 1: Layered Context Assembly

# Build the LLM prompt from multiple memory sources context_parts = [] # Layer 1: System instructions (always present) context_parts.append(system_prompt) # Layer 2: Working memory (task state) context_parts.append(format_working_memory(working_memory)) # Layer 3: Relevant past (vector search) relevant = vector_memory.search(current_query, top_k=5) context_parts.append(format_relevant_docs(relevant)) # Layer 4: Conversation history (recent) context_parts.append(format_history(conversation_history, max_turns=5)) # Assemble final prompt final_prompt = "\n\n".join(context_parts)

Pattern 2: Memory-Aware Agent Loop

def agent_step(goal, history, working, persistent, vector, state): # 1. Load relevant context from all memory types context = assemble_context(history, working, persistent, vector) # 2. Plan next action plan = llm.plan(goal, context) # 3. Execute and observe result = execute(plan.tool, plan.args) # 4. Update working memory working.set("last_result", result) # 5. Update structured state state.current_task.complete_step(result) # 6. Save to persistent memory if significant if result.is_important: persistent.save(result.key, result.value, "patterns") # 7. Add to vector memory for future search vector.add(result.summary, metadata={"task": goal}) # 8. Update conversation history history.add("assistant", result.summary) return result

Common Memory Mistakes

MistakeProblemFix
Storing everything in historyContext overflow, high token costUse ring buffer, summarize old messages
Ignoring working memoryAgent repeats work, loses progressTrack current file, plan, and errors
Storing secrets in persistent memorySecurity breach if store is compromisedNever store credentials; use secret managers
Vector memory without deduplicationRedundant search resultsHash and deduplicate before inserting
No structured stateAgent cannot resume interrupted tasksTrack task status and progress
Over-relying on context windowExpensive, slow, may exceed limitsUse RAG to retrieve relevant context

Memory and Security

Agent memory creates specific security considerations:

  • Injection via memory: If an attacker can write to persistent or vector memory, they can inject instructions that affect future agent behavior
  • Data leakage: Vector embeddings of sensitive documents can sometimes be reconstructed
  • Scope creep: Information stored for one purpose may be accessed for another
  • Retention: Keeping memory too long increases exposure; not keeping it long enough reduces capability
  • Access control: Multiple users sharing an agent should not see each other's memory

✅ Agent Memory Security Checklist

  • ☐ Never store API keys, passwords, or tokens in agent memory
  • ☐ Encrypt persistent memory at rest
  • ☐ Encrypt vector embeddings at rest
  • ☐ Implement access control per user/workspace
  • ☐ Clear working memory between tasks
  • ☐ Set retention limits on persistent memory
  • ☐ Audit memory writes and reads
  • ☐ Sanitize inputs before storing in vector memory
  • ☐ Isolate user memory in multi-tenant systems
  • ☐ Provide memory deletion capabilities (right to be forgotten)

Practical Exercises

Exercise 1: Trace the Memory

Read through the demo output. For each output, identify which memory type it demonstrates. What data is stored in each? What would be lost if that memory type were removed?

Exercise 2: Design Memory for a Coding Agent

Design the memory architecture for an AI coding agent. Which of the 5 types would you use? What would you store in each? What size limits would you set?

Exercise 3: Vector Memory Trade-offs

The demo uses TF-IDF for semantic search. What are the limitations compared to real embedding models? When would TF-IDF be insufficient? What privacy risks do real embedding models introduce?

Exercise 4: Privacy Audit

Review the security checklist. For each item, describe a realistic scenario where ignoring that item could lead to a security incident. Which items are most critical for a production system?

FAQ

Q: Which memory type is most important?
A: None is inherently more important — they serve different purposes. A well-designed agent needs at least conversation history (for dialogue), working memory (for current task), and some form of persistent or vector memory (for knowledge).

Q: Can I use all five types in one agent?
A: Yes, and production agents typically do. The key is assembling the right subset into the context window for each LLM call.

Q: How much context should I include?
A: Enough to be relevant, not so much that it overwhelms. A good rule: working memory + last 3-5 conversation turns + top 3-5 vector search results.

Q: Is vector memory the same as RAG?
A: Vector memory is a component of RAG. RAG adds chunking, retrieval, and context assembly on top of vector search.

Q: How do I handle memory across multiple users?
A: Isolate memory per user or workspace. Each user should have their own conversation history, working memory, and persistent memory. Vector stores should be partitioned by access control.

Q: Can agent memory be deleted?
A: It should be deletable for privacy compliance (e.g., GDPR right to erasure). Design memory stores with deletion capabilities from the start.

Further Reading

Continue Learning: Understand context engineering, explore RAG from scratch, learn how agent loops work, and protect data with privacy by design.

Discuss this topic on BestWordz Community.

Continue Learning: RAG Fundamentals

From embeddings to production RAG systems

  1. The Five Types of Agent Memory (this article)
  2. Why RAG Exists: The Hallucination Problem
  3. What Are Embeddings?
  4. Hybrid Search: Combining BM25 and Vector Search
  5. RAG Architecture Explained: Every Component of a Retrieval-Augmented AI System