Skip to main content

LightMem (lmem) Python SDK

Ultra-Fast Local AI Agent Persistent Memory Engine with Neural Extractive QA, Multimodal BLOB Vault & Knowledge Graph.

PyPI version License: MIT

LightMem combines SQLite WAL + FTS5 BM25 with lazy-initialized ONNX vector search (fastembed), local ONNX Extractive QA (minilm-squad2 / tinyroberta-squad2) & swappable Ollama rerankers (ollama:<model>), immutable SHA-256-verified multimodal BLOB attachments (images, audio, video, documents), Obsidian-grade [[wikilinks]] & multi-hop knowledge graph traversal, nearest-neighbor conflict merging, and temporal point-in-time (as_of) & single-day (date) queries — with zero Python dependencies. Default embedding backend is ONNX bge-small-en-v1.5.


0.8.0 configuration and compatibility

LLM entity extraction is off by default. Enable it explicitly through lmem config --entity-extraction llm. Configuration changes can require per-vault reindexing. Remote commands reject unsupported operations and attachment flags instead of silently falling back to local data. API keys in config --json are redacted.

Native executable auto-downloads verify the release’s SHA256SUMS before safe extraction. Linux wheels use standard manylinux2014_x86_64 tags; compatibility with older Linux distributions is not promised. The SDK remains a typed subprocess bridge; latency includes a native CLI launch for each method.

⚡ Quickstart

Installation

pip install lmem

Python SDK Usage

from lmem import LightMem

# Initialize vault (defaults to ~/.lightmem/memories.db or custom db_path)
lm = LightMem()

# 1. Store a memory (auto-infers across 14 categories if omitted)
memory = lm.remember(
    "PostgreSQL primary runs on port 5432 with WAL archiving enabled",
    category="fact",
    title="PostgreSQL Primary Config",
    tags=["postgres", "database", "production"],
    confidence=0.95,
)
print("Stored memory:", memory.id)

# 2. Store Multimodal Attachments (images, audio, 4K video, PDFs in isolated 0600 SQLite BLOB vault)
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as examples:
    notes = Path(examples) / "architecture-notes.txt"
    notes.write_text("API gateway connects to PostgreSQL", encoding="utf-8")
    diagram = lm.remember(
        "API Gateway routes to [[PostgreSQL Primary Config]]",
        files=[notes], tags=["architecture", "gateway"], extract=False,
    )

# 3. Hybrid Search (FTS5 BM25 + Vector Cosine RRF + Graph Multi-Hop & Media Filter)
results = lm.recall("postgres port", limit=5, multi_hop=True)
for r in results:
    print(f"[{r.score:.2f}] {r.memory.title}: {r.memory.content}")

# Materialize verified attachment file paths directly on disk
attachment_paths = lm.recall("gateway", media="document", limit=1, path=True)
inspected_paths = lm.inspect(diagram.id, path=True)

# 4. Neural Extractive QA (exact fact extraction via ONNX SQuAD-2.0 or Ollama)
answer = lm.answer("what port does postgresql use?")
print("Extracted answer:", answer.answer)      # "5432"
print("Confidence:", answer.confidence)
print("Reranker:", answer.reranker_used)

# 5. Conversational Observation & Atomic Fact Extraction
candidates = lm.observe(
    "User: We switched Redis to port 6380.\nAssistant: Updated!",
    dry_run=True,
)
for c in candidates:
    print(f"[{c.category}] {c.title}: {c.content}")

# 6. Intentional Knowledge Graph Linking & Multi-Hop Traversal
lm.link(diagram.id, memory.id, relation="depends_on", weight=1.0)
related = lm.related(memory.id, hops=2)
for rel in related:
    print(f"Hop {rel.distance}: {rel.memory.title} via {' -> '.join(rel.relation_path)}")

# 7. Conflict Detection, Deduplication & Vault Telemetry
conflicts = lm.conflicts(min_similarity=0.80)
stats = lm.stats()
print(f"Active memories: {stats.active_memories} | Vectors: {stats.vector_count}")

# 8. Single-File DB & Media Transfer Bundles (Zero Re-embedding)
# Packages checkpointed SQLite DB, all attached videos/photos/docs & vector embeddings into a .zip
lm.bundle_export("my-vault.zip")
info = lm.bundle_info("my-vault.zip")
print(f"Backed up {info['stats']['total_memories']} memories & {info['stats']['total_attachments']} media files")
lm.bundle_import("my-vault.zip", mode="replace")  # or mode="merge"

# 9. Deploy Skill to AI Agents (Antigravity, Codex, Hermes, Cursor, Claude)
lm.connect("antigravity")

🧩 Python SDK Reference (LightMem)

