Proposal: A basic conversation Memory component (persistence + recall) for stdlib

Aperta
#1,249 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 3 giorni

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
15/100
Tipo di issue
Funzionalità
Chiarezza
Da chiarire
Stato di attività
Tranquilla
Stack tecnologico
python
Ambito
ai

Direzione di ricerca

This is a design proposal, not a ready task. Read ChatContext and the instruct() grounding_context parameter in mellea.stdlib.components.chat to see the injection seam, and the RichDocument save/load idiom the issue cites. Do not start a patch until a maintainer decides whether it belongs in stdlib or mellea-contribs and whether V1 is explicit+heuristic only or includes LLM extraction. Done means that decision is recorded on the issue.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

p2

Summary

I'd like to contribute a small, dependency-free conversation memory component, and I'm opening
this issue first to get your direction on scope and placement (stdlib vs. mellea-contribs) before
sending a PR.

This is the familiar flat-file "user memory" pattern (similar to what assistant products expose
as persistent memory): a small, human-readable store of durable facts about the user that
survives restarts and is recalled into context when relevant. Today a Mellea session keeps recent
turns in ChatContext(window_size=N), but there's no built-in way to (1) persist durable facts
across process restarts, or (2) recall a relevant fact from earlier than the context window. This
proposal adds both, in pure Python, behind a small interface designed so richer backends can swap in
later without changing the API.

Motivation / the gaps

  • No cross-session persistence. When the process exits, everything the session learned is gone —
    there's no save()/load() for durable user facts. (RichDocument has a save/load idiom, but
    nothing equivalent for user memory.)
  • No selective recall. ChatContext is a recency window; once a turn slides out, it's
    unrecoverable, even if it's exactly the fact the next prompt needs.

Proposed design

A stable Memory Protocol + a built-in MarkdownMemory implementation. Durable user-facts are the
primary store
(a human-readable Markdown file); extracting facts from a conversation is a secondary
helper. retrieve() returns a mapping that drops directly into instruct(grounding_context=...) —
the existing injection seam.

@runtime_checkable
class Memory(Protocol):
    # primary: durable user-facts
    def remember(self, fact: str, *, metadata: dict | None = None) -> None: ...
    def forget(self, fact: str) -> None: ...
    def facts(self) -> list[str]: ...
    def retrieve(self, query: str, *, k: int = 5) -> dict[str, str | CBlock | Component]: ...
    # secondary helper: extract facts from a conversation (extractor pluggable — see design question)
    def ingest_context(self, ctx: Context, *, extractor: "FactExtractor | None" = None) -> None: ...
    # persistence
    def save(self, path: str | Path) -> None: ...                # writes <path>.md + <path>.meta.json
    @classmethod
    def load(cls, path: str | Path) -> "Memory": ...

class MarkdownMemory:   # V1 default: Markdown store + JSON sidecar, keyword+recency recall, no deps
    ...

Storage is a human-readable Markdown file (the source of truth) plus a small JSON sidecar for
metadata (timestamps/scores), so the .md stays hand-editable:

# User Memory
- User prefers uv over pip.
- User's name is Alice.

Usage (instruct-only, since grounding_context is an instruct() parameter):

mem = MarkdownMemory.load(p) if p.exists() else MarkdownMemory()
mem.remember("User prefers uv over pip.")                                      # durable fact
with start_session("ollama", context_type="chat") as s:
    out = s.instruct(user_msg, grounding_context=mem.retrieve(user_msg))       # recall
    mem.ingest_context(s.ctx)                                                  # OPTIONAL: extract facts
mem.save(p)                                                                    # persist (.md + .meta.json)

Scope (intentionally minimal for a first PR)

  • In: durable user-facts (remember/forget/facts), save/load (Markdown + JSON sidecar,
    versioned), keyword+recency retrieve() returning a grounding_context mapping, optional
    ingest_context() fact-extraction via as_chat_history(), unit tests (no LLM), one backend-free example.
  • Out / future: embeddings/semantic retrieval, active LLM-driven memory (via @mify/MObject),
    auto-persist via a SESSION_CLEANUP hook, and KV-cache-aware retrieval for LocalHFBackend. The
    retrieve() method is deliberately the single pluggable seam so these can land as follow-ups
    without breaking the API.

Key design question: how are facts extracted? (your call for V1)

The hardest scoping decision is who decides what becomes a stored fact. There's a spectrum, and
the choice determines whether V1 stays dependency-free or takes an LLM/backend dependency. The
interface is identical at every point on the spectrum — only what sits behind ingest_context()
changes — so we'd like your steer on where V1 should land:

Level Who extracts LLM/backend needed? Behaves like
A. Explicit App/user calls remember("…") No CLAUDE.md — deliberate writes
B. Heuristic Rule-based scan of turns ("remember that…", "my name is…") No Lightweight auto-capture
C. LLM-extracted A model reads the exchange and infers durable facts, dedupes/merges Yes ChatGPT / Anthropic-style auto-memory

We can ship A+B with zero dependencies today (deterministic, unit-testable, works on every
backend). C is the "feels magic" version but requires a model call per ingestion — i.e. memory
would depend on a backend, and tests become qualitative.

Questions:

  • Do you want V1 to be the clean, dependency-free A+B, with C added later behind the same
    ingest_context() seam (e.g. an opt-in extractor= that defaults to heuristics but accepts an
    LLM-backed extractor)?
  • Or do you consider LLM-extracted memory (C) essential to V1, accepting the backend dependency
    and qualitative tests? If so, should the extractor use the session's existing backend, or be a
    pluggable component?

Either way the public API is the same — this is purely about how much intelligence ships inside V1
vs. arrives as a follow-up. We're glad to build to your preference; we just don't want to assume.

Dependencies

Levels A+B: none — pure stdlib (json, pathlib, re), pyproject.toml unchanged. Level C
would add an LLM call via the session's backend (no new package, but a runtime/backend dependency
and qualitative tests) — included only if you want it in V1.

Compatibility

No changes to existing Mellea APIs or behavior. The component is additive and self-contained
(imports only mellea.core and mellea.stdlib.components.chat).

The question for maintainers

  1. Does this belong in mellea/stdlib, or would you prefer it start in mellea-contribs?
  2. Any preference on naming (Memory/MarkdownMemory vs. e.g. UserMemory)? And is Markdown +
    JSON-sidecar the storage you'd want, or a single JSON file?
  3. Is the Protocol + swappable-backend shape the right altitude, or do you prefer a single concrete
    class for now?

Happy to follow whichever direction you prefer — the design is self-contained so relocating between
stdlib and contribs is a file move, not a rewrite. I'll open the PR once you've weighed in.

@HendrikStrobelt @nrfulton

Lingua principale
Python
Stelle
1.8k
Fork
161
Merge medio
4g 3h
PR unite (30g)
45

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di generative-computing/mellea

Tutte le issue di generative-computing/mellea

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.