Generated banner for membukkit
Generated logo for membukkit

membukkit

Memory serverOfficial Memseek project

Created by Memseek

Published in memseekai/membukkit. Publisher page

22 GitHub stars

What it is

Long-term memory for LLM apps that shows its work: dated facts, as-of answers, supersession, and receipts on every answer. Library, CLI, local GUI, MCP.
— the description by Memseek

AutoGineer overview, from the brain’s own files

MemBukkit is a memory layer for LLM applications designed to solve the problem of persistent, explainable knowledge. It transforms raw conversations and documents into dated atomic facts, maintaining a dual-lane index of atomic facts and verbatim source turns. When information changes, the system marks old facts as superseded rather than deleting them, allowing agents to perform temporal queries (e.g., 'what was true in May?'). Every answer generated by the system includes detailed receipts, providing transparency into the evidence used, source references, and cost metrics. The architecture is built for performance and explainability, utilizing bucketed retrieval to minimize token usage while maintaining high accuracy in knowledge-intensive tasks.

How it works

Memory model: Vector store

AutoGineer overview, from the brain’s own files

The system operates through a write path that distills input into dated atomic facts and verbatim turns, storing them in a flat embedding index. During the read path, a question is processed with an as-of date, triggering a budgeted search across topic buckets to retrieve relevant evidence. The system then generates an answer accompanied by receipts that detail the specific facts used, their status, and their source pointers.

Folders
FolderRoleFiles
.githubagent-config3
docsdocs32
examplesexamples7
scriptsscripts5
srcsource-code194
teststests41
benchmarksfolder61
notebooksfolder4
uifolder23

Requirements

Apps: Docker

Runtimes: Python >=3.10

API keys (by name): ANTHROPIC_API_KEY, COMPAT_API_KEY, GEMINI_API_KEY, OPENAI_API_KEY, TURBOPUFFER_API_KEY

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Google Antigravity, Kiro, OpenCode, Amp, Roo Code, Cline, JetBrains Junie, Devin (ex-Windsurf)

Set it up

  1. Not scanned by AutoGineerIts dependencies are installed by pip or uv when you run it and were not scanned by AutoGineer (6 declared). https://pypi.org/project/membukkit/
  2. Created by Memseek. Published in memseekai/membukkit. Licence: Apache License 2.0.

Usage

AutoGineer overview, from the brain’s own files

  • Python library integration for custom LLM applications
  • CLI tool for managing local memory stores
  • MCP server for connecting agents like Cursor or Claude Desktop to persistent memory
  • HTTP service for multi-tenant agent memory access
“How much is my rent?”
The agent returns the rent amount as of the specified date, citing the specific lease agreement or update note used as evidence.
“What did I decide about the migration?”
The agent retrieves the relevant dated facts from the memory store and provides a summary with a receipt showing the source conversation turn.

Documentation by Memseek

<p align="center"> <img src="https://raw.githubusercontent.com/memseekai/membukkit/main/logo.png" alt="MemBukkit" width="160"/> </p>

<h1 align="center">MemBukkit</h1>

<p align="center"> <a href="https://pypi.org/project/membukkit/"><img src="https://img.shields.io/pypi/v/membukkit?style=flat-square&color=3775a9&logo=pypi&logoColor=white" alt="PyPI"/></a> <a href="https://github.com/memseekai/membukkit/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/memseekai/membukkit/ci.yml?branch=main&style=flat-square&label=CI" alt="CI"/></a> <a href="https://github.com/memseekai/membukkit/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-blue?style=flat-square" alt="License"/></a> <a href="https://www.python.org/downloads/"><img src="https://img.shields.io/badge/python-3.10%2B-3776ab?style=flat-square&logo=python&logoColor=white" alt="Python"/></a> <a href="https://github.com/memseekai/membukkit/blob/main/docs/index.md"><img src="https://img.shields.io/badge/docs-guide-0d9488?style=flat-square" alt="Docs"/></a> </p>

MemBukkit is long-term memory for LLM apps that shows its work. It turns conversations and documents into dated atomic facts. When something changes (new rent, new job), the old fact is superseded, not deleted, so you can ask "what was true in May?" and get May's answer. Every answer ships with receipts: the facts used, where they came from, what the query cost. It sets the state of the art on LongMemEval-S under the benchmark's official judge, 92.6%, while reading a small fraction of the tokens full-context reading pays. Python, CLI, local GUI, HTTP, and MCP, all over the same stores. Apache-2.0.

<p align="center"> <a href="https://github.com/memseekai/membukkit/blob/main/docs/index.md">Docs</a> · <a href="https://github.com/memseekai/membukkit/blob/main/docs/guide/install.md">Install</a> · <a href="https://github.com/memseekai/membukkit/blob/main/docs/guide/quickstart.md">Quickstart</a> · <a href="https://github.com/memseekai/membukkit/blob/main/docs/guide/agents.md">Agents</a> · <a href="https://github.com/memseekai/membukkit/blob/main/docs/guide/mcp.md">MCP</a> · <a href="https://github.com/memseekai/membukkit/blob/main/docs/guide/demos.md">Demos</a> · <a href="https://github.com/memseekai/membukkit/blob/main/docs/guide/benchmarks.md">Benchmarks</a> </p>

<p align="center"> <img src="https://raw.githubusercontent.com/memseekai/membukkit/main/docs/assets/demo-ask.gif" alt="Ask with receipts" width="720"/> </p>


Try it in one line

uvx --from "membukkit[all]" membukkit ui --demo personal-assistant