Method Description
lm.remember(content, ..., files=None, extract=False, supersede=False, no_entities=False) Store a memory, optional binary attachments (files=[...]), and auto-extracted entities (EntityRecord), auto-linking [[wikilinks]].
lm.recall(query, limit=5, category=None, media=None, multi_hop=False, path=False) Hybrid BM25 + Cosine RRF search; returns List[ScoredMemory] or List[str] file paths when path=True.
lm.answer(question, category=None, reranker=None, as_of=None, date=None) Extractive QA via local ONNX (minilm-squad2, tinyroberta-squad2), ollama:<model>, or top1.
lm.observe(input_text_or_path, yes=False, dry_run=False, reranker=None) Extract atomic candidate memories from dialogue transcripts or notes.
lm.inspect(memory_id, *extra_ids, save_to=None, path=False) Inspect full record + graph links + attachments, or materialize verified file paths (path=True).
lm.bundle_export(output_path) Export complete vault into a portable compressed .zip bundle (DB, vectors & all video/photo files).
lm.bundle_import(bundle_path, mode="replace") Restore (mode="replace") or merge (mode="merge") vault from a .zip transfer bundle.
lm.bundle_info(bundle_path) Inspect bundle manifest (record counts, attachments, schema) without extracting.
lm.list(page=None, limit=20, category=None, media=None, path=False) Paginated chronological listing (PaginatedList or List[str] paths when path=True).
lm.link(source, target, relation="relates_to", weight=1.0) Create or update a directional knowledge graph edge.
lm.unlink(source, target, relation=None) Remove a directional edge between two memories.
lm.related(memory_id, hops=2) Breadth-first multi-hop traversal with hop-decay scoring.
lm.graph(focus=None, hops=2) Export full or neighborhood knowledge graph {nodes, edges}.
lm.conflicts(yes=False, min_similarity=0.78, reranker=None) Detect (and optionally auto-merge with yes=True) conflicting or near-duplicate memories.
lm.deduplicate() Smart-merge exact duplicate memories.
lm.forget(memory_id, hard=False) Soft-expire (hard=False) or permanently purge (hard=True, cascading BLOBs & cached files).
lm.stats() Vault telemetry (StorageStats: active/expired counts, vector count, categories, DB size).
lm.connect(platform=None, workspace=False, path=None) Install SKILL.md to AI coding agents (antigravity, codex, hermes, cursor, claude, all).

💻 CLI Commands (Included)

The pip install lmem package also installs the standalone lmem (and lightmem) CLI:

lmem remember "Redis cache runs on port 6379" -t fact
lmem remember "Itachi 4K wallpaper" -f ./itachi-4k.mp4 --extract
lmem observe conversation.txt --yes
lmem recall "redis port" -l 5 --multi-hop
lmem recall "itachi" -m video -l 1 --path
lmem inspect <ID> --paths
lmem answer "what is my pan card no"
lmem link <SRC_ID> <DST_ID> -r "depends_on"
lmem related <ID> --hops 2
lmem graph --focus <ID> --hops 2
lmem conflicts
lmem bundle export -o backup.zip
lmem bundle info backup.zip
lmem bundle import backup.zip --merge
lmem connect all

Single-File DB & Media Transfer Bundles (v0.5.0)

Transfer complete memory vaults between machines, servers, or workstations in a single compressed file—including all SQLite tables, full vector embeddings, knowledge graph links, and attached physical video, photo, audio, and PDF files:

# Export complete vault with clean SQLite checkpoint (VACUUM INTO) & all physical media
lmem bundle export -o my-vault.zip
lmem export --bundle -o my-vault.zip

# Inspect archive contents, record counts, and attachments without unzipping
lmem bundle info my-vault.zip

# Restore on a new machine with zero re-indexing or re-embedding overhead
lmem bundle import my-vault.zip              # Clean restore (default: replace)
lmem bundle import my-vault.zip --merge      # Merge into existing memories

Bundles use the standard .zip (or .lmbundle) format containing:

  • memories.db: Pristine SQLite database snapshot generated via VACUUM INTO (WAL flushed, defragmented).
  • manifest.json: Verification manifest with schema version, record counts, SHA-256 digests, and media metadata.
  • attachments/: Physical media files (4K videos, photos, voice notes, PDFs) extracted automatically to the target vault.

Identity-aware connections (v0.4.0)

Register the person, the logical agent, and a named harness connection once:

lmem identity user-add alice --name "Alice"
lmem identity agent-add coding --user alice
lmem identity connection-add agy --user alice --agent coding --harness antigravity --project myapp --memory-scope project
lmem identity connection-add codex --user alice --agent coding --harness codex --project myapp --memory-scope project

lmem --connection agy --session chat-123 remember "Decision: use SQLite WAL" -t decision
lmem --connection codex recall "database decision"
lmem --connection codex context --json
lmem --connection codex --scope agent remember "Current debugging checkpoint"
lmem --connection agy connect
lmem --connection agy connect --mcp

Connections for the same user/project open the same persistent project vault across harnesses. user scope follows the user; agent scope belongs to the user/agent and, when provided, project. Each command uses one scope. Switch with --scope; recall does not blend scopes. LIGHTMEM_CONNECTION can select a default connection. Do not combine a connection with --db, LIGHTMEM_DB, or --global.

