Intelligent modular memory management system for LLMs
Project description
MemBlocks
A Python library for modular, section-aware memory management in LLM applications
Overview
MemBlocks is a Python library that solves the context problem in LLM applications. Instead of dumping entire conversation histories or using flat RAG, MemBlocks organises memory into independent, attachable blocks — each scoped to a distinct knowledge domain (e.g., work, personal, academic) — with section-specific storage, retrieval, and update strategies.
This repository contains:
memblocks_lib/— The core Python librarybackend/— FastAPI REST API demo wrapping the libraryfrontend/— React web UI demo consuming the backendmcp_server/— MCP server integration for AI assistants (Claude Desktop, etc.)evaluation/— LoCoMo benchmark evaluation harness
The Problem
LLMs lose context over time. Current solutions either:
- Send full chat histories — expensive, hits token limits fast
- Use flat RAG — treats all memory the same, creates retrieval noise, no domain separation
The Solution
MemBlocks introduces memory blocks — independently attachable memory spaces, each partitioned into three structured sections:
| Section | Purpose | Retrieval |
|---|---|---|
| Core Memory | Persistent high-priority facts (persona, user attributes) | Always injected in full — no search needed |
| Semantic Memory | Extracted facts and events with conflict-aware deduplication | Hybrid dense + sparse (SPLADE) search with RRF reranking |
| Recursive Summary | Progressively compressed recent conversational state | Always injected in full — no search needed |
Memory updates are driven by background agentic workflows triggered when the sliding message window reaches its configured limit (default: 10 messages). Three workflows run in parallel: Core Memory extraction, Semantic Memory extraction with conflict resolution (ADD / UPDATE / DELETE / NOOP), and Recursive Summary regeneration.
Quick Start
Prerequisites
- Python 3.11+
- Docker & Docker Compose
- UV package manager
Setup
git clone https://github.com/Ashish-Pandey62/MemBlocks.git
cd MemBlocks
# Copy and fill in your API keys
cp .env.example .env
# Install all packages
uv sync --all-packages
# Start infrastructure (Qdrant on :6333, Ollama on :11434)
docker-compose up -d
Basic Usage
import asyncio
from memblocks import MemBlocksClient, MemBlocksConfig
async def main():
config = MemBlocksConfig() # reads from .env
client = MemBlocksClient(config)
# --- One-time setup ---
user = await client.get_or_create_user("alice")
block = await client.create_block(user_id="alice", name="Work Memory")
session = await client.create_session(user_id="alice", block_id=block.id)
# --- Per-turn loop ---
user_msg = "What did we decide about the API design?"
context = await block.retrieve(user_msg) # hybrid retrieval across all sections
messages = await session.get_memory_window() # last N conversation turns
summary = await session.get_recursive_summary() # compressed recent context
# Assemble prompt and call your own LLM
system = "You are a helpful assistant.\n\n" + context.to_prompt_string()
response = my_llm.chat(system, messages + [{"role": "user", "content": user_msg}])
# Persist the turn — triggers background memory workflows automatically
await session.add(user_msg=user_msg, ai_response=response)
await client.close()
asyncio.run(main())
Repository Structure
memblocks_lib/ # Core Python library
├── src/memblocks/
│ ├── client.py # MemBlocksClient — main API entry point
│ ├── config.py # MemBlocksConfig (Pydantic settings)
│ ├── services/ # block, session, core_memory, semantic_memory, memory_pipeline
│ ├── storage/ # MongoDBAdapter, QdrantAdapter, EmbeddingProvider
│ ├── llm/ # Provider integrations: Groq, OpenRouter, Gemini, Ollama
│ ├── models/ # Pydantic schemas (block, memory, retrieval, llm_outputs)
│ └── prompts/ # Agentic workflow prompts (PS1 extraction, PS2 resolution, summary)
backend/ # FastAPI REST API demo
├── src/api/
│ ├── main.py # FastAPI app entrypoint
│ ├── routers/ # blocks, chat, memory, users, auth, transparency
│ └── models/requests.py # Request schemas
mcp_server/ # MCP server for AI assistant integration
├── src/server.py
└── src/cli.py
frontend/ # React web UI demo
├── src/components/ # ChatInterface, BlockManager
└── src/api/ # API client
evaluation/ # LoCoMo benchmark harness
├── eval.py / locomo_eval.py
├── runners/
├── metrics/
└── datasets/
tests/ # Integration tests
docker-compose.yml # Qdrant + Ollama services
pyproject.toml # UV workspace config
API Reference
Initialization
from memblocks import MemBlocksClient, MemBlocksConfig
config = MemBlocksConfig() # reads .env; all fields have sensible defaults
client = MemBlocksClient(config)
User & Block Management
user = await client.get_or_create_user(user_id="alice")
block = await client.create_block(user_id="alice", name="Work", description="Work context")
blocks = await client.get_user_blocks(user_id="alice")
await client.delete_block(block_id=block.id, user_id="alice")
Session & Conversation
session = await client.create_session(user_id="alice", block_id=block.id)
context = await block.retrieve(user_msg) # full hybrid retrieval
messages = await session.get_memory_window() # sliding window of recent turns
summary = await session.get_recursive_summary() # compressed context
await session.add(user_msg=user_msg, ai_response=response) # persist + trigger pipeline
await session.flush() # force pipeline run immediately
Isolated Retrieval
core_ctx = await block.core_retrieve() # Core Memory only, no vector search
semantic_ctx = await block.semantic_retrieve(query) # Semantic Memory only
Transparency & Observability
client.subscribe("on_memory_extracted", callback)
client.subscribe("on_conflict_resolved", callback)
client.subscribe("on_core_memory_updated", callback)
client.get_retrieval_log() # per-query retrieval details
client.get_processing_history() # pipeline run history
client.get_llm_usage() # token usage + latency per task type
Configuration
Key environment variables (see .env.example for the full list):
# LLM provider (groq | openrouter | gemini | ollama)
LLM_PROVIDER_NAME=groq
GROQ_API_KEY=your_groq_key
OPENROUTER_API_KEY=your_openrouter_key
GEMINI_API_KEY=your_gemini_key
# Vector database
QDRANT_HOST=localhost
QDRANT_PORT=6333
# Embeddings (local)
OLLAMA_BASE_URL=http://localhost:11434
# Reranking
COHERE_API_KEY=your_cohere_key
# Memory pipeline behaviour
MEMORY_WINDOW=10 # messages before pipeline triggers
KEEP_LAST_N=4 # messages to retain after pipeline flush
# MongoDB
MONGO_URI=mongodb://localhost:27017
Per-task LLM configuration (optional):
from memblocks.llm.task_settings import LLMSettings, LLMTaskSettings
config = MemBlocksConfig(
llm_settings=LLMSettings(
default=LLMTaskSettings(provider="openrouter", model="meta-llama/llama-4-maverick"),
retrieval=LLMTaskSettings(provider="groq", model="llama-3.1-8b-instant"),
)
)
Running the Demo Applications
Backend API:
uv run python -m uvicorn backend.src.api.main:app --reload
Frontend:
cd frontend && npm install && npm run dev
MCP Server (configure in your AI assistant):
{
"mcp": {
"memblocks": {
"type": "local",
"command": ["uv", "run", "python", "-m", "mcp_server.server"],
"environment": {"MEMBLOCKS_USER_ID": "your_user_id"}
}
}
}
Evaluation:
uv run python evaluation/locomo_eval.py
Documentation
| Document | Description |
|---|---|
| Setup Guide | Installation, prerequisites, configuration, LLM providers, troubleshooting |
| API Reference | Complete methods and interfaces with usage examples |
| Technical Overview | Architecture, memory pipeline internals, data flow, DB schemas |
| Contributing | Dev environment setup, running tests, code style, PR process |
Running Tests
# Unit tests (no infrastructure needed)
uv run --package memblocks pytest tests/ -v
# Integration tests (requires live MongoDB + Qdrant)
uv run --package memblocks pytest -m integration -v
Authors
Built by Ashish Pandey, Ankit Mehta, and Aayush Ojha.
Project Repository
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file memblocks-0.1.0.tar.gz.
File metadata
- Download URL: memblocks-0.1.0.tar.gz
- Upload date:
- Size: 68.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
314aeea84f01e49b98d4f1bd6dbba04c1a0970c63c83a6f98aa6bde80f7699d3
|
|
| MD5 |
9acf47a3b6fbb81a7a24f8bdaa81517a
|
|
| BLAKE2b-256 |
523204849f8e9eafba2d161be577ee155ff120be9bc50494d83927b197506a27
|
Provenance
The following attestation bundles were made for memblocks-0.1.0.tar.gz:
Publisher:
publish.yml on Ashish-Pandey62/MemBlocks
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
memblocks-0.1.0.tar.gz -
Subject digest:
314aeea84f01e49b98d4f1bd6dbba04c1a0970c63c83a6f98aa6bde80f7699d3 - Sigstore transparency entry: 1719832776
- Sigstore integration time:
-
Permalink:
Ashish-Pandey62/MemBlocks@a841538e0a07e6316074afcf3e1103751dd71c1b -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/Ashish-Pandey62
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@a841538e0a07e6316074afcf3e1103751dd71c1b -
Trigger Event:
push
-
Statement type:
File details
Details for the file memblocks-0.1.0-py3-none-any.whl.
File metadata
- Download URL: memblocks-0.1.0-py3-none-any.whl
- Upload date:
- Size: 96.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b0c1b8ecdfc8e404111b24dad228cb088615e47156adb6de79609c8ec2f301ba
|
|
| MD5 |
a14f206446ba24ca88aaae37fbb2f5a7
|
|
| BLAKE2b-256 |
910ed2648f4940bc8f7cbe2db6b38bec91bdead0facf9bf159cbb49a017433c0
|
Provenance
The following attestation bundles were made for memblocks-0.1.0-py3-none-any.whl:
Publisher:
publish.yml on Ashish-Pandey62/MemBlocks
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
memblocks-0.1.0-py3-none-any.whl -
Subject digest:
b0c1b8ecdfc8e404111b24dad228cb088615e47156adb6de79609c8ec2f301ba - Sigstore transparency entry: 1719832955
- Sigstore integration time:
-
Permalink:
Ashish-Pandey62/MemBlocks@a841538e0a07e6316074afcf3e1103751dd71c1b -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/Ashish-Pandey62
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@a841538e0a07e6316074afcf3e1103751dd71c1b -
Trigger Event:
push
-
Statement type: