### Minimal Async Example with ERS Source: https://github.com/drqedwards/ers/blob/main/README.md Demonstrates the basic usage of EnhancedReconsiderationSystem, adding memory blocks, chaining promises, and deferring memory for reconsideration in an asynchronous environment. Loads saved state if present. ```python import asyncio from ERS import EnhancedReconsiderationSystem, MemoryBlock, ERSPromise async def main(): ers = EnhancedReconsiderationSystem() # loads saved state if present await ers.add_memory("Paris is the capital of France") mem1 = MemoryBlock("Paris is the capital of France") await ers.add_memory("Paris is the largest city in France") mem2 = MemoryBlock("Paris is the largest city in France") ers.chain_promises(ERSPromise(mem1), ERSPromise(mem2)) ers.defer_memory(mem1) ers.defer_memory(mem2) ``` -------------------------------- ### Initialize and Use EnhancedReconsiderationSystem Source: https://context7.com/drqedwards/ers/llms.txt Demonstrates the initialization of the EnhancedReconsiderationSystem, adding memories, retrieving them, detecting contradictions, reconsidering memory confidence, deferring memories, and finally shutting down to save state. ```python import asyncio from ERS2 import EnhancedReconsiderationSystem, MemoryBlock async def main(): # Constructor loads saved state if present; starts fresh otherwise ers = EnhancedReconsiderationSystem(embedding_model='all-MiniLM-L6-v2') # INFO: No state file found - starting fresh # INFO: ERS initialized # Add memories; returns SHA-256 hash for later retrieval h1 = await ers.add_memory("Paris is the capital of France", source_quality=0.9, volatility=0.1) h2 = await ers.add_memory("Paris is not the capital of France", source_quality=0.4, volatility=0.5) h3 = await ers.add_memory("Lyon is a major city in France", source_quality=0.6, volatility=0.2) # INFO: Memory added: 3a2f8b1c... (confidence: 1.00) # Retrieve by hash mem1 = ers.memory_store.get(h1) mem2 = ers.memory_store.get(h2) print(mem1.content) # Paris is the capital of France # Check contradiction between two memories score = await ers.detect_contradiction(mem1, mem2) print(f"Contradiction: {score:.2f}") # ~0.80 (high sim + opposing negation) # Reconsider a single memory (decay + consensus + contradiction) conf, contradictions = await ers.reconsider_memory(mem1) print(f"New confidence: {conf:.3f}, contradictions found: {len(contradictions)}") # Defer a memory for later multi-pass processing mem3 = ers.memory_store.get(h3) ers.defer_memory(mem3, initial_score=0.5) print(f"Status: {mem3.status}") # DEFERRED # Process all deferred memories recursively (up to MAX_RECURSION_DEPTH=5 passes) await ers.reconsider_deferred() # Shutdown: saves ers_state.json + ers_lattice.safetensors await ers.close() # INFO: State saved to disk # INFO: ERS closed asyncio.run(main()) ``` -------------------------------- ### MemoryBlock Initialization and Serialization Source: https://context7.com/drqedwards/ers/llms.txt Demonstrates how to create a MemoryBlock instance, access its properties, and serialize/deserialize it to/from a dictionary for persistence. ```APIDOC ## MemoryBlock ### Description Core memory unit with integrity hashing. Encapsulates text content, confidence score, timestamps, source parameters, embeddings, access counters, and hashes. Supports serialization via `to_dict()` and `from_dict()`. ### Class `MemoryBlock` ### Methods #### `__init__` ```python MemoryBlock( content: str, confidence: float = 1.0, source_quality: float = 1.0, volatility: float = 0.0, embedding: Optional[np.ndarray] = None, access_count: int = 0, prev_hash: Optional[str] = None, status: str = 'ACTIVE' ) ``` #### `to_dict()` Serializes the MemoryBlock instance to a dictionary. #### `from_dict(data: dict)` Deserializes a dictionary into a MemoryBlock instance. ### Request Example ```python from ERS2 import MemoryBlock import numpy as np # Create a memory block mem = MemoryBlock( content="Paris is the capital of France", source_quality=0.9, volatility=0.1 ) # Serialize to dict (for JSON persistence) d = mem.to_dict() # Deserialize from dict mem2 = MemoryBlock.from_dict(d) ``` ### Response Example ```python # Properties of mem: # mem.hash[:16] -> SHA-256 integrity hash (first 16 chars) # mem.confidence -> 1.0 (starts at full confidence) # mem.status -> 'ACTIVE' # Keys in the dictionary representation: # dict_keys(['content', 'confidence', 'timestamp', 'source_quality', # 'volatility', 'access_count', 'prev_hash', 'hash', 'status', 'embedding']) ``` ``` -------------------------------- ### Create and Serialize MemoryBlock Source: https://context7.com/drqedwards/ers/llms.txt Demonstrates creating a MemoryBlock instance with content and source parameters, and serializing it to a dictionary for JSON persistence. Shows how to deserialize it back into a MemoryBlock object. ```python from ERS2 import MemoryBlock import numpy as np # Create a memory block mem = MemoryBlock( content="Paris is the capital of France", source_quality=0.9, # 0–1, higher = more reliable source volatility=0.1 # 0–1, higher = changes more frequently ) print(mem.hash[:16]) # SHA-256 integrity hash (first 16 chars) print(mem.confidence) # 1.0 (starts at full confidence) print(mem.status) # 'ACTIVE' # Serialize to dict (for JSON persistence) d = mem.to_dict() print(d.keys()) # dict_keys(['content', 'confidence', 'timestamp', 'source_quality', # 'volatility', 'access_count', 'prev_hash', 'hash', 'status', 'embedding']) # Deserialize from dict mem2 = MemoryBlock.from_dict(d) assert mem2.content == mem.content assert mem2.hash == mem.hash ``` -------------------------------- ### Ingest and Embed New Memory with add_memory Source: https://context7.com/drqedwards/ers/llms.txt Shows how to use the `add_memory` method to ingest content, generate its embedding, and store it. It also demonstrates retrieving the stored memory and checking its properties. ```python import asyncio from ERS2 import EnhancedReconsiderationSystem async def main(): ers = EnhancedReconsiderationSystem() # Returns the SHA-256 hash of the new block hash_id = await ers.add_memory( "Rome is the capital of Italy", source_quality=0.95, volatility=0.05 ) print(f"Stored with hash: {hash_id}") # Retrieve the block mem = ers.memory_store.get(hash_id) print(f"Content: {mem.content}") print(f"Embedding shape: {mem.embedding.shape}") # (384,) print(f"Prev hash set: {mem.prev_hash is not None}") # True if >1 block await ers.close() asyncio.run(main()) ``` -------------------------------- ### FullERS.save_state() and FullERS.load_state() Source: https://context7.com/drqedwards/ers/llms.txt Persists the full corpus, all MemoryBlock objects, and the deferred queue to a JSON file. The fitted TF-IDF vectorizer, SVD, and petal weights are serialized to a companion .models.pkl file using pickle, allowing exact inference reproduction after reload without refitting. ```APIDOC ## FullERS.save_state() / FullERS.load_state() ### Description Persists the full corpus, all `MemoryBlock` objects, and the deferred queue to a JSON file. The fitted TF-IDF vectorizer, SVD, and petal weights are serialized to a companion `.models.pkl` file using pickle, allowing exact inference reproduction after reload without refitting. ### Method - `save_state(filepath: str)`: Saves the current state to the specified JSON file. - `load_state(filepath: str)`: Loads the state from the specified JSON file. ### Parameters #### `save_state` Parameters - **filepath** (str) - Required - The path to the JSON file where the state will be saved. #### `load_state` Parameters - **filepath** (str) - Required - The path to the JSON file from which the state will be loaded. ### Request Example ```python from FULLER_ERS import FullERS import os ers = FullERS() ers.add_memory("Water boils at 100 degrees Celsius", source_quality=1.0) ers.add_state("Ice melts at 0 degrees Celsius", source_quality=1.0) ers.save_state('/tmp/science_ers.json') # Files created: assert os.path.exists('/tmp/science_ers.json') assert os.path.exists('/tmp/science_ers.json.models.pkl') # Load in a new session ers2 = FullERS() ers2.load_state('/tmp/science_ers.json') print(f"Memories restored: {len(ers2.memory_store)}") results = ers2.query("boiling point of water") print(results[0][2]) ``` ### Response #### Success Response (200) - `save_state`: No explicit return value, but files are created. - `load_state`: No explicit return value, but the ERS instance is populated with the loaded state. #### Response Example ``` Memories restored: 2 Water boils at 100 degrees Celsius ``` ``` -------------------------------- ### Calculate Time-Decayed Confidence with temporal_decay Source: https://context7.com/drqedwards/ers/llms.txt Illustrates the `temporal_decay` method for calculating a memory block's effective confidence over time. It shows how memory quality and volatility affect decay rates. ```python import asyncio, time from ERS2 import EnhancedReconsiderationSystem, MemoryBlock async def main(): ers = EnhancedReconsiderationSystem() # High-quality, low-volatility memory decays slowly h = await ers.add_memory("Water boils at 100°C", source_quality=1.0, volatility=0.0) mem = ers.memory_store.get(h) conf_now = await ers.temporal_decay(mem) print(f"Confidence now: {conf_now:.4f}") # ~1.0000 (just added) # Simulate 24 hours later conf_day = await ers.temporal_decay(mem, t=time.time() + 86400) print(f"Confidence in 24h: {conf_day:.4f}") # Slightly below 1.0 # High-volatility, low-quality memory decays faster h2 = await ers.add_memory("Stock price is $150", source_quality=0.3, volatility=0.9) mem2 = ers.memory_store.get(h2) conf_volatile = await ers.temporal_decay(mem2, t=time.time() + 86400) print(f"Volatile conf in 24h: {conf_volatile:.4f}") # Much lower asyncio.run(main()) ``` -------------------------------- ### EnhancedReconsiderationSystem Methods Source: https://github.com/drqedwards/ers/blob/main/README.md Core methods for interacting with the ERS, managing memory, and controlling the reconsideration process. ```APIDOC ## EnhancedReconsiderationSystem ### Description Provides the main interface for the Enhanced Reconsideration System. ### Methods - **add_memory(text, metadata=None)**: Adds a MemoryBlock, processes embeddings, and integrates it into the Knowledge Graph (KG) and Mem0. - **defer_memory(memory_block, score=None)**: Defers a given MemoryBlock for later reconsideration, optionally with a specified score. - **reconsider_deferred()**: Asynchronously processes the queue of deferred memories for reconsideration. - **recursive_loop_check()**: Asynchronously performs a multi-pass reconsideration of memory slots to ensure consistency and completeness. - **chain_promises(*promises)**: Links multiple ERSPromise objects together to create a chain of operations. - **close()**: Saves the current state of the ERS, including JSON state files and safetensors checkpoints. ``` -------------------------------- ### ERS Core Operations Source: https://github.com/drqedwards/ers/blob/main/README.md Demonstrates the core asynchronous operations for reconsidering deferred memories, checking for recursive loops, and closing the system to save state. ```python await ers.reconsider_deferred() await ers.recursive_loop_check() await ers.close() # saves state/backups ``` ```python asyncio.run(main()) ``` -------------------------------- ### RTM Double-Pass Pipeline Pseudocode Source: https://github.com/drqedwards/ers/blob/main/RTM.md Illustrates a high-level flow for a double-pass RTM pipeline, including memory decay, neighbor retrieval, consensus computation, contradiction detection, rewrite proposal, and embedding refinement. ```pseudocode for pass in 1..passes: for slot in memory_slots: decay(slot) neighbours = find_related(slot.embedding) consensus = compute_consensus(neighbours) if detect_contradiction(slot, neighbours): proposal = propose_rewrite(slot, consensus) if acceptance_policy(proposal, slot, neighbours): commit_rewrite(slot, proposal) slot.embedding = reembed(slot.text) # or refinement via lattice ``` -------------------------------- ### EnhancedReconsiderationSystem.reconsider_memory() Source: https://context7.com/drqedwards/ers/llms.txt Performs a full reconsideration pipeline for a single memory block. This includes applying temporal decay, finding related memories, computing consensus, detecting contradictions, and adjusting confidence. It returns the new confidence score and a list of detected contradiction scores. ```APIDOC ## EnhancedReconsiderationSystem.reconsider_memory() ### Description Runs the complete reconsideration pipeline for one block: temporal decay → find related → compute consensus → detect contradictions → apply confidence penalty. Contradicted neighbours are marked `'CONTRADICTED'`. Returns `(new_confidence, list_of_contradiction_scores)`. ### Method `async` ### Parameters - **memory**: `MemoryBlock` - The memory block to reconsider. ### Response - **new_confidence**: `float` - The updated confidence score for the memory block. - **contradictions**: `list` - A list of contradiction scores detected between the reconsidered memory and its neighbours. ### Request Example ```python import asyncio from ERS2 import EnhancedReconsiderationSystem async def main(): ers = EnhancedReconsiderationSystem() h1 = await ers.add_memory("Paris is the capital of France", source_quality=0.9) h2 = await ers.add_memory("Paris is not the capital of France", source_quality=0.3) mem1 = ers.memory_store.get(h1) new_conf, contradictions = await ers.reconsider_memory(mem1) print(f"New confidence: {new_conf:.3f}") print(f"Contradictions found: {len(contradictions)}") mem2 = ers.memory_store.get(h2) print(f"Contradicted block status: {mem2.status}") await ers.close() asyncio.run(main()) ``` ### Response Example ``` New confidence: 0.750 Contradictions found: 1 Contradicted block status: CONTRADICTED ``` ``` -------------------------------- ### add_memory Source: https://context7.com/drqedwards/ers/llms.txt Ingests and embeds new memory content. It adds the content as a MemoryBlock, chains it, computes its embedding, processes it through the PMLLLattice, and stores it in the MemoryStore. Returns the SHA-256 hash of the new block. ```APIDOC ## EnhancedReconsiderationSystem.add_memory() ### Description Adds content as a `MemoryBlock`, appends it to the blockchain-like chain (setting `prev_hash`), computes its sentence-transformer embedding, processes the embedding through the `PMLLLattice`, and stores the block in the `MemoryStore`. ### Method `async add_memory(content: str, source_quality: float, volatility: float) -> str` ### Parameters - **content** (str): The text content of the memory. - **source_quality** (float): The quality of the source of the memory (0.0 to 1.0). - **volatility** (float): The volatility of the memory (0.0 to 1.0). ### Returns - **str**: The SHA-256 hash of the newly added memory block. ``` -------------------------------- ### EnhancedReconsiderationSystem Source: https://context7.com/drqedwards/ers/llms.txt The main async orchestrator for the Enhanced Reconsideration System. It loads persisted state on construction, making sessions stateful. All memory operations are managed through this class. ```APIDOC ## EnhancedReconsiderationSystem ### Description The primary async orchestrator. On construction it loads previously persisted state from `ers_state.json` (queue + memory store) and `ers_lattice.safetensors` (lattice tensors), making a previously stateless session stateful. All memory operations go through this class. ### Methods - `__init__(embedding_model: str)`: Initializes the ERS, loading state if available. - `add_memory(content: str, source_quality: float, volatility: float)`: Adds a new memory, returning its hash. - `detect_contradiction(memory1: MemoryBlock, memory2: MemoryBlock)`: Detects contradictions between two memories. - `reconsider_memory(memory: MemoryBlock)`: Reconsiders a single memory, returning its new confidence and contradictions. - `defer_memory(memory: MemoryBlock, initial_score: float)`: Defers a memory for later processing. - `reconsider_deferred()`: Processes all deferred memories recursively. - `close()`: Shuts down the ERS, saving its state. ``` -------------------------------- ### Reconsider a single memory block Source: https://context7.com/drqedwards/ers/llms.txt Runs the full reconsideration pipeline for a memory block, including temporal decay, finding related memories, computing consensus, and detecting contradictions. Contradicted neighbors are flagged. Returns new confidence and contradiction scores. ```python import asyncio from ERS2 import EnhancedReconsiderationSystem async def main(): ers = EnhancedReconsiderationSystem() h1 = await ers.add_memory("Paris is the capital of France", source_quality=0.9) h2 = await ers.add_memory("Paris is not the capital of France", source_quality=0.3) mem1 = ers.memory_store.get(h1) new_conf, contradictions = await ers.reconsider_memory(mem1) print(f"New confidence: {new_conf:.3f}") print(f"Contradictions found: {len(contradictions)}") # Check neighbour was flagged mem2 = ers.memory_store.get(h2) print(f"Contradicted block status: {mem2.status}") # CONTRADICTED await ers.close() asyncio.run(main()) ``` -------------------------------- ### PMLLLattice for Embedding Processing with AttentionFlower Source: https://context7.com/drqedwards/ers/llms.txt Wraps an AttentionFlower module to transform and L2-normalize sentence embeddings. Supports safetensors checkpointing for reproducibility. Used internally by EnhancedReconsiderationSystem.add_memory(). ```python import asyncio, torch from ERS2 import PMLLLattice async def main(): lattice = PMLLLattice(hidden_dim=384, rank=64) # Process a single embedding vector raw_emb = torch.randn(1, 384) # (batch=1, dim=384) processed = await lattice.process_embedding(raw_emb) print(processed.shape) # torch.Size([1, 384]) print(processed.norm(dim=-1)) # tensor([1.0000]) — L2 normalized # Save and reload checkpoint lattice.state['sample_tensor'] = processed lattice.save_checkpoint('/tmp/lattice.safetensors') lattice2 = PMLLLattice(hidden_dim=384) lattice2.load_checkpoint('/tmp/lattice.safetensors') print('sample_tensor' in lattice2.state) # True asyncio.run(main()) ``` -------------------------------- ### Find related memories using cosine similarity Source: https://context7.com/drqedwards/ers/llms.txt Retrieves memories with cosine similarity above SIM_THRESHOLD. Ensure EnhancedReconsiderationSystem is initialized and memories are added. ```python import asyncio from ERS2 import EnhancedReconsiderationSystem async def main(): ers = EnhancedReconsiderationSystem() h1 = await ers.add_memory("Paris is the capital of France") h2 = await ers.add_memory("France's capital city is Paris") # Very similar h3 = await ers.add_memory("Tokyo is the capital of Japan") # Dissimilar mem1 = ers.memory_store.get(h1) related = await ers.find_related(mem1) for hash_id, sim in related: m = ers.memory_store.get(hash_id) print(f"sim={sim:.3f} '{m.content}'") # sim=0.923 'France's capital city is Paris' # (Tokyo block is below 0.7 threshold, not returned) await ers.close() asyncio.run(main()) ``` -------------------------------- ### EnhancedReconsiderationSystem.detect_contradiction() Source: https://context7.com/drqedwards/ers/llms.txt Detects semantic contradiction between two memory blocks. It uses embedding similarity and negation heuristics to provide a score indicating the likelihood of contradiction. ```APIDOC ## EnhancedReconsiderationSystem.detect_contradiction() ### Description Detects logical contradiction between two `MemoryBlock` instances using cosine similarity and negation-keyword heuristics. High embedding similarity combined with opposing negation patterns (e.g., one block contains "not") yields a score near 0.8. ### Method `async` ### Parameters - **memory1**: `MemoryBlock` - The first memory block. - **memory2**: `MemoryBlock` - The second memory block. ### Response - **contradiction_score**: `float` - A score indicating the degree of contradiction, typically near 0.8 for direct contradictions and lower for unrelated memories. ### Request Example ```python import asyncio from ERS2 import EnhancedReconsiderationSystem async def main(): ers = EnhancedReconsiderationSystem() h1 = await ers.add_memory("Paris is the capital of France") h2 = await ers.add_memory("Paris is not the capital of France") h3 = await ers.add_memory("Tokyo is the capital of Japan") mem1, mem2, mem3 = (ers.memory_store.get(h) for h in (h1, h2, h3)) score_contra = await ers.detect_contradiction(mem1, mem2) print(f"Direct contradiction: {score_contra:.2f}") score_unrelated = await ers.detect_contradiction(mem1, mem3) print(f"Unrelated contradiction: {score_unrelated:.2f}") await ers.close() asyncio.run(main()) ``` ### Response Example ``` Direct contradiction: 0.80 Unrelated contradiction: 0.10 ``` ``` -------------------------------- ### AttentionFlower Multi-petal Attention Module Source: https://context7.com/drqedwards/ers/llms.txt Implements radial multi-head attention using multiple independent linear projections with ReLU activations, then averaging. Used within PMLLLattice and can be used standalone for embedding refinement. ```python import torch from ERS2 import AttentionFlower flower = AttentionFlower(num_petals=8, hidden_dim=384) x = torch.randn(4, 384) # batch of 4 embeddings, dim=384 out = flower(x) print(out.shape) # torch.Size([4, 384]) # Count parameters params = sum(p.numel() for p in flower.parameters()) print(f"Parameters: {params:,}") # 8 * (384*384 + 384) = ~1.18M ``` -------------------------------- ### RTM Configuration Options for ERS Source: https://github.com/drqedwards/ers/blob/main/RTM.md Suggested configuration parameters for RTM integration within ERS, controlling recursive passes, stopping criteria, and rewrite limits. ```yaml rtm: passes: 2 early_stop_cosine_delta: 0.002 max_rewrites_per_slot: 1 decay_alpha: 0.95 ``` -------------------------------- ### MemoryStore In-memory Similarity Index Source: https://context7.com/drqedwards/ers/llms.txt Stores MemoryBlock instances indexed by hash and supports cosine-similarity nearest-neighbor lookups. Used by EnhancedReconsiderationSystem for find_related() operations. ```python from ERS2 import MemoryStore, MemoryBlock import numpy as np store = MemoryStore() m1 = MemoryBlock("Paris is the capital of France") m1.embedding = np.random.randn(384).astype('float32') m1.embedding /= np.linalg.norm(m1.embedding) m2 = MemoryBlock("France capital is Paris") m2.embedding = m1.embedding + np.random.randn(384) * 0.05 # Very similar m2.embedding /= np.linalg.norm(m2.embedding) store.add(m1) store.add(m2) # Retrieve by hash retrieved = store.get(m1.hash) print(retrieved.content) # Paris is the capital of France # Find similar (cosine sim > 0.7 threshold by default) similar = store.find_similar(m1.embedding, threshold=0.7) for hash_id, sim in similar: print(f"sim={sim:.4f} {store.get(hash_id).content}") ``` -------------------------------- ### ERS Full State Persistence Source: https://context7.com/drqedwards/ers/llms.txt Saves the entire ERS state, including memories and models, to disk and loads it in a new session. Ensures exact inference reproduction without refitting. ```python from FULLER_ERS import FullERS import os ers = FullERS() ers.add_memory("Water boils at 100 degrees Celsius", source_quality=1.0) ers.add_memory("Ice melts at 0 degrees Celsius", source_quality=1.0) ers.save_state('/tmp/science_ers.json') # Files created: assert os.path.exists('/tmp/science_ers.json') assert os.path.exists('/tmp/science_ers.json.models.pkl') # Load in a new session ers2 = FullERS() ers2.load_state('/tmp/science_ers.json') print(f"Memories restored: {len(ers2.memory_store)}") # 2 results = ers2.query("boiling point of water") print(results[0][2]) # Water boils at 100 degrees Celsius ``` -------------------------------- ### EnhancedReconsiderationSystem.find_related() Source: https://context7.com/drqedwards/ers/llms.txt Retrieves a list of memories from the store that are semantically similar to a given memory, based on cosine similarity. It returns tuples of (hash_id, cosine_similarity) for memories exceeding a specified threshold. ```APIDOC ## EnhancedReconsiderationSystem.find_related() ### Description Returns a list of `(hash_id, cosine_similarity)` tuples for memories in the store whose embedding cosine similarity exceeds `SIM_THRESHOLD` (default 0.7), excluding the query memory itself. ### Method `async` ### Parameters - **memory**: `MemoryBlock` - The memory block to find related memories for. - **SIM_THRESHOLD**: `float` (optional) - The minimum cosine similarity threshold. Defaults to 0.7. ### Response - **list**: A list of tuples, where each tuple contains `(hash_id, cosine_similarity)`. ### Request Example ```python import asyncio from ERS2 import EnhancedReconsiderationSystem async def main(): ers = EnhancedReconsiderationSystem() h1 = await ers.add_memory("Paris is the capital of France") h2 = await ers.add_memory("France's capital city is Paris") h3 = await ers.add_memory("Tokyo is the capital of Japan") mem1 = ers.memory_store.get(h1) related = await ers.find_related(mem1) for hash_id, sim in related: m = ers.memory_store.get(hash_id) print(f"sim={sim:.3f} '{m.content}'") await ers.close() asyncio.run(main()) ``` ### Response Example ``` sim=0.923 'France\'s capital city is Paris' ``` ``` -------------------------------- ### FullERS Synchronous ERS with TF-IDF Source: https://context7.com/drqedwards/ers/llms.txt A dependency-light, synchronous ERS implementation using TF-IDF, TruncatedSVD, and random linear projections for embeddings. No GPU required. Full corpus re-embedding occurs on each add_memory() call. ```python from FULLER_ERS import FullERS ers = FullERS() # Add memories (synchronous; no async needed) i1 = ers.add_memory("Paris is the capital of France", source_quality=0.9, volatility=0.1) i2 = ers.add_memory("Paris is the largest city in France", source_quality=0.7, volatility=0.3) i3 = ers.add_memory("Lyon is a major city in France", source_quality=0.6, volatility=0.2) ``` -------------------------------- ### Compute weighted consensus from related memories Source: https://context7.com/drqedwards/ers/llms.txt Aggregates confidence from related memories using similarity-weighted, age-discounted voting. The result is a consensus confidence float in [0, 1]. Requires related memories to be pre-computed. ```python import asyncio from ERS2 import EnhancedReconsiderationSystem async def main(): ers = EnhancedReconsiderationSystem() h1 = await ers.add_memory("Paris is the capital of France", source_quality=0.9) h2 = await ers.add_memory("The capital of France is Paris", source_quality=0.85) h3 = await ers.add_memory("Paris is in France", source_quality=0.7) mem1 = ers.memory_store.get(h1) related = await ers.find_related(mem1) # [(h2, sim), (h3, sim)] consensus = await ers.compute_consensus(mem1, related) print(f"Consensus score: {consensus:.4f}") # High value since all agree asyncio.run(main()) ``` -------------------------------- ### Lazy Embedding Computation with Caching Source: https://context7.com/drqedwards/ers/llms.txt Shows how to compute and cache sentence-transformer embeddings for a MemoryBlock's content using an asynchronous method. Subsequent calls to get_embedding will return the cached result without re-encoding. ```python import asyncio from sentence_transformers import SentenceTransformer from ERS2 import MemoryBlock async def demo(): embedder = SentenceTransformer('all-MiniLM-L6-v2') mem = MemoryBlock("The Eiffel Tower is in Paris") emb = await mem.get_embedding(embedder) print(emb.shape) # (384,) print(emb[:5]) # Normalized float32 values # Second call returns cached result emb2 = await mem.get_embedding(embedder) assert (emb == emb2).all() asyncio.run(demo()) ``` -------------------------------- ### RTMMemory Source: https://context7.com/drqedwards/ers/llms.txt Standalone RTM persistent memory with reconsideration. Implements the Recursive Transformer Model memory specification: persistent memory slots with temporal decay, cosine-similarity retrieval, consensus voting, contradiction detection, and a `reconsider()` method that penalizes contradicted entries and adds updated knowledge. ```APIDOC ## RTMMemory ### Description `RTMMemory` is a standalone class implementing the Recursive Transformer Model memory specification: persistent memory slots with temporal decay, cosine-similarity retrieval, consensus voting, contradiction detection, and a `reconsider()` method that penalizes contradicted entries and adds updated knowledge. ### Methods - `add_memory(content: str, embedding: torch.Tensor)`: Adds a new memory entry. - `retrieve(query_embedding: torch.Tensor)`: Retrieves memories based on a query embedding. - `reconsider(query_embedding: torch.Tensor, new_content: str, new_embedding: torch.Tensor)`: Penalizes contradicted memories and adds new knowledge. ### Parameters #### Initialization Parameters - **embed_dim** (int) - The dimension of the embeddings. - **lambda0** (float) - Base decay rate. - **alpha** (float) - Access reinforcement weight. - **tau_sim** (float) - Similarity threshold for related memories. - **tau_c** (float) - Contradiction threshold. #### `add_memory` Parameters - **content** (str) - The textual content of the memory. - **embedding** (torch.Tensor) - The embedding vector for the memory. #### `retrieve` Parameters - **query_embedding** (torch.Tensor) - The embedding vector for the query. #### `reconsider` Parameters - **query_embedding** (torch.Tensor) - The embedding vector for the query. - **new_content** (str) - The textual content of the new or updated memory. - **new_embedding** (torch.Tensor) - The embedding vector for the new or updated memory. ### Request Example ```python import torch import time from TRM_RTM import RTMMemory mem = RTMMemory( embed_dim=64, lambda0=0.01, # Base decay rate alpha=0.1, # Access reinforcement weight tau_sim=0.7, # Similarity threshold for related memories tau_c=0.5 # Contradiction threshold ) # Add memories with their embeddings e1 = torch.randn(1, 1, 64) e2 = torch.randn(1, 1, 64) mem.add_memory("The sky is blue", e1) mem.add_memory("The ocean is blue", e2) # Retrieve: returns aggregate embedding + consensus confidence query = torch.randn(1, 1, 64) agg_emb, conf = mem.retrieve(query) print(f"Aggregate embedding shape: {agg_emb.shape}") print(f"Confidence: {conf:.3f}") # Reconsideration: penalizes contradicted memories, adds new entry new_emb = torch.randn(1, 1, 64) mem.reconsider(query, "Updated observation", new_emb) print(f"Total memories: {len(mem.memories)}") ``` ### Response #### Success Response - `add_memory`: No explicit return value. - `retrieve`: Returns a tuple containing the aggregate embedding and consensus confidence. - `reconsider`: No explicit return value. #### Response Example ``` Aggregate embedding shape: torch.Size([1, 1, 64]) Confidence: 0.650 Total memories: 3 ``` ``` -------------------------------- ### ERS Memory Operations Source: https://context7.com/drqedwards/ers/llms.txt Demonstrates core ERS memory operations: reconsidering individual memories, deferring and batch processing, performing text similarity queries, and persisting/restoring the ERS state. ```python conf, contradictions = ers.reconsider_memory(i1) print(f"Memory {i1} confidence: {conf:.3f}, contradictions: {len(contradictions)}") ``` ```python ers.defer_memory(i3, initial_score=0.4) ers.reconsider_deferred(max_depth=5) mem3 = ers.memory_store.memories[i3] print(f"Memory {i3} status: {mem3.status}") # RESOLVED ``` ```python results = ers.query("capital of France", top_k=3, threshold=0.0) for sim, idx, content in results: print(f"sim={sim:.3f} '{content}'") # sim=0.921 'Paris is the capital of France' # sim=0.654 'Paris is the largest city in France' ``` ```python ers.save_state('/tmp/full_ers_state.json') # Saved: /tmp/full_ers_state.json + /tmp/full_ers_state.json.models.pkl ``` ```python from FULLER_ERS import FullERS as FullERS2 ers2 = FullERS2() ers2.load_state('/tmp/full_ers_state.json') results2 = ers2.query("capital of France") print(results2[0][2]) # Paris is the capital of France ``` -------------------------------- ### ERSPromise Object Source: https://github.com/drqedwards/ers/blob/main/README.md Facilitates asynchronous operation chaining within the ERS. ```APIDOC ## ERSPromise ### Description An object used for managing and chaining asynchronous operations within the ERS. ### Methods - **resolve()**: Resolves the promise, executing its associated operation. - **then(next_promise)**: Chains another ERSPromise to be executed after the current one resolves. ``` -------------------------------- ### RTMMemory Standalone Operations Source: https://context7.com/drqedwards/ers/llms.txt Manages persistent memory slots with temporal decay, similarity retrieval, and contradiction detection. Supports adding memories, retrieving aggregate embeddings, and reconsidering/updating entries. ```python import torch import time from TRM_RTM import RTMMemory mem = RTMMemory( embed_dim=64, lambda0=0.01, # Base decay rate alpha=0.1, # Access reinforcement weight tau_sim=0.7, # Similarity threshold for related memories tau_c=0.5 # Contradiction threshold ) # Add memories with their embeddings e1 = torch.randn(1, 1, 64) e2 = torch.randn(1, 1, 64) mem.add_memory("The sky is blue", e1) mem.add_memory("The ocean is blue", e2) # Retrieve: returns aggregate embedding + consensus confidence query = torch.randn(1, 1, 64) agg_emb, conf = mem.retrieve(query) print(f"Aggregate embedding shape: {agg_emb.shape}") # torch.Size([1, 1, 64]) print(f"Confidence: {conf:.3f}") # Reconsideration: penalizes contradicted memories, adds new entry new_emb = torch.randn(1, 1, 64) mem.reconsider(query, "Updated observation", new_emb) print(f"Total memories: {len(mem.memories)}") # 3 ``` -------------------------------- ### temporal_decay Source: https://context7.com/drqedwards/ers/llms.txt Calculates the time-decayed confidence of a memory block. It applies adaptive exponential decay, modulated by source quality, volatility, and access reinforcement, simulating memory consolidation. ```APIDOC ## EnhancedReconsiderationSystem.temporal_decay() ### Description Computes the current effective confidence of a memory block by applying adaptive exponential decay modulated by source quality, volatility, and access reinforcement (mimicking memory consolidation). ### Method `async temporal_decay(memory: MemoryBlock, t: Optional[float] = None) -> float` ### Parameters - **memory** (MemoryBlock): The memory block to calculate confidence for. - **t** (Optional[float]): The timestamp at which to calculate the confidence. Defaults to the current time. ### Returns - **float**: The effective confidence of the memory block at the specified time. ``` -------------------------------- ### Detect semantic contradiction between memories Source: https://context7.com/drqedwards/ers/llms.txt Detects logical contradiction using cosine similarity and negation heuristics. Returns a score near 0.8 for direct contradictions and lower for unrelated memories. Ensure both MemoryBlock instances are valid. ```python import asyncio from ERS2 import EnhancedReconsiderationSystem async def main(): ers = EnhancedReconsiderationSystem() h1 = await ers.add_memory("Paris is the capital of France") h2 = await ers.add_memory("Paris is not the capital of France") h3 = await ers.add_memory("Tokyo is the capital of Japan") mem1, mem2, mem3 = (ers.memory_store.get(h) for h in (h1, h2, h3)) # Direct contradiction (same topic, opposing negation, high sim) score_contra = await ers.detect_contradiction(mem1, mem2) print(f"Direct contradiction: {score_contra:.2f}") # ~0.80 # Unrelated memories — low contradiction score_unrelated = await ers.detect_contradiction(mem1, mem3) print(f"Unrelated contradiction: {score_unrelated:.2f}") # ~0.10 await ers.close() asyncio.run(main()) ``` -------------------------------- ### EnhancedReconsiderationSystem.compute_consensus() Source: https://context7.com/drqedwards/ers/llms.txt Calculates a weighted consensus score for a given memory based on its related memories. The score is a float between 0 and 1, reflecting the agreement within the memory's neighbourhood, considering similarity and age. ```APIDOC ## EnhancedReconsiderationSystem.compute_consensus() ### Description Aggregates confidence from related memories using similarity-weighted, age-discounted voting. The result is a consensus confidence float in [0, 1] that reflects agreement from the neighbourhood. ### Method `async` ### Parameters - **memory**: `MemoryBlock` - The memory block for which to compute consensus. - **related_memories**: `list` - A list of tuples `(hash_id, cosine_similarity)` representing related memories. ### Response - **consensus_score**: `float` - A float in the range [0, 1] representing the consensus confidence. ### Request Example ```python import asyncio from ERS2 import EnhancedReconsiderationSystem async def main(): ers = EnhancedReconsiderationSystem() h1 = await ers.add_memory("Paris is the capital of France", source_quality=0.9) h2 = await ers.add_memory("The capital of France is Paris", source_quality=0.85) h3 = await ers.add_memory("Paris is in France", source_quality=0.7) mem1 = ers.memory_store.get(h1) related = await ers.find_related(mem1) consensus = await ers.compute_consensus(mem1, related) print(f"Consensus score: {consensus:.4f}") await ers.close() asyncio.run(main()) ``` ### Response Example ``` Consensus score: 0.8500 ``` ``` -------------------------------- ### HybridTRMRTM Source: https://context7.com/drqedwards/ers/llms.txt PyTorch model with persistent RTM memory. Combines Recursive Transformer Model (TRM) deep recursion with persistent RTM memory. On each forward pass it optionally queries the RTMMemory store to augment the input tensor, runs latent recursive refinement, and optionally updates memory with the output. ```APIDOC ## HybridTRMRTM ### Description `HybridTRMRTM` is a `torch.nn.Module` that combines Recursive Transformer Model (TRM) deep recursion with persistent RTM memory. On each forward pass it optionally queries the `RTMMemory` store to augment the input tensor, runs latent recursive refinement, and optionally updates memory with the output. ### Method - `__call__(x, query_content, query_embedding, update_memory)`: Performs a forward pass through the model. ### Parameters #### Input Parameters - **x** (torch.Tensor) - The input tensor. - **query_content** (str) - Optional content for the query. - **query_embedding** (torch.Tensor) - The embedding for the query. - **update_memory** (bool) - If True, the output is written back to RTM memory. ### Request Example ```python import torch from TRM_RTM import HybridTRMRTM d_model = 128 num_classes = 10 model = HybridTRMRTM(d_model=d_model, num_classes=num_classes, embed_dim=d_model) # Pre-populate memory model.memory.add_memory("Known fact A", embedding=torch.randn(1, 1, d_model)) model.memory.add_memory("Known fact B", embedding=torch.randn(1, 1, d_model)) # Forward pass: input augmented with retrieved memory, then TRM recursion x = torch.randn(1, 1, d_model) query_emb = torch.randn(1, 1, d_model) y_hat, q_hat = model( x, query_content="New observation", query_embedding=query_emb, update_memory=True # writes output back to RTM memory ) print(f"Logits shape: {y_hat.shape}") print(f"Halting prob: {q_hat.item():.3f}") # Retrieve aggregated memory embedding with confidence agg_emb, conf = model.memory.retrieve(query_emb) print(f"Retrieved conf: {conf:.3f}") ``` ### Response #### Success Response - **y_hat** (torch.Tensor): The output logits. - **q_hat** (torch.Tensor): The halting probability. #### Response Example ``` Logits shape: torch.Size([1, 1, 10]) Halting prob: 0.850 Retrieved conf: 0.750 ``` ``` -------------------------------- ### MemoryBlock Object Source: https://github.com/drqedwards/ers/blob/main/README.md Represents a single block of memory within the ERS, with methods for serialization and access to its fields. ```APIDOC ## MemoryBlock ### Description Represents an individual memory entry, including its content, metadata, and associated identifiers. ### Methods - **to_dict()**: Serializes the MemoryBlock object into a dictionary. - **from_dict(data)**: Creates a MemoryBlock object from a dictionary. ### Fields - **id** (any): Unique identifier for the memory block. - **text** (string): The textual content of the memory. - **embedding** (any): The embedding vector associated with the text. - **confidence** (float): Confidence score of the memory. - **created_at** (datetime): Timestamp when the memory was created. - **updated_at** (datetime): Timestamp when the memory was last updated. - **sha256_hash** (string): SHA256 hash of the memory's content. - **kg_id** (any): Identifier in the Knowledge Graph. - **mem0_id** (any): Identifier in the Mem0 storage. ``` -------------------------------- ### HybridTRMRTM Model Forward Pass Source: https://context7.com/drqedwards/ers/llms.txt Utilizes a HybridTRMRTM model for augmented input processing with Recursive Transformer Model (TRM) and persistent RTM memory. Optionally queries memory, refines recursively, and updates memory. ```python import torch from TRM_RTM import HybridTRMRTM d_model = 128 num_classes = 10 model = HybridTRMRTM(d_model=d_model, num_classes=num_classes, embed_dim=d_model) # Pre-populate memory model.memory.add_memory("Known fact A", embedding=torch.randn(1, 1, d_model)) model.memory.add_memory("Known fact B", embedding=torch.randn(1, 1, d_model)) # Forward pass: input augmented with retrieved memory, then TRM recursion x = torch.randn(1, 1, d_model) query_emb = torch.randn(1, 1, d_model) y_hat, q_hat = model( x, query_content="New observation", query_embedding=query_emb, update_memory=True # writes output back to RTM memory ) print(f"Logits shape: {y_hat.shape}") # torch.Size([1, 1, 10]) print(f"Halting prob: {q_hat.item():.3f}") # 0.0–1.0; used for adaptive recursion depth # Retrieve aggregated memory embedding with confidence agg_emb, conf = model.memory.retrieve(query_emb) print(f"Retrieved conf: {conf:.3f}") ```