Register custom harnesses and deploy their bound instructions:

lmem identity harness-add my-harness --path /absolute/path/to/skills
lmem identity connection-add custom --user alice --agent coding --harness my-harness --memory-scope user
lmem --connection custom connect
lmem identity list connections --json
lmem identity list users --json

Custom MCP clients can launch lmem --connection custom mcp; automatic MCP configuration supports Antigravity, Claude, and Cursor. The MCP context tool shows the active binding. Connection IDs, user IDs, agent IDs, project IDs, and optional session IDs accept 1–128 ASCII letters, digits, underscores, or hyphens.

The registry is stored in ~/.lightmem/identities.db and scoped vaults under ~/.lightmem/vaults/ (or LIGHTMEM_CONFIG_DIR). Scope keys use hashes to avoid filesystem case collisions. All memory operations, including graph traversal, deduplication, conflicts, attachments, and export, operate on the selected vault. New memories expose optional context source metadata in JSON; exact duplicates retain their original source. Backups preserve source metadata even when deliberately imported into another vault.

Existing commands and databases continue to work. Schema v5 adds optional source context; existing memories are not attributed to a user automatically. To copy existing memories into a new scope, explicitly export the old database and import into the selected connection. These are local organizational identities, not authentication. Connections do not automatically capture chats; agents must invoke remember or observe.

from lmem import LightMem

admin = LightMem()
admin.register_user("alice")
admin.register_agent("coding", "alice")
admin.register_connection("agy", "alice", "coding", "antigravity", project_id="myapp", scope="project")

memory = LightMem(connection="agy", session="chat-123")
saved = memory.remember("Decision: use SQLite WAL", category="decision")
print(saved.context)
print(memory.context())

Python also exposes register_harness, identities, connection_info, and connect(mcp=True). Use different connection IDs for multiple harnesses while retaining the same user/project to share decisions.


📄 License

MIT License. Created by Pathi Krishna Kanth.

Metadata

Release files for lmem 0.8.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lmem 0.8.1
File Size Uploaded Provenance Actions
lmem-0.8.1.tar.gz 16.8 kB With provenance Details for lmem-0.8.1.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for lmem 0.8.1
File Interpreter ABI Platform Actions
lmem-0.8.1-py3-none-win_amd64.whl Python 3 none Windows x86-64 Details for lmem-0.8.1-py3-none-win_amd64.whl
lmem-0.8.1-py3-none-manylinux2014_x86_64.whl Python 3 none Linux glibc 2.17+ x86-64 Details for lmem-0.8.1-py3-none-manylinux2014_x86_64.whl
lmem-0.8.1-py3-none-macosx_11_0_arm64.whl Python 3 none macOS 11.0+ ARM64 Details for lmem-0.8.1-py3-none-macosx_11_0_arm64.whl

Total release size: 41.4 MB

Release files / lmem-0.8.1.tar.gz

Download URL lmem-0.8.1.tar.gz
Size 16.8 kB
Tags Source
SHA-256 checksum
How to use checksums
58cba2ba19333ac689cc4671fa5841e9834d990b4417137a0b0861bcb6ea271c
BLAKE2b-256 checksum
How to use checksums
a0e5e80d9ce50e76809ed09eb3a265c2c2edbfc4f967df288426d5f4849c2012
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Release files / lmem-0.8.1-py3-none-win_amd64.whl

Download URL lmem-0.8.1-py3-none-win_amd64.whl
Size 13.2 MB
Tags Python 3 Windows x86-64
SHA-256 checksum
How to use checksums
3b4f4ffe7e888aa24753d6b83524b999d11384d0efd1f260b7cb2a9a50475cf1
BLAKE2b-256 checksum
How to use checksums
ef180a3074afb3292e659319b14bbbeb987fc73fc03b5cf68a41dfc702ff190f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Release files / lmem-0.8.1-py3-none-manylinux2014_x86_64.whl

Download URL lmem-0.8.1-py3-none-manylinux2014_x86_64.whl
Size 15.4 MB
Tags Linux glibc 2.17+ x86-64 Python 3
SHA-256 checksum
How to use checksums
ab34687bb87de914022b5834722fb6b218105f5e3e6f947d32c307dfacee0b8f
BLAKE2b-256 checksum
How to use checksums
c0b9124e0bc6d68e1bad131034234f955854330d6220c9bb775c302a831a833a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Release files / lmem-0.8.1-py3-none-macosx_11_0_arm64.whl

Download URL lmem-0.8.1-py3-none-macosx_11_0_arm64.whl
Size 12.8 MB
Tags Python 3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
be90422c48b764fde098f076709d1d234126c32c749597671fa4d4fd4e819d90
BLAKE2b-256 checksum
How to use checksums
080da456b8e82c6dec0886e1f14d3e920b9c91fa8dd35e5f46b7316dc4e088fe
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Security for lmem 0.8.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 4 files in this release have been uploaded with provenance metadata.

Select from 4 files

Attestation for lmem-0.8.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page