Skip to content

V1 Memory and Knowledge en

weego edited this page Nov 15, 2026 · 1 revision

Memory, Sessions, and RAG

简体中文 | English

Applies to v1.0.0. These three kinds of state serve different purposes; do not use them interchangeably.

Need Interface What it stores
Remember a user-authorized long-term preference MemoryProtocol, MemoryPolicy Memory scoped to a user, tenant, source, and scope.
Restore a conversation or review model/tool activity Session, SqliteSessionStore Ordered events, turns, checkpoints, and branches.
Find source-backed facts SqliteFTSRetrievalProvider Documents, chunks, sources, and citation IDs. Retrieval is not factual verification.

Long-term memory and isolation

Adapters implement store(data, user_id) and retrieve(query, user_id). An optional metadata argument can retain provenance and scope. Retrieval results use the shape {"results": [...]}. This in-memory example checks basic isolation with no model or database:

from LightAgent import SharedMemoryPool

pool = SharedMemoryPool(agent_name="guide")
pool.store("Alice prefers concise summaries.", user_id="tenant-a:alice")
pool.store("Bob prefers detailed summaries.", user_id="tenant-b:bob")

alice = pool.list_records(user_id="tenant-a:alice")
assert len(alice) == 1
assert pool.list_records(user_id="tenant-c:alice") == []
print(pool.retrieve("concise", user_id="tenant-a:alice")["results"])

Pass memory=pool to an Agent, and keep the protocol when swapping backends. Derive namespaces and user_id from authenticated application identity, not from arbitrary tenant claims in the request. The shared pool is an in-process prototype; use an external backend for production persistence. Install the mem0 extra to use Mem0. See the Mem0 example, vector adapter example, MemCode, and ClawMem.

Configure MemoryPolicy explicitly in production. Filter reads by provenance, scope, and ownership, and reject unattributed results if needed. Limit duplicate, excessive, or low-quality writes. With require_write_admission=True, writes require a positive admission decision. This example allows only bounded user-scope memory; a production application can incorporate a trusted review record:

from LightAgent import MemoryPolicy

def admit_user_preference(data, context):
    return context["source"] == "user" and context["scope"] == "user" and len(data) <= 200

policy = MemoryPolicy(
    namespace="tenant-a",
    allow_unattributed_results=False,
    allowed_sources=("user",),
    allowed_scopes=("user",),
    require_write_admission=True,
    memory_write_admission=admit_user_preference,
    max_writes_per_run=1,
)

Self-learning reflections and internal evidence form non-injectable MemoryCandidate records by default. Inspect them with agent.list_memory_candidates(). The trusted host can call agent.promote_memory_candidate(candidate_id, decision=...) or configure memory_promotion_admission with a MemoryPromotionDecision and promotion Hooks to audit approval, rejection, rewriting, or retention as a candidate. Do not promote low-trust material into system instructions. The application owns retention, deletion, and backend permissions. Framework tests do not establish the transaction and isolation guarantees of arbitrary graph databases. See Write Admission, Memory Security, and Memory and Delegation Boundaries.

Sessions, replay, and forks

Set session_store=SqliteSessionStore(...) when creating the Agent and pass the same application session_id across turns. Authenticate users and check session ownership in the application; knowing a session ID is not authorization. A low-level offline example:

from pathlib import Path
from tempfile import TemporaryDirectory

from LightAgent import Session, SqliteSessionStore

with TemporaryDirectory() as directory:
    store = SqliteSessionStore(Path(directory) / "sessions.sqlite3")
    session = store.create(Session(session_id="guide"))
    session.append("message.received", {"content": "保留这条项目决策。"})
    saved = session.checkpoint("before-review")
    store.save(session)
    restored = store.get("guide")
    print(restored.replay().to_dict())
    assert restored.replay().last_sequence >= saved.sequence

InMemorySessionStore is useful for tests; JsonlSessionStore for controlled local files; SQLite for single-host persistence with transactions, sequence checks, and integrity chains. Replay reads history without calling the model or running tools. A fork starts a new branch with recorded lineage without changing existing events. At the Agent level, use replay_session(), checkpoint_session(), and fork_session(). Use ContextProjector to project messages and ContextBudget or ContextCompactor to manage context and large tool outputs. A session log is neither long-term memory nor durable task state.

SQLite knowledge retrieval

from pathlib import Path
from tempfile import TemporaryDirectory

from LightAgent import RetrievalDocument, SqliteFTSRetrievalProvider

with TemporaryDirectory() as directory:
    rag = SqliteFTSRetrievalProvider(Path(directory) / "knowledge.sqlite3")
    rag.ingest(RetrievalDocument(
        document_id="manual",
        title="验收说明",
        source="handbook.md",
        tenant_id="acme",
        content="Run regression tests before release.",
    ))
    matches = rag.search("regression", tenant_id="acme", limit=3)
    assert matches and not rag.search("regression", tenant_id="other")
    for match in matches:
        print(match.citation_id, match.source, match.content)

Use read_chunk() to look up a citation, and list_documents(), remove(), and reindex() to manage the index. Derive scope, owner, and tenant filters from the authorization context and enforce access to citations downstream. SessionSearchProvider searches session events and returns session:<id>:<sequence> citations, rather than searching the document index. Version distinction: the v1.0.0 tag uses the original FTS5/LIKE query semantics. The plain-text and wildcard changes in PR #124 were merged after the tag. The example uses a fixed ordinary word.

Clone this wiki locally