Multi-layered AI memory system with graph databases, vector stores, and intelligent processing pipelines
pip install smartmemory-core==1.4.129 Copy PIP instructions
Read the docs · Compare vs Mem0 / Zep / Letta / claude-mem · Maya sample app
SmartMemory is an AI memory system with five core typed memory types — episodic, semantic, procedural, pending (short-term, formerly "working"), and zettelkasten — instead of a single vector store. It combines a knowledge graph (FalkorDB), vector embeddings, and an observable 11-stage extraction pipeline so LLM agents can remember, reason over relationships, and update structured knowledge across sessions and tools.
SmartMemory's memory types fall into two cohorts. The knowledge layer (semantic, episodic, procedural, zettel) stores what's true. The expertise layer (decision, constraint, learned, opinion, reasoning, observation) stores what to do — and what not to do. The expertise layer is what makes the substrate useful for acting, not just recalling: captured choices, rejected alternatives, hard constraints, lessons learned. See Expertise vs Knowledge for the full mapping and recall channel.
pip install smartmemory # Everything: local memory + MCP server + graph viewer + CLI pip install smartmemory-core[lite] # Core library only, local mode (for developers) pip install smartmemory-core[server] # Core library only, server mode (FalkorDB + Redis) smartmemory is the distribution package. A single install bundles smartmemory-core[lite] (local SQLite + usearch storage), the unified MCP server, the graph viewer, and the CLI — there is no separate [local] extra. You pick local or remote mode at smartmemory setup time, not at install time. smartmemory-core is the core library for developers building on top of SmartMemory.
from smartmemory.tools.factory import create_lite_memory, lite_context # Simple usage — full LLM extraction runs if OPENAI_API_KEY is set memory = create_lite_memory() item_id = memory.ingest("Alice leads Project Atlas") results = memory.search("who leads Atlas", top_k=5) # Preferred in scripts — cleans up globals and closes SQLite on exit with lite_context() as memory: item_id = memory.ingest("Alice leads Project Atlas") results = memory.search("who leads Atlas") # Force no LLM calls (even if OPENAI_API_KEY is set) from smartmemory.pipeline.config import PipelineConfig memory = create_lite_memory(pipeline_profile=PipelineConfig.lite(llm_enabled=False)) Or via CLI:
smartmemory-core add "Alice leads Project Atlas" smartmemory-core search "who leads Atlas" smartmemory-core rebuild # Reindex vector store from graph data smartmemory-core watch /path/to/vault # Auto-ingest new/changed .md files Architecture Overview SmartMemory implements a multi-layered memory architecture with the following components:
classify → coreference → simplify → entity_ruler → llm_extract → ontology_constrain → store → link → enrich → ground → evolve Each stage implements the StageCommand protocol (execute(state, config) → state, undo(state) → state). The pipeline supports breakpoint execution (run_to(), run_from(), undo_to()) for debugging and resumption.
add() is simple storage: normalize → store → embed (use for internal/derived items).
# Lite mode (zero infra — SQLite + usearch, no Docker required) # Embeds with all-MiniLM-L6-v2 on ONNX Runtime: ~150 MB, sub-second cold start, no torch. pip install smartmemory-core[lite] # Server mode (FalkorDB + Redis, requires Docker or manual install; includes the torch stack) pip install smartmemory-core[server] # Embedding runtime (same model, same vectors — pick by hardware) pip install smartmemory-core[torch] # sentence-transformers on CPU (previous default) pip install smartmemory-core[gpu] # sentence-transformers; CUDA used automatically when visible pip install smartmemory-core[rerank] # Cross-encoder reranker (needs torch) # Optional features pip install smartmemory-core[cli] # CLI tools pip install smartmemory-core[watch] # Vault watcher for Markdown files pip install smartmemory-core[wikipedia] # Wikipedia enrichment pip install smartmemory-core[all] # All optional features Models and hermetic startup Entity extraction needs a spaCy model, and local embedding needs the MiniLM weights. The library never installs anything at import time: create_lite_memory() raises MissingModelError naming the exact command when a model is absent. Pass auto_download_models=True to let it fetch them (the smartmemory CLI does this during smartmemory setup).
python -m spacy download en_core_web_sm SMARTMEMORY_HF_ALLOW_DOWNLOAD=1 python -c "from smartmemory.plugins.embedding import EmbeddingService; EmbeddingService().embed('warm')" The embedding backend is auto-detected at first use: torch with CUDA, then torch on CPU, then ONNX Runtime. Vectors are identical across backends, so a store written by one opens with any other. Force one with SMARTMEMORY_EMBEDDING_BACKEND=onnx|torch|auto.
The first time a SmartMemory() is constructed in a process, the runtime asks https://api.smartmemory.ai/memory/lite/update-check once whether a newer release is published. If there is one, it logs a single line on the smartmemory.update_check logger. Nothing is printed to stdout and nothing blocks: the request runs on a daemon thread with a 2 second timeout. Operational failures only log a warning naming what was lost; they never interrupt construction.
No memory content, no file paths, no hostname, no username, and no IP-derived identity are sent. The install id is random and is never derived from your hardware. At most one request is made per 24 hours per install.
To turn it off, set either SMARTMEMORY_NO_UPDATE_CHECK=1 or the cross-tool DO_NOT_TRACK=1. Setting SMARTMEMORY_UPDATE_CHECK_URL to an empty string also disables it, and the check is skipped automatically when a CI environment variable is present.
See the licensing documentation for redistribution terms and the update-check disclosure.
Lite mode (smartmemory-core[lite]): No external services needed. SQLite and usearch are bundled.
Server mode (smartmemory-core[server]): Requires FalkorDB and Redis:
# Docker Compose (recommended) — from repository root docker-compose up -d # Starts FalkorDB on port 9010, Redis on port 9012 # Or manually docker run -d -p 9010:6379 falkordb/falkordb:latest docker run -d -p 9012:6379 redis:7-alpine # Verify redis-cli -p 9010 PING # FalkorDB redis-cli -p 9012 PING # Redis 🎯 Quick Start Basic Usage (Lite Mode) from smartmemory.tools.factory import create_lite_memory # No Docker, no config — just works memory = create_lite_memory() # Ingest a memory (full pipeline: extract → store → link → enrich → evolve) item_id = memory.ingest("User prefers Python for data analysis tasks") # Or use add() for simple storage without pipeline item = MemoryItem( content="Quick note about Python", memory_type="semantic", metadata={'topic': 'preferences'} ) memory.add(item) # Search memories (automatically scoped) results = memory.search("Python programming", top_k=5) for result in results: print(f"Content: {result.content}") print(f"Type: {result.memory_type}") # Get memory summary summary = memory.get_all_items_debug() print(f"Total memories: {summary['total_items']}") Using Different Memory Types from smartmemory import SmartMemory, MemoryItem # Initialize SmartMemory memory = SmartMemory() # Add pending memory (short-term context awaiting consolidation) pending_item = MemoryItem( content="Current conversation context", memory_type="pending" ) memory.add(pending_item) # Add semantic memory (facts and concepts) semantic_item = MemoryItem( content="Python is a high-level programming language", memory_type="semantic" ) memory.add(semantic_item) # Add episodic memory (experiences) episodic_item = MemoryItem( content="User completed Python tutorial on 2024-01-15", memory_type="episodic" ) memory.add(episodic_item) # Add procedural memory (skills and procedures) procedural_item = MemoryItem( content="To sort a list in Python: use list.sort() or sorted(list)", memory_type="procedural" ) memory.add(procedural_item) # Add Zettelkasten note (interconnected knowledge) zettel_item = MemoryItem( content="# Machine Learning\n\nML learns from data using algorithms.", memory_type="zettel", metadata={'title': 'ML Basics', 'tags': ['ai', 'ml']} ) memory.add(zettel_item) CLI Usage (Optional) # Install CLI tools pip install smartmemory-core[cli] # Add a memory smartmemory-core add "Python is great for AI" # Add without creating a markdown file smartmemory-core add "Quick note" --no-markdown # Search memories smartmemory-core search "Python programming" --top-k 5 # Search with JSON output smartmemory-core search "Python programming" --json # Rebuild the vector index from graph data smartmemory-core rebuild # Auto-ingest new/changed Markdown files from a vault directory pip install smartmemory-core[watch] smartmemory-core watch /path/to/vault Use Cases Conversational AI Systems Maintain context across multiple conversation sessions Learn user preferences and adapt responses Build comprehensive user profiles over time Educational Applications Track learning progress and adapt teaching strategies Remember previous topics and build upon them Personalize content based on individual learning patterns Knowledge Management Store and retrieve complex information relationships Connect related concepts across different domains Evolve understanding through continuous learning Build a personal knowledge base with Zettelkasten method Personal AI Assistants Remember user preferences and past interactions Provide contextually relevant recommendations Learn from user feedback to improve responses Examples The examples/ directory contains a broader set of demonstration scripts than the highlights below. See examples/README.md for the full catalog and setup notes.
SmartMemory uses environment variables for configuration:
Dedicated vector domains (optional, default off): SmartMemory can route a domain's embeddings into its own vector collection + embedder instead of the shared semantic_memory collection. Each flag is read at registry-build time; flip it on only after the collection is populated, so dev/CI never load the specialized model.
When a flag is on, an unscoped search() automatically fans out to that collection and RRF-merges its hits with the base results (scoped/memory_type= queries are unaffected).
# Lite mode — only API key needed (optional, enables LLM extraction) export OPENAI_API_KEY=your-api-key-here # Server mode — also needs database hosts export FALKORDB_HOST=localhost export FALKORDB_PORT=9010 export REDIS_HOST=localhost export REDIS_PORT=9012 Memory Evolution SmartMemory includes built-in evolvers that automatically transform memories. In lite mode, evolution runs incrementally in the background — memories evolve as they're added, not just at the end of each pipeline run.
Core evolvers — memory type transitions and lifecycle:
Enhanced evolvers — neuroscience-inspired dynamics:
Sleep-cycle & agent evolvers — opt-in background re-derivation (REM/NREM analogs):
Replaced by ConsolidationRouter (CORE-MEMORY-DYNAMICS-1 M1):
Evolvers run automatically as part of the memory lifecycle. See the examples directory for evolution demonstrations.
SmartMemory features a unified, extensible plugin architecture that allows you to customize and extend functionality. All plugins follow a consistent class-based pattern.
SmartMemory auto-registers a small set of built-in plugins at startup, with additional specialist plugins available for opt-in use:
Auto-registered by default (loaded by PluginManager._load_builtin_plugins):
Specialist plugins (selected by pipeline stage, opt-in feature, or the Studio evolver catalog — not auto-run in the idle cycle):
Two registries coexist by design: a small eager, auto-run set (above) that runs in the idle/batch evolution cycle, and a lazy catalog of ~40 evolvers (evolution/registry.py) that Studio can select into workflow DAGs without importing every class at boot. Auto-run ⊆ catalog is an enforced invariant.
Create your own plugins by extending the base classes:
from smartmemory.plugins.base import EnricherPlugin, PluginMetadata class MyCustomEnricher(EnricherPlugin): @classmethod def metadata(cls): return PluginMetadata( name="my_enricher", version="1.0.0", author="Your Name", description="My custom enricher", plugin_type="enricher", dependencies=["some-lib>=1.0.0"], security_profile="standard", requires_network=False, requires_llm=False ) def enrich(self, item, node_ids=None): # Your enrichment logic item.metadata["custom_field"] = "value" return item.metadata See the examples directory for complete plugin examples.
Publish your plugin as a Python package with entry points:
# pyproject.toml [project.entry-points."smartmemory.plugins.enrichers"] my_enricher = "my_package:MyCustomEnricher" Install and use:
pip install my-smartmemory-plugin # Automatically discovered and loaded! Plugin Types ExtractorPlugin: Extract entities and relationships from text EnricherPlugin: Add metadata and context to memories GrounderPlugin: Link memories to external knowledge sources EvolverPlugin: Transform memories based on conditions All plugins are automatically discovered and registered at startup.
SmartMemory includes a comprehensive security system for plugins:
# Plugins are secure by default PluginMetadata( security_profile="standard", # Balanced security requires_network=True, # Explicitly declare requirements requires_llm=False ) See the full documentation for complete security documentation.
See the examples/ directory for complete plugin examples:
# Run all tests PYTHONPATH=. pytest -v tests/ # Run specific test categories PYTHONPATH=. pytest tests/unit/ PYTHONPATH=. pytest tests/integration/ PYTHONPATH=. pytest tests/e2e/ # Run examples PYTHONPATH=. python examples/memory_system_usage_example.py PYTHONPATH=. python examples/conversational_assistant_example.py API Reference Progress Event Bus (PLAT-PROGRESS-1) Unified progress emission via Redis Streams. Producers call emit(); consumers subscribe over SSE via /memory/progress/stream (see smart-memory-service). Stream key: sm:progress: ; Redis DB 1; MAXLEN default 10_000 (override via SMARTMEMORY_PROGRESS_MAXLEN).
from smartmemory.progress import bind, unbind, bound_progress, emit # One emit anywhere in the process writes a ProgressEvent to the # caller's workspace stream. run_id + scope come from contextvars set # by bind() / bound_progress(); never passed as kwargs. # Simple request-scoped pattern bind(run_id="abc-123", scope="workspace:team-42") try: emit(kind="pipeline.stage", status="progress", stage="extract", payload={"progress": 50, "message": "Extracting entities"}) finally: unbind() # Context-managed pattern — preferred for background tasks that run in # a fresh asyncio context (e.g. FastAPI BackgroundTasks). bind() # bindings in the scheduling handler don't propagate. with bound_progress(run_id="abc-123", scope="workspace:team-42"): emit(kind="pipeline.stage", status="ok", stage="extract", payload={"progress": 100, "message": "Completed extraction"}) Status values: started | progress | ok | warn | error | skipped. Kinds are dotted producer-owned tags (pipeline.stage, evolver.result, studio.job, …); the transport has no registry.
class SmartMemory: def __init__( self, scope_provider: Optional[ScopeProvider] = None, vector_backend=None, # Any VectorStoreBackend; None uses default (FalkorDB) cache=None, # Any cache-compatible object; e.g. NoOpCache() observability: bool = True, # False disables Redis Streams emission and metrics pipeline_profile=None, # PipelineConfig instance; PipelineConfig.lite() for zero-infra entity_ruler_patterns=None, # Any object with get_patterns() -> dict[str, str] ) # Primary API def ingest(self, item, sync=True, **kwargs) -> str # Full pipeline def add(self, item, **kwargs) -> str # Simple storage def get(self, item_id: str) -> Optional[MemoryItem] def search( self, query: str, top_k: int = 5, memory_type: str = None, origin: str = None, # prefix filter, e.g. "user" decompose_query: bool = False, # split compound queries multi_hop: bool = False, # chained recursive retrieval semantic_hops: bool = False, # LLM-driven hop planning expertise: bool = False, # typed-dict expertise channel include_superseded: bool = False, as_of_date=None, # bi-temporal time travel (datetime | ISO-8601) ) -> List[MemoryItem] def delete(self, item_id: str) -> bool # Expertise-layer capture def add_decision(self, content: str, **kwargs) -> str def add_constraint(self, content: str, **kwargs) -> str def add_learning(self, content: str, **kwargs) -> str def add_opinion(self, content: str, subject: str, **kwargs) -> str def add_observation(self, entity_id: str, fact_id: str, aspect: str = None) -> str def add_reasoning(self, trace, source_item_id: str = None, **kwargs) -> str # Graph Integrity (v0.3.8+) def delete_run(self, run_id: str) -> int # Delete entities by pipeline run def rename_entity_type(self, old: str, new: str) -> int # Ontology evolution def merge_entity_types(self, sources: List[str], target: str) -> int # Advanced def run_clustering(self) -> dict def run_evolution_cycle(self) -> None def personalize(self, traits: dict = None, preferences: dict = None) -> None def get_all_items_debug(self) -> Dict[str, Any] # Lifecycle def close(self) -> None # Clean shutdown (optional) API Design:
@dataclass class MemoryItem: content: str memory_type: str = 'semantic' item_id: str = field(default_factory=lambda: str(uuid.uuid4())) valid_start_time: Optional[datetime] = None valid_end_time: Optional[datetime] = None transaction_time: datetime = field(default_factory=datetime.now) embedding: Optional[List[float]] = None entities: Optional[list] = None relations: Optional[list] = None metadata: dict = field(default_factory=dict) Security Metadata:
SmartMemory requires the following key dependencies:
Lite mode adds: usearch (vector search), uses Python's built-in sqlite3.
Server mode adds: falkordb (graph + vector storage), redis (caching).
# Modes pip install smartmemory-core[lite] # Zero-infra local mode (SQLite + usearch, no Docker) pip install smartmemory-core[server] # Server mode (FalkorDB + Redis) # Tools pip install smartmemory-core[cli] # Command-line interface (add, search, rebuild) pip install smartmemory-core[watch] # Vault watcher for auto-ingesting Markdown files # Integrations pip install smartmemory-core[slack] # Slack integration pip install smartmemory-core[aws] # AWS integration pip install smartmemory-core[wikipedia] # Wikipedia enrichment # Everything pip install smartmemory-core[all] # All optional features Feedback Bug reports and feature requests are welcome at support@smartmemory.ai.
SmartMemory Lite is distributed as a compiled runtime under the SmartMemory Lite Runtime License (see LICENSE).
The hosted service and platform are licensed separately.
SmartMemory takes plugin security seriously. All plugins run in a sandboxed environment with:
External plugins use the standard security profile by default.
pip install smartmemory Explore the examples directory for complete demonstrations and use cases.
See CHANGELOG.md for complete version history.
Check the documentation for the latest updates.
Search uses lexical with default weight 0.8. Replace removed contains and keyword-bm25 channel weights explicitly. A zero weight disables lexical, and omission preserves the existing default/profile behavior. Required lexical unavailability fails the whole search. Service callers receive 400 for query/name validation and 503 for unavailable indexes.
Lite is single-tenant. Graph-first retrieval conditionally fills from FTS5 lexical and vector search. Bounded refill can underfill, and regex-text still scans. CORE-FACT-INDEX-1 separately owns deferred fact ranking and path expansion.
Quiesce old writers before first-open indexing. Verify the engine capability pin and use sm rebuild --lexical for recovery. Migration, targets and measured limitations.
onnx torch gpu llm ml server coreference stats rerank code benchmarks docs slack aws wikipedia cli lite watch dev all
ai memory graph-database vector-database llm knowledge-graph semantic-memory episodic-memory rag embeddings
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Enable javascript to be able to filter the list of wheel files.
Yanked reason: Superseded by coordinated SmartMemory 1.4.39 lockstep release; no external users.




