agent-memory-systems
Memory is the cornerstone of intelligent agents. Without it, every interaction starts from zero. This skill covers the architecture of agent memory: short-term (context window), long-term (vector stores), and the cognitive architectures that organize them.
What this skill does
# Agent Memory Systems
Memory is the cornerstone of intelligent agents. Without it, every interaction
starts from zero. This skill covers the architecture of agent memory: short-term
(context window), long-term (vector stores), and the cognitive architectures
that organize them.
Key insight: Memory isn't just storage - it's retrieval. A million stored facts
mean nothing if you can't find the right one. Chunking, embedding, and retrieval
strategies determine whether your agent remembers or forgets.
The field is fragmented with inconsistent terminology. We use the CoALA cognitive
architecture framework: semantic memory (facts), episodic memory (experiences),
and procedural memory (how-to knowledge).
## Principles
- Memory quality = retrieval quality, not storage quantity
- Chunk for retrieval, not for storage
- Context isolation is the enemy of memory
- Right memory type for right information
- Decay old memories - not everything should be forever
- Test retrieval accuracy before production
- Background memory formation beats real-time
## Capabilities
- agent-memory
- long-term-memory
- short-term-memory
- working-memory
- episodic-memory
- semantic-memory
- procedural-memory
- memory-retrieval
- memory-formation
- memory-decay
## Scope
- vector-database-operations → data-engineer
- rag-pipeline-architecture → llm-architect
- embedding-model-selection → ml-engineer
- knowledge-graph-design → knowledge-engineer
## Tooling
### Memory_frameworks
- LangMem (LangChain) - When: LangGraph agents with persistent memory Note: Semantic, episodic, procedural memory types
- MemGPT / Letta - When: Virtual context management, OS-style memory Note: Hierarchical memory tiers, automatic paging
- Mem0 - When: User memory layer for personalization Note: Designed for user preferences and history
### Vector_stores
- Pinecone - When: Managed, enterprise-scale (billions of vectors) Note: Best query performance, highest cost
- Qdrant - When: Complex metadata filtering, open-source Note: Rust-based, excellent filtering
- Weaviate - When: Hybrid search, knowledge graph features Note: GraphQL interface, good for relationships
- ChromaDB - When: Prototyping, small/medium apps Note: Developer-friendly, ~20ms p50 at 100K vectors
- pgvector - When: Already using PostgreSQL, simpler setup Note: Good for <1M vectors, familiar tooling
### Embedding_models
- OpenAI text-embedding-3-large - When: Best quality, 3072 dimensions Note: $0.13/1M tokens
- OpenAI text-embedding-3-small - When: Good balance, 1536 dimensions Note: $0.02/1M tokens, 5x cheaper
- nomic-embed-text-v1.5 - When: Open-source, local deployment Note: 768 dimensions, good quality
- all-MiniLM-L6-v2 - When: Lightweight, fast local embedding Note: 384 dimensions, lowest latency
## Patterns
### Memory Type Architecture
Choosing the right memory type for different information
**When to use**: Designing agent memory system
# MEMORY TYPE ARCHITECTURE (CoALA Framework):
"""
Three memory types for different purposes:
1. Semantic Memory: Facts and knowledge
- What you know about the world
- User preferences, domain knowledge
- Stored in profiles (structured) or collections (unstructured)
2. Episodic Memory: Experiences and events
- What happened (timestamped events)
- Past conversations, task outcomes
- Used for learning from experience
3. Procedural Memory: How to do things
- Rules, skills, workflows
- Often implemented as few-shot examples
- "How did I solve this before?"
"""
## LangMem Implementation
"""
from langmem import MemoryStore
from langgraph.graph import StateGraph
# Initialize memory store
memory = MemoryStore(
connection_string=os.environ["POSTGRES_URL"]
)
# Semantic memory: user profile
await memory.semantic.upsert(
namespace="user_profile",
key=user_id,
content={
"name": "Alice",
"preferences": ["dark mode", "concise responses"],
"expertise_level": "developer",
}
)
# Episodic memory: past interaction
await memory.episodic.add(
namespace="conversations",
content={
"timestamp": datetime.now(),
"summary": "Helped debug authentication issue",
"outcome": "resolved",
"key_insights": ["Token expiry was root cause"],
},
metadata={"user_id": user_id, "topic": "debugging"}
)
# Procedural memory: learned pattern
await memory.procedural.add(
namespace="skills",
content={
"task_type": "debug_auth",
"steps": ["Check token expiry", "Verify refresh flow"],
"example_interaction": few_shot_example,
}
)
"""
## Memory Retrieval at Runtime
"""
async def prepare_context(user_id, query):
# Get user profile (semantic)
profile = await memory.semantic.get(
namespace="user_profile",
key=user_id
)
# Find relevant past experiences (episodic)
similar_experiences = await memory.episodic.search(
namespace="conversations",
query=query,
filter={"user_id": user_id},
limit=3
)
# Find relevant skills (procedural)
relevant_skills = await memory.procedural.search(
namespace="skills",
query=query,
limit=2
)
return {
"profile": profile,
"past_experiences": similar_experiences,
"relevant_skills": relevant_skills,
}
"""
### Vector Store Selection Pattern
Choosing the right vector database for your use case
**When to use**: Setting up persistent memory storage
# VECTOR STORE SELECTION:
"""
Decision matrix:
| | Pinecone | Qdrant | Weaviate | ChromaDB | pgvector |
|------------|----------|--------|----------|----------|----------|
| Scale | Billions | 100M+ | 100M+ | 1M | 1M |
| Managed | Yes | Both | Both | Self | Self |
| Filtering | Basic | Best | Good | Basic | SQL |
| Hybrid | No | Yes | Best | No | Yes |
| Cost | High | Medium | Medium | Free | Free |
| Latency | 5ms | 7ms | 10ms | 20ms | 15ms |
"""
## Pinecone (Enterprise Scale)
"""
from pinecone import Pinecone
pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
index = pc.Index("agent-memory")
# Upsert with metadata
index.upsert(
vectors=[
{
"id": f"memory-{uuid4()}",
"values": embedding,
"metadata": {
"user_id": user_id,
"timestamp": datetime.now().isoformat(),
"type": "episodic",
"content": memory_text,
}
}
],
namespace=namespace
)
# Query with filter
results = index.query(
vector=query_embedding,
filter={"user_id": user_id, "type": "episodic"},
top_k=5,
include_metadata=True
)
"""
## Qdrant (Complex Filtering)
"""
from qdrant_client import QdrantClient
from qdrant_client.models import PointStruct, Filter, FieldCondition
client = QdrantClient(url="http://localhost:6333")
# Complex filtering with Qdrant
results = client.search(
collection_name="agent_memory",
query_vector=query_embedding,
query_filter=Filter(
must=[
FieldCondition(key="user_id", match={"value": user_id}),
FieldCondition(key="type", match={"value": "semantic"}),
],
should=[
FieldCondition(key="topic", match={"any": ["auth", "security"]}),
]
),
limit=5
)
"""
## ChromaDB (Prototyping)
"""
import chromadb
client = chromadb.PersistentClient(path="./memory_db")
collection = client.get_or_create_collection("agent_memory")
# Simple and fast for prototypes
collection.add(
ids=[str(uuid4())],
embeddings=[embedding],
documents=[memory_text],
metadatas=[{"user_id": user_id, "type": "episodic"}]
)
results = collection.query(
query_embeddings=[query_embedding],
n_results=5,
where={"user_id": user_id}
)
"""
### Chunking Strategy Pattern
Breaking documents into retrievable chunks
**When to use**:Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.