That opens the GUI on a preloaded demo store. No clone, no venv, and Node is never needed because the GUI ships prebuilt. With pip it's pip install "membukkit[all]". Docker works too:

docker run -p 127.0.0.1:8377:8377 -v membukkit-data:/data -e OPENAI_API_KEY ghcr.io/memseekai/membukkit

It runs fully local. Point it at Ollama and nothing leaves your machine:

membukkit ask "what did I decide about the migration?" --store notes --llm ollama:llama3.1

Prefer a hosted model? Paste a key in the GUI, or export OPENAI_API_KEY=sk-.... Either way, the first ask downloads the retrieval weights once and caches them.

Every install path, including a dev clone: Install guide.

Python API

from membukkit import Memory

mem = Memory.from_pretrained(llm="openai:gpt-4o-mini")
mem.add("I signed a lease, rent is $2100.", subject="alex", date="2024-01-10")
mem.add("Landlord raised rent to $2300.", subject="alex", date="2024-03-01")

r = mem.ask("How much is my rent?", as_of="2024-06-01")
print(r.answer)             # truth as of that date
print(r.est_reader_tokens)  # ~tokens the reader saw
print(r.evidence[0].status, r.evidence[0].source_ref)  # current|superseded + citation

add returns a write receipt (n_stored, superseded, status), so empty LLM extracts never look like success. The full CLI walkthrough of the same flow is in the Quickstart.

How it works

Long-term memory is an indexing problem before it is a reading problem. What the store commits to at write time decides what any reader can possibly see later. Everything in MemBukkit follows from that.

flowchart LR
  subgraph W["write path"]
    S["sessions & documents"] --> D["LLM distillation"]
    D --> F["dated atomic facts<br/>+ source pointers"]
    S --> V["verbatim turns"]
  end
  F --> X[("flat embedding index<br/>+ topic buckets")]
  V --> X
  subgraph R["read path"]
    Q["question + as-of date"] --> B["budgeted bucket routing"]
    B --> K["top-k dated evidence"]
    K --> A["answer + receipts"]
  end
  X --> B

Writing. An LLM distills each session or document into dated atomic facts like 2024-01-08: rent is 800€, and the verbatim source turns are stored right next to them. Every fact keeps a pointer to its source. Why both? Because an extractor decides at write time what will matter later, and it is sometimes wrong. The atomic lane gives the system dates and updates it can reason about. The verbatim lane keeps everything the extractor skipped. When a new fact contradicts an old one, the old one is marked superseded instead of deleted. That is what makes "what was true in May?" answerable.

Indexing. Both lanes go into one flat embedding index, optionally split into topic buckets with plain KMeans. No LLM-built graph, no ontology, no summary hierarchy. Structures like those bake their builder's assumptions into the index, and revising them means rebuilding everything. Here the index builds in seconds with zero LLM calls, and changing how you retrieve is a config change, not a migration.

Reading. A question opens the closest topic buckets until a scan budget is covered, then the reader answers from the top evidence: dated, source-linked lines, filtered to what was known at the as-of date. It reads a small slice of memory instead of everything, and it answers better because of it. See Benchmarks for how much better.

Receipts. Every answer reports what it used and what it cost: tokens, estimated dollars, scan fraction, opened buckets, and each evidence line's status with its source turn or clause. The receipts are not decoration. In our research, hiding exactly the buckets a receipt names destroys the answer, while hiding random ones changes nothing. The trace really is the evidence trail.

Optional: a BM25 lexical lane. Everything above is dense retrieval, which is the shipped method and the one every number here was measured with. If your corpus is full of exact strings that embeddings blur together, error codes, filenames, rare identifiers, you can turn on a BM25 lane that searches the whole bank by term overlap and adds its hits to the routed pool before ranking. It is off by default and changes nothing until you ask for it:

from membukkit import Memory
from membukkit.config import RetrievalConfig

mem = Memory.from_pretrained(retrieval=RetrievalConfig(lexical_lane=True))

Needs pip install "membukkit[bm25]". How it fuses and what it costs: Library API.

Chosen by answer quality, not retrieval metrics

The research behind MemBukkit kept producing the same surprise: better retrieval did not mean better answers. Reading everything scored far below reading a routed slice. A stronger reranker did not beat plain cosine order. Extraction-heavy designs lost evidence that a flat two-lane index kept. So every retrieval policy that ships here was selected by one test: did the final answer get better?

That is also why nothing depends on our fine-tuned models. Swap in off-the-shelf weights, or an all open-weights stack, and the results hold. You are adopting an index design, not a checkpoint.

The numbers behind each of these claims are in Benchmarks below. The full mechanism is in Method, and a research paper is under review. For how MemBukkit compares to file notes, plain vector RAG, and temporal graphs as categories, see When to use.

Benchmarks

Every score here is graded by each benchmark's official judge, and every one is a frozen recipe that pins the reader, distiller, judge, encoder, and distillation cache. One command reruns it, and --check verifies your result against the expected band.

That first part is doing more work than it looks. Higher LongMemEval numbers exist, and they are graded by their own authors, in one case by the same model that wrote the answers. Under the official gpt-4o judge the field is MemBukkit 92.6, then Supermemory 85.2, then Zep 71.2. See who judges what.

