1
Install Stalebrain and Dependencies
Begin by setting up your development environment. Stalebrain is distributed via PyPI, making installation straightforward for Python projects. Open your terminal and run the following command to install the core library along with its recommended dependencies for vector storage and serialization. Ensure you have Python 3.9 or higher installed, as Stalebrain leverages modern type hinting features for enhanced developer experience. If you are integrating this into an existing AI agent framework like LangChain or AutoGen, make sure those packages are also installed to facilitate seamless interoperability. After installation, verify the setup by importing the module in a local Python script to ensure no dependency conflicts arise during the initial import phase.
Pro Tip
Use a virtual environment (venv or conda) to avoid contaminating your global Python packages with Stalebrain's specific vector database requirements.
2
Initialize the Stalebrain Memory Store
The core of Stalebrain is its memory store, which mimics human cognitive structures. You need to initialize a `StalebrainStore` instance. This object manages the lifecycle of memories, handling their creation, retrieval, and eventual decay. Start by importing the `StalebrainStore` class and instantiating it with a configuration dictionary. You can specify parameters such as `max_capacity` (the maximum number of memories to store), `decay_rate` (how quickly memories lose relevance), and `embedding_model` (the model used to vectorize text for semantic search). For most local development, using a lightweight embedding model like `all-MiniLM-L6-v2` is recommended for speed, while production environments might prefer higher-accuracy models. The initialization process also sets up the underlying vector database, so ensure you have the necessary drivers installed for your chosen backend (e.g., ChromaDB or FAISS).
Pro Tip
Always define a unique `store_id` during initialization. This allows you to run multiple independent memory contexts within the same application without data leakage between different agents.
3
Ingesting Information into Memory
Once the store is initialized, you can start feeding it information. Stalebrain accepts structured or unstructured data. For unstructured text, use the `add_memory` method, which automatically tokenizes, embeds, and stores the information with a timestamp and a unique identifier. For structured data, you can pass a dictionary containing metadata fields such as `source`, `urgency`, and `category`. This metadata is crucial for the decay algorithm, as high-urgency items decay slower than low-urgency ones. When adding a memory, you can also specify a `ttl` (time-to-live) for explicit expiration if you want hard limits on retention. The system returns a `memory_id` which you should store in your agent's state to allow for direct updates or deletions later. Remember that every write operation triggers an embedding calculation, so batch adding memories when possible to optimize performance.
Pro Tip
Assign higher 'urgency' scores to critical facts or instructions. Stalebrain's decay algorithm uses this score to determine which memories to prune first when the store reaches capacity.
4
Retrieving Context with Semantic Search
Retrieval is where Stalebrain shines. Use the `query` method to retrieve relevant memories based on natural language queries. This method performs a semantic search using the embeddings generated during ingestion. You can tune the retrieval using parameters like `top_k` (number of results) and `similarity_threshold` (minimum cosine similarity score). The returned results are sorted by relevance, but also weighted by their current 'freshness' score. This means recent or highly urgent memories are prioritized over older, less relevant ones, mimicking human recall. The output is a list of memory objects, each containing the original text, metadata, and a relevance score. Integrate this retrieval step into your agent's loop before generating a response, ensuring the LLM has access to the most pertinent historical context without bloating the input token count.
Pro Tip
Set a dynamic `similarity_threshold` based on the query's specificity. Broad queries may need lower thresholds to capture diverse context, while specific lookups benefit from higher thresholds to avoid noise.
5
Configuring Decay and Forgetting Mechanisms
Stalebrain's unique value proposition is its active forgetting mechanism. You must configure the decay scheduler to manage memory lifecycle. Use the `configure_decay` method to set the global decay rate and pruning interval. The decay algorithm reduces the 'strength' of each memory over time. When a memory's strength falls below a certain threshold, or when the store exceeds `max_capacity`, Stalebrain automatically prunes the weakest memories. This prevents the context window from growing indefinitely and reduces computational costs for future retrievals. You can also manually trigger a `prune` operation if you need to enforce strict memory limits immediately. Understanding this mechanism is vital for long-running agents; without proper decay configuration, your agent may retain irrelevant noise, degrading performance over time. Monitor the `store_stats` method to visualize how memory density and average strength change over time.
Pro Tip
For long-running agents, schedule a background job to call `compact_memory` every few hours. This merges similar memories and removes expired ones, keeping the vector index lean and fast.
6
Integrating with an AI Agent Loop
Now, connect Stalebrain to your AI agent. In a typical ReAct or chain-of-thought loop, insert a retrieval step before the LLM generation phase. Pass the retrieved memories as part of the system prompt or context window. After the agent takes an action or receives new information, call `add_memory` to log the outcome. This creates a continuous feedback loop where the agent learns from its own history. Ensure that sensitive information is filtered out before being stored if you are dealing with PII. You can implement a pre-storage hook in Stalebrain to sanitize inputs. By integrating Stalebrain, your agent gains the ability to 'remember' past interactions and 'forget' irrelevant details, leading to more coherent and efficient long-term behavior. This setup transforms a stateless LLM call into a stateful, evolving agent.
Pro Tip
Limit the number of retrieved memories to 5-10 items per query. Too much context can overwhelm the LLM and increase latency. Stalebrain's relevance scoring helps you select the best few.
7
Monitoring and Debugging Memory Health
Finally, implement monitoring to ensure your memory system is healthy. Stalebrain provides a `get_stats` method that returns metrics such as total memories, average decay rate, and retrieval latency. Log these metrics periodically to detect anomalies, such as a sudden drop in retrieval accuracy or unexpected memory bloat. If you notice performance degradation, check if the `decay_rate` is too slow, causing the store to fill up with low-value data, or if the `embedding_model` is causing bottlenecks. Additionally, use the `debug_query` mode to inspect the raw vector distances and decay scores for specific queries. This helps in fine-tuning the retrieval thresholds. Regularly reviewing these stats ensures your agent remains efficient and responsive, even after running for weeks or months. This proactive maintenance is key to sustaining the benefits of cognitive memory management.
Pro Tip
Set up alerts for 'memory capacity' warnings. If the store consistently hits 90% capacity, consider increasing `max_capacity` or adjusting the decay rate to prune more aggressively.