Overview
OpenFang’s memory substrate provides a unified API over three specialized storage backends, all backed by a single SQLite database. Agents interact with a singleMemory trait that abstracts over structured KV storage, semantic search, and knowledge graphs.
The entire memory system is synchronous at the storage layer (SQLite) but exposed via async APIs to the runtime. This allows non-blocking I/O while maintaining ACID guarantees.
The Three Layers
Structured Store
Key-value pairs, agent state, session persistence. Fast lookups by exact key.
Semantic Store
Text-based memory fragments with vector embeddings. Recalls relevant memories by similarity.
Knowledge Graph
Entities and relations extracted from conversations. Enables graph queries and reasoning.
Memory Substrate Architecture
- WAL mode (Write-Ahead Logging) for concurrent reads
- 5-second busy timeout to handle contention
- Foreign key constraints for referential integrity
- Automatic migrations on first open
1
Opening the Substrate
2
Schema Initialization
Tables are created for:
agents: Agent manifestssessions: Message history per agentkv_store: Key-value pairsmemory_fragments: Semantic memory with optional embeddingsentities: Knowledge graph nodesrelations: Knowledge graph edgesusage_log: Token usage and cost tracking
3
Ready for Use
The substrate is wrapped in
Arc<MemorySubstrate> and passed to the kernel and runtime.Layer 1: Structured Store
The structured store is a simple key-value store scoped by agent ID:Use Cases
Use Cases
- Agent state: Counters, flags, timestamps
- Hand metrics: Dashboard metrics (e.g.,
reports_count) - Configuration overrides: Per-agent settings
- Cached results: Expensive computations that don’t need semantic recall
Schema
Schema
Layer 2: Semantic Store
The semantic store holds memory fragments — snippets of text with optional vector embeddings for similarity search.Storing Memories
Recalling Memories
Text-Based Recall (No Embedding)
Text-Based Recall (No Embedding)
Uses SQLite full-text search (FTS5):This returns fragments ranked by:
- Keyword match score (BM25)
- Recency (newer memories rank higher)
- Access frequency (decay-based score)
Vector-Based Recall (With Embedding)
Vector-Based Recall (With Embedding)
If an embedding driver is available, OpenFang uses cosine similarity for more accurate recall:This computes cosine similarity between the query vector and all stored fragment vectors, returning the top K matches.
Schema
Schema
Vector Embeddings
OpenFang supports pluggable embedding drivers:- OpenAI (
text-embedding-3-small, 1536 dims) - Voyage AI (
voyage-2, 1024 dims) - Cohere (
embed-english-v3.0, 1024 dims) - Local Transformers (via
rust-bertcrate, offline)
openfang.toml:
Layer 3: Knowledge Graph
The knowledge store represents entities (nodes) and relations (edges) extracted from agent conversations.Entities
Relations
Graph Queries
Find Connected Entities
Find Connected Entities
Pattern Matching (Cypher-like)
Pattern Matching (Cypher-like)
(Person) -[works_for]-> (OpenAI) matches.Schema
Schema
Memory Consolidation
Over time, memory fragments accumulate. The consolidation engine runs periodically to:- Decay importance scores using exponential decay
- Merge similar fragments to reduce redundancy
- Delete low-importance memories below a threshold
- Compact embeddings by re-clustering and averaging
Decay Function
Decay Function
Importance decays exponentially based on time since last access:Default decay rate: 0.95 (95% retention per day, 50% after ~14 days)
Merge Heuristics
Merge Heuristics
Two fragments are merged if:
- Cosine similarity > 0.9 (for vector embeddings)
- Edit distance < 10% (for text-only)
- Same agent and source
Session Management
Every agent has sessions — isolated conversation threads:1
Create or Load Session
2
Append Messages
During the agent loop, messages are appended:
3
Save Session
Sessions are channel-scoped — an agent can have different sessions for Telegram vs Discord. This prevents context leakage across channels.
Usage Tracking
TheUsageStore records every LLM call:
Memory Limits & Auto-Trimming
To prevent unbounded growth:- Session trimming: When a session exceeds 20 messages, the oldest are removed (keeping the most recent context)
- Fragment pruning: During consolidation, fragments with importance < 0.1 are deleted
- Embedding cache: Only the most recent 10,000 embeddings are cached in memory
Import/Export
Export to JSON
Export to JSON
Import from JSON
Import from JSON
Next Steps
Memory API Reference
Full API documentation for memory operations
Agent Lifecycle
See how agents use memory during execution
Knowledge Graphs
Advanced guide to graph queries and entity extraction
Embeddings
Configure and optimize vector-based memory recall