Benchmark (what it stresses)StackScoreReproduce
LongMemEval-S (knowledge updates, temporal reasoning across sessions)gpt-5.4 reader, official gpt-4o judge92.6%membukkit bench --repro longmemeval-gpt54
LongMemEval-Sgpt-4o-mini reader82.0% (95% CI 78.6–85.4)membukkit bench --repro longmemeval-gpt4o-mini
LongMemEval-Sall open weights: gemma-4-26b reader + distiller88.8%membukkit bench --repro longmemeval-gemma
LoCoMo (Mem0's protocol and judge, zero retuning)gpt-4o-mini87.5%membukkit bench --repro locomo-mem0
BEAM (100K / 1M / 10M-token haystacks, official judge)gemma-4-26b0.535 / 0.498 / 0.447membukkit bench --repro beam-100k-gemma

What the research found, on LongMemEval-S (500 questions, official gpt-4o judge, paired comparisons sharing reader, judge, and ingestion):

  • Full-context reading scores 56.4% against MemBukkit's 82.0% with the same reader and judge, a +25.6 point gap (paired 95% CI [20.8, 30.4]), while MemBukkit reads ~3.2k tokens per question instead of ~100k.

  • Excluding the buckets an answer's receipt names collapses accuracy from 80.0% to 1.3%. Excluding a matched random set leaves it at 82.3%.

  • Given identical ingestion, extraction-only Mem0 scores 21.4% on questions answered in the assistant's own replies, where the verbatim lane scores 92.9%. Lane ablation: verbatim-only 75.4%, atomic-only 58.0%, both 82.8%.

  • Dropping the cross-encoder entirely and ranking the same opened region by plain cosine (83.4%, --rerank-select none) statistically ties the shipped hybrid config (82.0%, paired p=0.40). Swapping the fine-tuned encoder for an off-the-shelf one moves the score by just −0.4 (p=0.81). The reranker is tail insurance, not the headline.

Single-pass ask, no agentic re-query loops, official judges. LLM readers and judges are stochastic, so scores reproduce as bands, not bit-exact values. Judges, costs, and per-category breakdowns: Benchmarks guide.

Retrieval, measured directly

Answer quality is one thing, retrieval is another, so there is a second suite that grades retrieval alone with no LLM and no judge in the loop: HotpotQA multi-hop, 1,000 questions, scored against qmd by the same metric functions over the same candidate sets.

A multi-hop question needs two documents, and one of two is a miss, not half a success. On finding both, MemBukkit's document-retrieval path reaches 87.4% against qmd's best backend at 86.1% while answering in 47ms against 1,222ms. A heavier configuration, swapping in a 0.6B encoder and adding query decomposition driven by a local 1.7B model, reaches 90.8%. On the bridge questions that actually require two hops the gap is 88.4% against 82.3%. qmd stays a little ahead at putting one right document in first place, 93.2% against 92.1%, a difference inside sampling noise.

The same no-LLM treatment on conversational memory: session-level Recall@5 on the original LongMemEval-S split, the metric gbrain and MemPalace publish against. With gbrain's own embedding model (text-embedding-3-large) under MemBukkit's turn-level indexing and no reranker at all, 99.8% (499/500) against gbrain-hybrid's 97.6% and MemPalace's 96.6%, same dataset, same K, same n, no LLM in the loop, none of our fine-tuned weights involved. The as-shipped production cut with the same encoder scores 99.2%; with our 110M local encoder and zero API calls, 96.4%. Per-question rankings, a training-overlap disclosure for the shipped reranker, and the commands that regenerate every row are in benchmarks/longmemeval_session_recall/.

Read it with the setup, which is in the benchmark notes: those rows measure the document-retrieval configuration of the stack rather than the chunked path membukkit search runs today, the candidate sets are small enough that both systems saturate at k=10, and qmd's lexical backend scored zero on these long natural-language queries in a way that looks like a configuration artifact rather than a real result.

Known limits, so nothing surprises you later: distillation is an LLM call per session at write time (cached), so the cost moves rather than vanishing. Updates supersede rather than overwrite, so the old fact stays stored, which is what makes as-of queries possible; when you want a fact gone for real, delete it. And the distiller bounds the atomic lane: small local models extract weaker facts, and the verbatim lane limits the damage.

Bring your data

membukkit ui                                     # create a store → Ingest (drag & drop)
membukkit ingest ~/Downloads/WhatsAppChat.txt --store me   # or from the CLI
Drop thisHow you get it
WhatsApp .txtChat → Export → without media
ChatGPT / Claude ZIPSettings → Export data (or conversations.json)
PDFs / CRM CSV / notesHubSpot deals export, contracts, Notion MD zip, Obsidian folder, ./docs

Ask the same question at two dates and compare the receipts. Full steps per source: Bring your own.

MCP

A thin stdio server gives Cursor / Claude Desktop three tools over the same stores: memory_add, memory_search, memory_ask.

membukkit mcp --store notes

Client config and example prompts: MCP guide.

Surfaces

PieceRole
Memoryadd / search / ask / delete + write & ask receipts
CLI / GUIingest files, demos, explainability lab
Local v1 HTTP/api/v1/{store}/… for agents on disk stores
MCPCursor / Claude tools over the same stores

MemorySystem remains the full pipeline API. See Library API and Method.

Contributing & license

Contributions welcome, see CONTRIBUTING.md. Licensed under Apache-2.0.

docs/code-walkthrough.md

MEMBUKKIT Code Walkthrough

This document explains the main code paths in MEMBUKKIT: initialization, ingestion, storage, retrieval, query routing, answer generation, service APIs, CLI evaluation, and the supporting model/prompt layers. Public timestamp inputs accept datetime objects or ISO8601 strings; legacy slash-date strings remain supported for benchmarks and older callers.

The central object is MemorySystem. Most application code either constructs a MemorySystem, ingests conversation sessions into it, or asks it questions.

One-Page Schematic

flowchart TD
    INIT[MemorySystem.from_pretrained] --> MODELS[Load encoder, reranker, LLM backend]
    MODELS --> DISTILLER[Create FactDistiller]
    MODELS --> BACKEND[Create storage backend]

    INGEST[mem.ingest sessions + dates] --> TRANSCRIPT[Build numbered transcript]
    TRANSCRIPT --> EXTRACT[LLM distills atomic facts]
    EXTRACT --> RECORDS[FactRecord text, timestamp, entities, time bucket]
    RECORDS --> UPSERT[Backend upsert_facts]
    UPSERT --> EMBED[Embed new facts only]
    EMBED --> STORE[Store facts and vectors]
    STORE --> PARTITION[Lazy topic partition or persisted centroids]

    QUESTION[mem.answer question] --> ROUTER[Classify query type]
    ROUTER --> RETRIEVE[_retrieve]
    RETRIEVE --> CANDIDATES[Backend candidate generation]
    CANDIDATES --> RERANK[Cross-encoder utility scores]
    RERANK --> FUSION[Hybrid RRF with cosine, or xenc-only]
    FUSION --> FACTLINES[Chronological dated fact lines]
    FACTLINES --> READER[Reader prompt selected by query type]
    READER --> LLMANSWER[LLM answer]
    LLMANSWER --> NORMALIZE[Normalize N/I abstention]
    NORMALIZE --> RESULT[AnswerResult answer, trace, facts]

Public API

The package exports its main user-facing types in src/membukkit/__init__.py:

NamePurpose
MemorySystemMain stateful memory pipeline.
ModelConfigTells the system where encoder and reranker weights live.
RetrievalConfigControls bucket count, scan budgets, top-k, fusion, and service retrieval mode.
PromptConfigOptional prompt overrides.
StorageConfigChooses in-memory or Turbopuffer storage.
AnswerResultReturn object from mem.answer(...).
RetrievalTraceInspectable retrieval trace attached to an answer.

Typical usage:

from membukkit import MemorySystem, ModelConfig, RetrievalConfig, PromptConfig

mem = MemorySystem.from_pretrained(
    models=ModelConfig(model_dir="./models"),
    retrieval=RetrievalConfig(),
    llm="openai:gpt-4o-mini",
    prompts=PromptConfig.default(),
)

mem.ingest(
    sessions=[[{"role": "user", "content": "I switched to a vegan diet."}]],
    dates=["2024-06-01"],
)

res = mem.answer("What diet am I on?", question_date="2024-07-01")
print(res.answer)
print(res.facts)
print(res.trace)

Directory Map

PathRole
pipeline.pyMain MemorySystem pipeline.
config.pyDataclass configuration.
extraction/Session-to-atomic-fact distillation.
prompts/Prompt templates for extraction, reading, and eval protocols.
models/Encoder and cross-encoder reranker wrappers.
retrieval/Bucket construction, routing, query classification, filters.
storage/Backend abstraction, in-memory backend, Turbopuffer backend.
reading/Reader factories that turn facts into answer prompts.
llm/OpenAI, Anthropic, and local LLM adapters.
service/FastAPI multi-tenant service.
data/LongMemEval and LoCoMo dataset adapters.
eval/Evaluation harness and judge prompts.
cli.pymembukkit eval, training dispatchers, and membukkit serve.
telemetry.pyOptional Logfire/OpenTelemetry facade.

Initialization

Initialization usually starts at MemorySystem.from_pretrained.

flowchart LR
    CFG[ModelConfig RetrievalConfig PromptConfig StorageConfig] --> FP[from_pretrained]
    FP --> ENC[Encoder]
    FP --> RERANK[UtilityReranker]
    FP --> LLM[parse_llm_spec]
    FP --> DIST[FactDistiller]
    FP --> SYS[MemorySystem]
    SYS --> BACKEND[make_backend]

from_pretrained does five things:

  1. Resolves model paths through models/registry.py.

  2. Creates an Encoder, a lazy wrapper around SentenceTransformer.

  3. Loads a UtilityReranker, a CrossEncoder that scores (query, fact) pairs.

  4. Parses the LLM spec through llm/backends.py, for example openai:gpt-4o-mini.

  5. Creates a FactDistiller and a storage backend.

The backend is created by storage.make_backend:

Configuration

config.py defines four important dataclasses.

ModelConfig

  • model_dir: optional root for model weights.

  • encoder: encoder path or name.

  • reranker: reranker path or name.

  • device: optional device override.

RetrievalConfig

  • num_buckets: number of topic buckets to build.

  • scan_budget: fraction of memory to scan for normal topic routing.

  • scan_budget_reason: larger scan budget for reasoning queries.

  • scan_budget_temporal: optional override for temporal questions.

  • bucket_mode: topic, multiaxis, or fallback non-bucket retrieval.

  • select: hybrid, cosine, or xenc-style reranking.

  • top_k: default final facts for the reader.

  • reasoning_top_k: larger final fact count for reasoning questions.

  • retrieval_mode: service mode, gated or open.

  • bm25_lane: whether Turbopuffer adds a lexical BM25 lane.

StorageConfig

  • Chooses memory vs Turbopuffer.

  • Provides Turbopuffer namespace, region, API key, vector precision, and recluster threshold.

PromptConfig

  • Holds optional custom prompt templates.

  • Current pipeline code mostly uses built-in prompt constants directly.

Ingestion Flow

Ingestion is handled by MemorySystem.ingest.

sequenceDiagram
    participant User
    participant MemorySystem
    participant Distiller
    participant Backend
    participant Encoder

    User->>MemorySystem: ingest(sessions, dates, subject)
    MemorySystem->>MemorySystem: build_transcript(turns, numbered=True)
    MemorySystem->>Distiller: distill(key, transcript, date)
    Distiller->>Distiller: build extraction prompt
    Distiller->>Distiller: llm_fn(prompt)
    Distiller->>Distiller: parse_facts(raw)
    Distiller-->>MemorySystem: turn-indexed atomic facts
    MemorySystem->>MemorySystem: create FactRecord per fact
    MemorySystem->>Backend: upsert_facts(records)
    Backend->>Backend: deduplicate by content_id
    Backend->>Encoder: encode new fact texts
    Encoder-->>Backend: normalized vectors
    Backend->>Backend: store facts, vectors, metadata
Input Shape

ingest receives:

sessions: List[List[Dict[str, str]]]
dates: Optional[List[str]]
subject: Optional[str]

Each session is a list of turns:

{"role": "user", "content": "I started learning Portuguese."}

The date list is parallel to sessions. Dates are normalized through membukkit.time_utils.parse_datetime, which accepts Python datetime/date objects, ISO8601 strings, and legacy slash-date strings:

  • YYYY-MM-DD

  • YYYY-MM-DDTHH:MM:SS

  • YYYY-MM-DDTHH:MM:SSZ

  • YYYY-MM-DDTHH:MM:SS-05:00

  • YYYY/MM/DD HH:MM

  • YYYY/MM/DD

Transcript Building

build_transcript turns a session into compact numbered lines:

[T0] user: I started learning Portuguese.
[T1] assistant: Nice, here is a study plan...

Long turn text is truncated to keep distillation prompts bounded.

Fact Distillation

FactDistiller converts a transcript into atomic facts. It uses prompt templates in prompts/extraction.py.

There are two prompt modes:

PromptUsed whenBehavior
EXTRACTION_PROMPTNo subject suppliedWrites facts about "the user".
NAMED_EXTRACTION_PROMPTsubject suppliedWrites facts about the named person and protects identity attribution.

The prompt requires output lines in this format:

<turn_index> | <atomic fact>

parse_facts reads those lines into (turn_index, fact) pairs. Empty or NONE output means no facts were extracted.

Distillation can be cached by content hash if FactDistiller(cache_path=...) is used. The cache key includes a prompt version, and for named extraction it also includes the subject.

FactRecord Creation

For each distilled fact, MemorySystem.ingest creates a FactRecord with:

  • text: the atomic fact.

  • timestamp: parsed session date.

  • source_session: currently ingest:<session_index>.

  • subject: optional memory owner/person.

  • entities: simple extracted entity strings.

  • time_bucket: YYYY-MM or unknown.

Entity extraction and time bucketing come from retrieval/bucket_index.py.

Storage Backends

Storage is hidden behind the MemoryBackend protocol. The pipeline does not directly own arrays or database rows anymore. It asks the backend to:

  • clear memory,

  • upsert facts,

  • count facts,

  • generate candidate pools,

  • expose topic partitions,

  • provide topic exemplars,

  • delete memory.

The key shared data structures are:

TypeMeaning
FactRecordA fact before or during storage.
CandidateA fact returned from retrieval, ready for reranking.
CandidatePoolCandidate list plus trace and cosine availability.
MemoryBackendProtocol implemented by storage backends.

Internally, timestamps are represented as datetime objects. ISO8601 is the canonical string format for structured fields, while reader prompts keep compact date-only prefixes such as [2024-06-01].

Deduplication

content_id creates a stable SHA-1 based id from normalized fact text and optional subject. Backends deduplicate on that id, so ingesting the same extracted fact twice does not store it twice.

InMemoryBackend

InMemoryBackend is the default backend. It keeps:

  • _texts

  • _times

  • _entities

  • _time_buckets

  • _ids

  • _embs

  • _partition

On upsert_facts, it:

  1. Deduplicates incoming facts.

  2. Embeds only new fact texts.

  3. Appends text, timestamp, metadata, ids, and vectors.

  4. Invalidates the topic partition so it will rebuild lazily.

This backend is used by tests, local Python usage, and evaluation.

TurbopufferBackend

TurbopufferBackend is the persistent service backend. Each owner maps to one namespace, usually mem_<owner>.

It stores:

  • vector,

  • fact text,

  • timestamp,

  • topic bucket,

  • entities,

  • time bucket,

  • source metadata,

  • subject,

  • supersession fields,

  • partition version.

Important behavior:

  • New facts are embedded before write.

  • Vectors are stored as f16 by default.

  • Existing ids are checked before embedding to avoid unnecessary model calls.

  • Topic centroids are stored as a sentinel __partition__ row.

  • maybe_recluster and recluster rebuild centroids and patch scalar topic_bucket values without rewriting vectors.

  • supersede can mark older facts as stale by patching metadata.

Topic Buckets And Routing

The core retrieval method lives in retrieval/buckets.py.

flowchart TD
    FACTVECS[Fact embeddings] --> KMEANS[KMeans topic partition]
    KMEANS --> CENTROIDS[Normalized centroids]
    KMEANS --> MEMBERS[by_bucket fact ids]

    QUERY[Question] --> QEMB[Query embedding]
    QEMB --> SCORES[cosine query vs centroids]
    SCORES --> ORDER[Sort buckets by score]
    ORDER --> OPEN[Open buckets until scan budget reached]
    OPEN --> CAND[Candidate fact ids]
Building A Topic Partition

build_topic_partition(fact_embs, k=24):

  1. Chooses an effective bucket count.

  2. Runs KMeans or MiniBatchKMeans.

  3. Builds by_bucket, mapping each bucket to member fact indices.

  4. Computes normalized centroids.

  5. Optionally builds multiple prototypes per bucket with k_proto.

For very small banks, all facts go into one bucket.

Routing A Query

route_topic(partition, query_emb, budget=0.3):

  1. Normalizes the query embedding.

  2. Scores every bucket centroid.

  3. Converts scores to softmax route probabilities.

  4. Opens buckets in descending score order.

  5. Stops when opened facts cover at least the scan budget.

  6. Returns candidate indices and an inspectable trace.

The trace includes:

  • opened bucket ids,

  • route probabilities,

  • bucket sizes,

  • total facts,

  • scanned facts,

  • scan fraction,

  • total buckets.

Multi-Axis Routing

bucket_mode="multiaxis" adds two symbolic axes:

  • entity buckets from simple entity extraction,

  • time buckets from year-month timestamps.

route_multiaxis unions:

  • topic-routed candidates,

  • exact entity matches,

  • explicit time-bucket matches for temporal questions.

This is useful for catching named or dated evidence that topic routing alone may miss.

Query Classification

Query classification lives in retrieval/router.py.

The router is deliberately rule-based. It detects:

Query classExamples of cuesReader behavior
TEMPORAL"when", "before", "after", "latest", datesUse reasoning reader and temporal retrieval.
KNOWLEDGE_UPDATE"now", "currently", "changed", "switched"Use reasoning reader to resolve current/latest facts.
AGGREGATION"how many", "list all", "every", "total"Use reasoning reader for multi-fact synthesis.
GENERALNo special cuesUse dated reader.

Recommendation detection is separate:

is_recommendation_query(query_text)

If a query is a recommendation/advice request, it routes to the recommendation reader first, even if it also has other cues.

The helper functions used by the pipeline are:

  • is_recommendation_query

  • is_reasoning_query

  • is_temporal_query

Answer Flow

Answering is handled by MemorySystem.answer.

sequenceDiagram
    participant User
    participant MemorySystem
    participant Router
    participant Backend
    participant Reranker
    participant Reader
    participant LLM

    User->>MemorySystem: answer(question, question_date, identity)
    MemorySystem->>MemorySystem: if backend.count() == 0 return N/I
    MemorySystem->>Router: classify query
    Router-->>MemorySystem: is_rec, is_reason, is_temp
    MemorySystem->>Backend: candidates(query, top_k, flags)
    Backend-->>MemorySystem: CandidatePool
    MemorySystem->>Reranker: score(query, candidate texts)
    Reranker-->>MemorySystem: utility scores
    MemorySystem->>MemorySystem: select/fuse rankings
    MemorySystem->>MemorySystem: format facts chronologically
    MemorySystem->>Reader: reader(fact_lines, question, question_date)
    Reader->>LLM: prompt
    LLM-->>Reader: answer text
    Reader-->>MemorySystem: answer
    MemorySystem-->>User: AnswerResult

The answer path has four main stages:

  1. Classify the query.

  2. Retrieve and rerank candidate facts.

  3. Select the right reader.

  4. Return an AnswerResult.

Top-K Adjustment

Normal questions use RetrievalConfig.top_k.

Reasoning questions can use the larger RetrievalConfig.reasoning_top_k:

if self._retrieval.reasoning_top_k > k_eff and is_reason:
    k_eff = self._retrieval.reasoning_top_k

This gives multi-fact questions more evidence.

Candidate Generation And Reranking

Candidate generation happens inside the backend. Reranking happens in MemorySystem._retrieve.

flowchart TD
    QUERY[Question] --> BACKEND[backend.candidates]
    BACKEND --> POOL[CandidatePool]
    POOL --> XENC[UtilityReranker.score]
    XENC --> UTIL[utility scores]
    POOL --> COS[cosine scores if available]
    UTIL --> SELECT[Ranking selection]
    COS --> SELECT
    SELECT --> TOPK[Top-k Candidates]
In-Memory Candidate Generation

For bucket_mode="topic":

  1. Encode query.

  2. Build or reuse topic partition.

  3. Route query to buckets by scan budget.

  4. Return candidates from opened buckets.

  5. If select="hybrid", attach cosine scores for RRF fusion.

For bucket_mode="multiaxis":

  1. Build topic/entity/time partition.

  2. Route by topic.

  3. Add entity and time matches.

  4. Optionally cap topic candidates by cosine before reranking.

For other bucket modes:

  1. Compute cosine against all facts.

  2. Take the top candidate_pool.

Turbopuffer Candidate Generation

The Turbopuffer backend performs a database-backed candidate search:

  1. Count live facts.

  2. Embed the query.

  3. Extract query entities and optional time ranges.

  4. Route against cached topic centroids.

  5. Build a Turbopuffer filter.

  6. Run vector ANN and optionally BM25.

  7. Fuse server-side with RRF when both lanes are enabled.

  8. Return candidates to the local cross-encoder.

There are two service retrieval modes:

ModeMeaning
gatedTopic/entity/time filters constrain or broaden retrieval before DB search.
openANN-first over the namespace; buckets become descriptive trace data.
Local Cross-Encoder Rerank

UtilityReranker.score scores every candidate as a (query, fact) pair. Higher means more useful/relevant.

Hybrid RRF Fusion

When RetrievalConfig.select == "hybrid" and cosine scores exist, the pipeline uses rrf_order from retrieval/buckets.py.

RRF combines two rankings over the same candidate pool:

  • cross-encoder utility rank,

  • cosine similarity rank.

The formula is:

score = 1 / (k_rrf + rank_cross_encoder) + 1 / (k_rrf + rank_cosine)

The intuition: a fact can rank well if either the semantic vector signal or the cross-encoder relevance signal strongly likes it.

Fact Presentation

After retrieval, _present_temporal formats selected candidates as dated facts and sorts them chronologically:

[2024-06-01] The user switched to a vegan diet.
[2024-06-10] The user said the vegan diet was going well.

Readers see this ordered list, not raw Candidate objects.

Reader Layer

Readers live in reading/readers.py, with prompts in prompts/reading.py.

The pipeline chooses one of three main readers:

Reader factoryPromptUsed for
make_dated_readerDATED_READER_PROMPTDirect memory lookups.
make_reasoning_readerREASONING_READER_PROMPTTemporal, counting, latest/current, multi-session synthesis.
make_recommendation_readerRECOMMENDATION_READER_PROMPTPersonalized advice or recommendations.

All reader factories close over an llm_fn and return an answer function:

answer(fact_lines: List[str], question: str, qdate: str) -> str

Each reader:

  1. Builds a fact_block.

  2. Adds today_line if a question date exists.

  3. Adds _identity_preamble(identity) if identity exists.

  4. Formats a prompt.

  5. Calls the LLM.

  6. Returns stripped answer text.

The reasoning and Mem0 readers also strip final-answer markers such as Answer: or ANSWER:.

Abstention

The canonical internal abstention is:

N/I

_normalize_abstain converts N/I or NI to:

Based on our past conversations, you never mentioned that, so I don't have any information about it.

make_abstain_gate can build a groundedness verifier, but the main pipeline currently does not call it.

LLM Backends

llm/backends.py defines a simple callable interface:

class LLMBackend(Protocol):
    def __call__(self, prompt: str) -> str: ...

Implemented backends:

BackendSpec exampleNotes
OpenAIopenai:gpt-4o-miniUses chat completions. Temperature is omitted for models that do not support it.
Anthropicanthropic:claude-sonnet-4-20250514Uses messages API.
Local OpenAI-compatiblelocal:http://localhost:8000/v1:model-nameUseful for local model servers.

The same llm_fn is used for extraction and reading unless you manually wire different functions.

Models

There are two learned model roles.

Encoder

Encoder lazily loads a SentenceTransformer and encodes fact text and query text into normalized vectors. These vectors power:

  • fact storage,

  • KMeans topic buckets,

  • query-to-centroid routing,

  • cosine ranking.

Reranker

UtilityReranker wraps a CrossEncoder. It scores (query, fact) pairs after candidate generation.

This model is more expensive than cosine, so bucket routing keeps its input pool small.

Service API

The service is implemented in service/app.py and service/manager.py.

flowchart TD
    HTTP["HTTP request /v1/{owner}/..."] --> APP[FastAPI app]
    APP --> SVC[MemoryService]
    SVC --> CACHE[LRU cache of MemorySystem per owner]
    SVC --> SHARED[Shared encoder, reranker, LLM]
    SVC --> NS[Turbopuffer namespace mem_owner]
    NS --> SYS[MemorySystem with TurbopufferBackend]

MemoryService loads expensive models once per worker. Each owner gets a lightweight MemorySystem bound to one Turbopuffer namespace.

Important endpoints:

EndpointPurpose
GET /healthHealth check.
POST /v1/{owner}/ingestIngest sessions into an owner's memory.
POST /v1/{owner}/answerAnswer from an owner's memory.
GET /v1/{owner}/partitionShow partition version and bucket sizes.
POST /v1/{owner}/label_bucketsAsk the LLM to label buckets.
POST /v1/{owner}/warmWarm namespace and centroid cache.
POST /v1/{owner}/reclusterRebuild topic partition if needed.
DELETE /v1/{owner}Delete an owner's namespace.

Owner ids are sanitized by namespace_for(owner) into mem_<owner>.

CLI

cli.py defines the membukkit command.

Main subcommands:

CommandPurpose
membukkit evalRun LongMemEval or LoCoMo evaluation.
membukkit train-encoderDispatch to scripts/train_encoder.py.
membukkit train-rerankerDispatch to scripts/train_reranker.py.
membukkit serveStart the FastAPI service with Turbopuffer storage.
CLI Evaluation Path

The CLI eval path drives the production MemorySystem, the same ingest + kind-scoped union retrieval the service uses, so eval can't diverge from production (the old bespoke in-CLI retrieval has been removed):

  1. Load dataset instances.

  2. Build retrieval tasks with _build_all_tasks_lib: ingest each conversation into a MemorySystem (in-memory or Turbopuffer backend) and collect the union fact lines per method via answer(..., generate_answer=False).

  3. Cache task rows to the persistent task cache.

  4. Run readers and judges concurrently.

  5. Write e2e_summary.json and e2e_results.jsonl.

--replay-tasks skips model loading and retrieval by reusing the cached task rows.

Data And Evaluation

Dataset interfaces live in data/base.py:

  • FactInput

  • QueryInput

  • CoreMemDataset

LongMemEval support:

  • data/longmemeval.py downloads the cleaned benchmark from Hugging Face.

  • data/instance.py adapts each item into facts, queries, abilities, evidence indices, and utility matrices.

LoCoMo support:

  • data/locomo.py adapts LoCoMo into the LongMemEval-style instance interface.

  • LoCoMo categories are mapped into broad task types for reader and judge use.

Judging:

  • eval/judges.py has a generic numeric LLM judge and an official LongMemEval yes/no judge.

  • prompts/protocol.py contains Mem0 answer and judge prompts.

  • eval/harness.py provides a high-level evaluate(mem, dataset, ...) wrapper that resets and ingests per instance.

Telemetry

telemetry.py is a dependency-optional facade over Logfire/OpenTelemetry.

The rest of the code can call:

  • telemetry.span(...)

  • telemetry.timed(...)

  • telemetry.counter(...)

  • telemetry.histogram(...)

  • telemetry.set_attributes(...)

If Logfire is not installed or configured, these calls become safe no-ops.

By default, raw user text is not attached to telemetry. capture_content=True must be explicitly enabled to attach question, answer, or memory text.

Runtime Sequence: Ingest Then Answer

sequenceDiagram
    participant App
    participant MemorySystem
    participant Distiller
    participant Backend
    participant Encoder
    participant Router
    participant Reranker
    participant Reader

    App->>MemorySystem: from_pretrained(...)
    MemorySystem->>Encoder: lazy model wrapper
    MemorySystem->>Reranker: load cross-encoder
    MemorySystem->>Backend: make_backend(...)

    App->>MemorySystem: ingest(sessions, dates)
    MemorySystem->>Distiller: transcript -> atomic facts
    MemorySystem->>Backend: upsert_facts(FactRecord[])
    Backend->>Encoder: encode new facts
    Backend-->>MemorySystem: n_new

    App->>MemorySystem: answer(question)
    MemorySystem->>Router: classify query
    MemorySystem->>Backend: candidates(...)
    Backend->>Encoder: encode query
    Backend-->>MemorySystem: CandidatePool
    MemorySystem->>Reranker: score(query, facts)
    Reranker-->>MemorySystem: utility scores
    MemorySystem->>MemorySystem: RRF/select top-k
    MemorySystem->>Reader: prompt selected facts
    Reader-->>MemorySystem: answer text
    MemorySystem-->>App: AnswerResult

Important Design Choices

Atomic Facts Instead Of Raw Turns

The distiller rewrites chat sessions into short, self-contained memory facts. This makes retrieval units cleaner and makes the answer more likely to be explicit in the facts handed to the reader.

Buckets As Both Index And Explanation

Topic buckets are not only for speed. The opened bucket list is the retrieval explanation: it says which regions of memory were activated and how much memory was scanned.

Cross-Encoder Only After Gating

The cross-encoder is powerful but expensive. MEMBUKKIT first uses embeddings and bucket routing to produce a smaller candidate pool, then applies the cross-encoder only inside that pool.

Query-Type-Routed Readers

One prompt does not fit every question. The router picks:

  • dated reader for direct lookup,

  • reasoning reader for synthesis,

  • recommendation reader for personalized advice.

Backend Seam

MemorySystem owns model logic and final reranking. Backends own fact storage and candidate materialization. This keeps the in-memory research path and the Turbopuffer service path under one API.

Common Modification Points

GoalStart here
Change how facts are extractedprompts/extraction.py, extraction/distiller.py
Change reader behaviorprompts/reading.py, reading/readers.py
Change query classificationretrieval/router.py
Change bucket routingretrieval/buckets.py
Change metadata or storage semanticsstorage/base.py, backend implementation
Change local retrieval behaviorstorage/memory.py, MemorySystem._retrieve
Change service retrieval behaviorstorage/turbopuffer.py, retrieval/query_filters.py
Change eval scoringeval/judges.py, prompts/protocol.py
Add API endpointservice/app.py
Change CLI optionscli.py

Compact Mental Model

Conversation sessions
    -> LLM distillation
    -> atomic dated facts
    -> embeddings + metadata
    -> storage backend
    -> topic/entity/time organization
    -> query routing
    -> candidate pool
    -> cross-encoder rerank
    -> hybrid fusion
    -> dated fact lines
    -> query-type-specific reader prompt
    -> final answer + trace

In short: MEMBUKKIT turns messy conversational history into dated atomic facts, organizes those facts into explainable buckets, scans only the relevant memory regions for a question, reranks the selected facts, and asks a reader LLM to answer only from that evidence.

384 files · 376 not served here

Advantages

  • Supports temporal reasoning by superseding old facts instead of deleting them, enabling accurate as-of queries. evidence: README.md
  • Provides full transparency with receipts that include evidence status, source references, and cost metrics for every answer. evidence: docs/index.md
  • Optimizes performance by using bucketed retrieval, reading only a small slice of memory rather than the full context. evidence: README.md

Limitations

  • Distillation is an LLM-dependent process that occurs at write time, incurring costs for each session or document ingested. evidence: README.md
  • The atomic lane is bounded by the quality of the distillation model; smaller local models may extract weaker facts. evidence: README.md

Security

Risk level: No risk found

This brain runs

This brain runs nothing: AutoGineer found no hooks, scripts, plugin code or MCP servers in its files.

Attribution and licence

Created by
Memseek
Declared authors
  • MemBukkit contributors (declared in pyproject.toml)
Publisher
Memseek (Official Memseek project)
Source
memseekai/membukkit · commit 66a3c82
Licence
Apache License 2.0 (files served here)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Memseek.

Install from source

376 of its files are not served here, so there is no ZIP. memseekai/membukkit at 66a3c82