zeos-memory 1.2.0
Memory infrastructure for AI agents — persistent context, session governance, and three-tier memory
Requires Python: >=3.10
Keywords: agents, ai, context, knowledge-graph, llm, mcp, memory, session-management

# zeos-memory

Persistent memory for AI agents. Install, remember, recall. That's it.

```bash
pip install zeos-memory
```

```python
from zeos_memory import Memory

m = Memory("./data")
m.remember("user prefers dark mode")
m.recall("preferences")  # -> ["user prefers dark mode"]
```

Memories persist to disk. A knowledge graph builds silently underneath — connecting concepts, recognizing patterns, and making recall smarter the more you remember.

## Why not just a list?

A flat list works until your agent has 500 memories and queries return noise. zeos-memory uses BM25 text search **plus** a knowledge graph that tracks entity co-occurrence:

| Scenario | Query | BM25 Only | BM25 + Graph |
|----------|-------|-----------|--------------|
| Direct match | `React` | 2 hits | 2 hits |
| Co-occurrence | `Server Components` | 1 hit | 2 hits |
| Entity expansion | `TypeScript` | 2 hits | 3 hits |
| Lowercase tech | `kubernetes docker` | 2 hits | 2 hits |

The graph finds memories that keyword search misses — through entity links, co-occurrence patterns, and learned vocabulary. Zero configuration. Zero extra dependencies.

## Progressive Capability

### Level 0: In-memory (zero config)

```python
m = Memory()
m.remember("user likes vim")
m.recall("editor")  # -> ["user likes vim"]
```

### Level 1: Persistent (survives restarts)

```python
m = Memory("./agent-data")
# Memories, graph, and search index saved to disk automatically
```

### Level 2: Semantic search (install model2vec)

```bash
pip install zeos-memory[embeddings]
```

```python
m = Memory("./data")  # auto-detects model2vec
m.remember("the deployment uses kubernetes pods")
m.recall("container orchestration")  # semantic match
```

### Level 3: Fact extraction (bring your LLM)

```python
m = Memory("./data", llm=my_llm_fn)
m.add("User said they love Python and hate YAML configs")
# Extracts: ["User loves Python", "User dislikes YAML configs"]
```

Any function with signature `(prompt: str) -> str` works — OpenAI, Anthropic, Ollama, anything.

## API Reference

### `Memory(path?, agent?, embed_fn?, llm?)`

| Param | Type | Default | Description |
|-------|------|---------|-------------|
| `path` | `str \| Path \| None` | `None` | Storage directory. None = in-memory only |
| `agent` | `str` | `"default"` | Agent identifier |
| `embed_fn` | `callable \| None` | auto-detect | Embedding function. None = BM25-only |
| `llm` | `callable \| None` | `None` | LLM for fact extraction via `add()` |

### Methods

| Method | Returns | Description |
|--------|---------|-------------|
| `remember(text, metadata?)` | `None` | Store a memory |
| `recall(query, limit=5, explain=False)` | `list[str]` or `list[dict]` | Search by relevance |
| `add(text_or_messages)` | `list[str]` | Extract facts via LLM and store |
| `forget(text)` | `bool` | Remove first matching memory |
| `stats()` | `dict` | Count, tokens, health, retention, graph stats |
| `memories` | `list[str]` | All stored texts (property) |
| `len(m)` | `int` | Memory count |
| `"text" in m` | `bool` | Substring containment check |

### `recall()` with `explain=True`

```python
results = m.recall("React", explain=True)
# [{"content": "...", "score": 0.85, "decay": 3, "date": "2026-02-12",
#   "matched_terms": ["react"], "source": "manual", "graph_entities": ["react", "typescript"]}]
```

## Optional Extras

```bash
pip install zeos-memory[embeddings]   # model2vec for semantic search
pip install zeos-memory[mcp]          # MCP server for AI agent integration
pip install zeos-memory[full]         # Everything
```

### MCP Server

```json
{
  "mcpServers": {
    "zeos-memory": {
      "command": "python",
      "args": ["-m", "zeos_memory"]
    }
  }
}
```

## How It Works

**Storage:** MEMORY.md (human-readable) + GRAPH.json (knowledge graph) + optional embeddings cache. All plain files, version-controllable.

**Search pipeline:**
1. BM25 keyword scoring (always on)
2. Embedding similarity (if model2vec/fastembed installed)
3. Knowledge graph entity expansion (automatic)
4. Results merged: 70% text score + 30% graph score

**Knowledge graph:** Entities extracted via fast regex heuristics (<1ms for 200 words). Recognizes 120+ tech terms (kubernetes, docker, redis, etc.), CamelCase names, acronyms, version-qualified terms, and dotted names (Next.js). Entities from past memories are recognized in new ones automatically — the graph compounds.

**Retention tiers:** Memories carry decay scores (0-6). Higher = longer retention. Pinned memories persist indefinitely. When over token budget, low-decay entries archive first.

## Advanced: Full ZeosMemory API

Power users who need session lifecycle, decision tracking, or multi-agent governance:

```python
from zeos_memory import ZeosMemory

zm = ZeosMemory("my-project", agent="claude", root="./data")
session = zm.start_session()
zm.snap(delta="Built auth module")
journal, memory = zm.end(
    summary="Auth complete",
    delta="Tests passing",
    next_actions="Add refresh tokens",
)
```

## License

Apache-2.0