Skip to main content

opensomem — an open implementation of SoMem

opensomem is an independent, open-source implementation of SoMem (Self-Organized Memory), the method from "Can LLM Agents Organize Their Own Memory?" by Fu, Qi et al. (arXiv 2611.11929).

Not the official implementation. This project is not affiliated with the paper's authors. Their official code is github.com/Qi202/SoMem. opensomem was written from the paper; the authors' repository was only skimmed for orientation, and no code was copied from it. Credit for the method belongs to the paper's authors.

What this implementation adds: no runtime dependencies (standard library only); any chat provider (Anthropic, OpenAI, Gemini, or any OpenAI-compatible endpoint such as NVIDIA, Groq, OpenRouter or a local Ollama server); a strict validator for every memory edit; and, in the source repository, a LoCoMo evaluation harness and a memory audit tool.

pip install opensomem

The LLM decides the semantic organization of memory: what to record, how to group it, when to revise or merge, and what goes into Core. Deterministic code (the runtime) enforces the invariants and derives every access structure. Original interactions are never lost, and every statement links back to them as evidence. Memory is plain Markdown in a workspace folder, so a workspace built by one model can be read by any other.

memory/
├── somem.toml            configuration (all defaults: somem/config.py, rationale: PLAN.md)
├── source/               immutable evidence: D<n>.md (read-only, write-once) + manifest.jsonl (hashes)
├── topics/               agent-organized memory units (Markdown); topics/core.md = Core
├── timeline/             derived: YYYY.md, YYYY/MM.md, YYYY/MM/DD.md
├── views/                derived: relations.{json,md} (graph + backlinks), recent.{json,md}, inventory.txt
└── .somem/               runtime state, unit registry (creation order), logs/*.jsonl, caches, staging

Setup

Python 3.11+. There are no runtime dependencies (HTTP goes through urllib), and pytest is only needed for the tests.

python3.12 -m venv .venv && source .venv/bin/activate
pip install -e '.[dev]'
pytest                                  # 110 offline tests
examples/run_demo.sh                    # offline demo of the paper's example (no API key)

Using it with real models

export ANTHROPIC_API_KEY=...            # or OPENAI_API_KEY / GEMINI_API_KEY; local servers need none
opensomem -w memory init
opensomem -w memory ingest examples/demo_conversation/s1.json examples/demo_conversation/s2.json \
                       examples/demo_conversation/s3.json examples/demo_conversation/s4.json
opensomem -w memory ask "What is the status of the Kestrel migration and why was it late?" --trace
opensomem -w memory reorganize              # files changed since the last pass;  --all = final pass
opensomem -w memory inspect                 # tree + counters
opensomem -w memory inspect topics/work.md  # a file
opensomem -w memory inspect --graph 4a8b10cd  # a paragraph: evidence, outgoing links, backlinks
opensomem -w memory validate                # re-run the validator on the live workspace

You can configure the Writer and Reader independently, in somem.toml ([writer.llm], [reader.llm]) or per command:

opensomem -w memory --writer-model anthropic/<model> ingest s5.json
opensomem -w memory --reader-model openai/<model> ask "..."
opensomem -w memory --reader-model gemini/<model> ask "..."
opensomem -w memory --reader-model local/llama3.1 ask "..."   # any OpenAI-compatible server; set base_url in somem.toml

OpenAI-compatible endpoints (NVIDIA, Groq, OpenRouter, Ollama)

--writer-model / --reader-model set only the provider and model. The endpoint URL and the key's environment variable go in the workspace's somem.toml, written before init (otherwise init writes the defaults):

[writer.llm]
provider = "openai"                                   # OpenAI-compatible chat/completions
model = "<model id from your provider>"
base_url = "https://integrate.api.nvidia.com/v1"
api_key_env = "NVIDIA_API_KEY"
max_tokens = 16384    # reasoning models can spend thousands of tokens thinking before they answer
timeout_s = 300

[reader.llm]
provider = "openai"
model = "<model id from your provider>"
base_url = "https://integrate.api.nvidia.com/v1"
api_key_env = "NVIDIA_API_KEY"
max_tokens = 16384
timeout_s = 300

Only one process may write a workspace at a time; a second ingest on the same workspace exits with an error instead of archiving the same sessions twice.

Session files are either JSON ({"date": "2026-03-05", "messages": [{"speaker": "user", "text": "...", "time"?: "..."}]}) or plain text (Speaker: text lines, with an optional first line Date: 2026-03-05).

Python API:

from opensomem.system import SoMem
sm = SoMem("memory")
report = sm.ingest([{"speaker": "user", "text": "..."}], date="2026-03-05")
print(sm.ask("When is the meeting?", date="2026-03-15").answer)

How it works

Topic format (opensomem/markdown.py)

# Events

The reading group meets on March 18[^e1] at the Community Center; it moved from Riverside Library
because the library is under repair.[^e2] See [the venue](places.md#^7c91e2ab). ^0caf5cdf

[^e1]: Time: 2026-03-18; Sources: D1:1, D2:1
[^e2]: Time: 2026-03-12; Sources: D1:1, D2:1

Each paragraph is one memory unit with a stable ^8-hex ID, footnoted evidence (Time at the source's precision, plus Source IDs), and links to paragraphs in other files.

Write path (writer.py, runtime.py, edits.py, validator.py)

  1. Runtime.ingest_source appends the session to Source. This is program code only: the file is created exclusively, set to 0444, and hashed in the manifest.
  2. The Writer agent reads memory with read-only tools and returns an edit proposal (JSON ops: upsert_paragraph, merge_paragraphs, move_paragraph, delete_paragraph, create/write/move/delete_file, rename_heading).
  3. The proposal is applied to a staged copy (.somem/stage/<id>/). The runtime then assigns any missing IDs, normalizes footnotes, and repairs links broken by moves or merges.
  4. The validator checks seven rules: source_unchanged, source_refs, links, paragraph_contract, time, paths, core.
  5. Accept: views are rebuilt in the stage, then topics/ timeline/ views/ are swapped in with directory renames under an install journal, which Workspace.recover() rolls back after a crash. Reject: the stage is discarded, the validator errors go back to the Writer, and it retries (default 3 retries).
  6. Every N sessions (reorg.every_n_sessions, default 5), a reorganization pass re-runs the Writer over Topic files changed since the last pass. opensomem reorganize --all runs the final pass. An optional post-write probe (probe.enabled) asks a question about the new session, has the Reader answer it, judges the answer, and triggers a targeted repair if it fails.

Derived views (views.py)

These are pure functions of Topic plus the unit registry, with no LLM calls:

  • Graph: edges and backlinks per paragraph.
  • Timeline: one entry per evidence annotation, filed by its time precision.
  • Recent: the K newest units, by creation order (default K=20).
  • Inventory: the list of workspace files.

Read path (reader.py, tools.py, search.py)

The Reader's initial context holds Core, Recent, the inventory and the question date. Its tools are bm25_search, embedding_search (both with path_filter and date_range), list_memory_files and read_memory_file (line ranges). It is capped at 20 turns by default. Two alternative interfaces are selected with reader.interface or --interface:

  • memory_search: one tool with BM25, dense and hybrid (RRF) modes.
  • shell: an allow-listed read-only shell: ls find rg grep cat sed head tail wc. Pipes are allowed. Redirects, chaining and sed -i/find -exec are refused, sed may only print line ranges, and paths are confined to the workspace.

The default embedder is an offline, deterministic hashing embedder. To use real embeddings, set [embedding] backend = "openai" | "gemini" | "ollama".

LLM layer (llm.py, agent.py)

  • Providers: anthropic, openai, gemini, local (any OpenAI-compatible server) and scripted (replay, for tests and demos).
  • Client features: retries with exponential backoff on 429/5xx/timeouts, token accounting and cost accounting (set a [pricing] table to get costs), a disk cache under .somem/cache/llm, temperature 0, and a seed where the provider supports one.
  • Tool calling uses a plain-text JSON protocol rather than provider-native function calling, so any chat model can act as Writer or Reader.

Prompts

Prompts live in prompts/ as versioned files (writer_v1.md, reader_v1.md, …). The design is described in prompts/README.md. The paper does not publish its prompts, so these were written for this implementation.

Logs

.somem/logs/ holds:

  • writer.jsonl: every proposal, accept or reject with errors, give-up, probe, and the full trajectory.
  • reader.jsonl: question, answer, evidence and trajectory.
  • llm.jsonl: every call with tokens, cost, latency, cache hits and retries.
  • source.jsonl: appends to Source.

Tests

File Covers
test_validator.py at least one failing case per rule (27 cases) plus a valid baseline
test_staging.py accept installs; reject / partial failure / path escape leave every byte unchanged; crash recovery; paragraph ops and link repair; deterministic IDs
test_source.py verbatim archive, read-only files, no overwrite, Writer cannot touch Source, tamper detection blocks commits
test_views.py golden files for timeline/relations/recent/inventory (UPDATE_GOLDEN=1 to regenerate), determinism, precision routing
test_reader.py search plus filters, read confinement, shell allow-list (each case also asserts the workspace is unchanged), Reader trajectory, alternative interfaces
test_llm.py, test_agent.py, test_writer.py providers via fake transport, retries, cache; agent loop; Writer retry, give-up, reorganization, probe→repair
test_integration_reading_group.py the paper's example end to end (see below)
test_cli.py every CLI command

About the integration test: it runs offline with scripted Writer and Reader agents that make real tool calls and build their outputs from the tool results. For example, the session-2 Writer finds the existing paragraph ID through bm25_search, and the Reader composes its answer from the retrieved paragraph and Timeline file. test_reading_group_live runs the same scenario against the models you configure:

SOMEM_LIVE_WRITER=provider/model SOMEM_LIVE_READER=provider/model pytest -m live
# OpenAI-compatible endpoint: also set SOMEM_LIVE_BASE_URL and SOMEM_LIVE_KEY_ENV

Known limitations

  • Timeline statements can be fragments. A statement is the text between footnote markers, as specified, so a statement such as at the Community Center. can lose its subject when one sentence carries two markers.
  • Core size is approximate. It is estimated as chars / 4 tokens; there is no tokenizer dependency.
  • Single writer per workspace. A second process that tries to write the same workspace stops with an error instead of waiting; run one ingest at a time per workspace.

Metadata

Release files for opensomem 0.1.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 opensomem 0.1.1
File Size Uploaded Provenance Actions
opensomem-0.1.1.tar.gz 79.1 kB Without provenance Details for opensomem-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for opensomem 0.1.1
File Interpreter ABI Platform Actions
opensomem-0.1.1-py3-none-any.whl Python 3 none any Details for opensomem-0.1.1-py3-none-any.whl

Total release size: 144.3 kB

Release files / opensomem-0.1.1.tar.gz

Download URL opensomem-0.1.1.tar.gz
Size 79.1 kB
Tags Source
SHA-256 checksum
How to use checksums
5a9e3f7542dd9dec55c6aa1c0aa286a5e388be035569895befb9e0101d56ef1b
BLAKE2b-256 checksum
How to use checksums
8c98a674ec9b8ef3b2d3a633745f681419c62525b33198d08ed0582b622e0e9f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.16

Release files / opensomem-0.1.1-py3-none-any.whl

Download URL opensomem-0.1.1-py3-none-any.whl
Size 65.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9a80b7120c6851fd37a7568888604ba315006e2081fd0573fb7416737943b21c
BLAKE2b-256 checksum
How to use checksums
65b6eeb33eb4a36d9b088832822965cea92b8bb08a24112a9035e06fc2f02ae6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.16

Security for opensomem 0.1.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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files No provenance

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