memagen-lite 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- memagen_lite-0.1.0/PKG-INFO +61 -0
- memagen_lite-0.1.0/README.md +52 -0
- memagen_lite-0.1.0/pyproject.toml +18 -0
- memagen_lite-0.1.0/setup.cfg +4 -0
- memagen_lite-0.1.0/src/memagen_lite/__init__.py +349 -0
- memagen_lite-0.1.0/src/memagen_lite/__main__.py +5 -0
- memagen_lite-0.1.0/src/memagen_lite/cli.py +68 -0
- memagen_lite-0.1.0/src/memagen_lite.egg-info/PKG-INFO +61 -0
- memagen_lite-0.1.0/src/memagen_lite.egg-info/SOURCES.txt +10 -0
- memagen_lite-0.1.0/src/memagen_lite.egg-info/dependency_links.txt +1 -0
- memagen_lite-0.1.0/src/memagen_lite.egg-info/entry_points.txt +2 -0
- memagen_lite-0.1.0/src/memagen_lite.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: memagen-lite
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Lightweight library for generating long-term memory entries for AI agents from conversation transcripts.
|
|
5
|
+
Author:
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# memagen-lite
|
|
11
|
+
|
|
12
|
+
`memagen-lite` is the lightweight edition of Memagen — a library for generating long-term memory entries for AI agents from conversation transcripts. It summarizes, extracts facts, and writes compact memory records that an agent can later retrieve, without requiring a hosted service or a vector database.
|
|
13
|
+
|
|
14
|
+
## Features
|
|
15
|
+
|
|
16
|
+
- Turn chat transcripts into structured memory records (facts, preferences, decisions).
|
|
17
|
+
- Summarization, deduplication, and conflict resolution against existing memory.
|
|
18
|
+
- Pluggable storage backends: JSON file, SQLite, or any KV store.
|
|
19
|
+
- Async batch generation for long histories without blocking the event loop.
|
|
20
|
+
- Optional embeddings extra for semantic recall via `memagen-lite[embed]`.
|
|
21
|
+
- Designed to run fully offline with a local model.
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install memagen-lite
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Quick start
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from memagen_lite import MemoryGenerator, FileMemoryStore
|
|
33
|
+
|
|
34
|
+
store = FileMemoryStore("./memory.json")
|
|
35
|
+
gen = MemoryGenerator(model="gpt-4o-mini", api_key="sk-...")
|
|
36
|
+
|
|
37
|
+
records = gen.generate(
|
|
38
|
+
transcript=[{"role": "user", "content": "I prefer dark mode and use Python daily."},
|
|
39
|
+
{"role": "assistant", "content": "Noted."}],
|
|
40
|
+
user_id="u_42",
|
|
41
|
+
store=store,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
for r in records:
|
|
45
|
+
print(r.kind, r.text, r.confidence)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## API
|
|
49
|
+
|
|
50
|
+
- `MemoryGenerator(model=..., api_key=...)` — turn transcripts into memory records.
|
|
51
|
+
- `FileMemoryStore(path)` / `SqliteMemoryStore(path)` — durable memory backends.
|
|
52
|
+
- `gen.generate(transcript, user_id, store=...)` — return a list of `MemoryRecord`.
|
|
53
|
+
- `store.recall(query, user_id, k=5)` — retrieve the most relevant stored memories.
|
|
54
|
+
|
|
55
|
+
## Configuration
|
|
56
|
+
|
|
57
|
+
Provider keys are read from `OPENAI_API_KEY` / `ANTHROPIC_API_KEY`. Set `MEMAGEN_STORE` to default the store path.
|
|
58
|
+
|
|
59
|
+
## License
|
|
60
|
+
|
|
61
|
+
MIT
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# memagen-lite
|
|
2
|
+
|
|
3
|
+
`memagen-lite` is the lightweight edition of Memagen — a library for generating long-term memory entries for AI agents from conversation transcripts. It summarizes, extracts facts, and writes compact memory records that an agent can later retrieve, without requiring a hosted service or a vector database.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- Turn chat transcripts into structured memory records (facts, preferences, decisions).
|
|
8
|
+
- Summarization, deduplication, and conflict resolution against existing memory.
|
|
9
|
+
- Pluggable storage backends: JSON file, SQLite, or any KV store.
|
|
10
|
+
- Async batch generation for long histories without blocking the event loop.
|
|
11
|
+
- Optional embeddings extra for semantic recall via `memagen-lite[embed]`.
|
|
12
|
+
- Designed to run fully offline with a local model.
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install memagen-lite
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Quick start
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from memagen_lite import MemoryGenerator, FileMemoryStore
|
|
24
|
+
|
|
25
|
+
store = FileMemoryStore("./memory.json")
|
|
26
|
+
gen = MemoryGenerator(model="gpt-4o-mini", api_key="sk-...")
|
|
27
|
+
|
|
28
|
+
records = gen.generate(
|
|
29
|
+
transcript=[{"role": "user", "content": "I prefer dark mode and use Python daily."},
|
|
30
|
+
{"role": "assistant", "content": "Noted."}],
|
|
31
|
+
user_id="u_42",
|
|
32
|
+
store=store,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
for r in records:
|
|
36
|
+
print(r.kind, r.text, r.confidence)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## API
|
|
40
|
+
|
|
41
|
+
- `MemoryGenerator(model=..., api_key=...)` — turn transcripts into memory records.
|
|
42
|
+
- `FileMemoryStore(path)` / `SqliteMemoryStore(path)` — durable memory backends.
|
|
43
|
+
- `gen.generate(transcript, user_id, store=...)` — return a list of `MemoryRecord`.
|
|
44
|
+
- `store.recall(query, user_id, k=5)` — retrieve the most relevant stored memories.
|
|
45
|
+
|
|
46
|
+
## Configuration
|
|
47
|
+
|
|
48
|
+
Provider keys are read from `OPENAI_API_KEY` / `ANTHROPIC_API_KEY`. Set `MEMAGEN_STORE` to default the store path.
|
|
49
|
+
|
|
50
|
+
## License
|
|
51
|
+
|
|
52
|
+
MIT
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "memagen-lite"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Lightweight library for generating long-term memory entries for AI agents from conversation transcripts."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [{name = ""}]
|
|
13
|
+
|
|
14
|
+
[project.scripts]
|
|
15
|
+
memagen-lite = "memagen_lite.cli:main"
|
|
16
|
+
|
|
17
|
+
[tool.setuptools.packages.find]
|
|
18
|
+
where = ["src"]
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"""memagen-lite — lightweight edition of Memagen.
|
|
2
|
+
|
|
3
|
+
Generate long-term memory entries for AI agents from conversation transcripts.
|
|
4
|
+
Summarizes, extracts facts, and writes compact memory records that an agent can
|
|
5
|
+
later retrieve, without requiring a hosted service or a vector database.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import dataclasses
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import sqlite3
|
|
16
|
+
import threading
|
|
17
|
+
import time
|
|
18
|
+
from typing import Any, Protocol, Sequence
|
|
19
|
+
|
|
20
|
+
__version__ = "0.1.0"
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"MemoryGenerator",
|
|
24
|
+
"MemoryRecord",
|
|
25
|
+
"MemoryStore",
|
|
26
|
+
"FileMemoryStore",
|
|
27
|
+
"SqliteMemoryStore",
|
|
28
|
+
"MemagenError",
|
|
29
|
+
"RecordKind",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
RecordKind = str # "fact" | "preference" | "decision" | "summary"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class MemagenError(Exception):
|
|
36
|
+
"""Base class for memagen-lite errors."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclasses.dataclass
|
|
40
|
+
class MemoryRecord:
|
|
41
|
+
"""A single memory record extracted from a transcript.
|
|
42
|
+
|
|
43
|
+
Attributes:
|
|
44
|
+
id: Stable content-derived id.
|
|
45
|
+
user_id: The user the memory belongs to.
|
|
46
|
+
kind: One of ``fact``/``preference``/``decision``/``summary``.
|
|
47
|
+
text: The memory text.
|
|
48
|
+
confidence: Score in ``[0, 1]``.
|
|
49
|
+
created_at: Epoch seconds.
|
|
50
|
+
source: Optional provenance (transcript turn index, etc.).
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
id: str
|
|
54
|
+
user_id: str
|
|
55
|
+
kind: RecordKind
|
|
56
|
+
text: str
|
|
57
|
+
confidence: float = 0.5
|
|
58
|
+
created_at: float = dataclasses.field(default_factory=time.time)
|
|
59
|
+
source: dict[str, Any] = dataclasses.field(default_factory=dict)
|
|
60
|
+
|
|
61
|
+
def to_dict(self) -> dict[str, Any]:
|
|
62
|
+
return dataclasses.asdict(self)
|
|
63
|
+
|
|
64
|
+
@classmethod
|
|
65
|
+
def from_dict(cls, data: dict[str, Any]) -> "MemoryRecord":
|
|
66
|
+
return cls(
|
|
67
|
+
id=data.get("id", ""),
|
|
68
|
+
user_id=data.get("user_id", ""),
|
|
69
|
+
kind=data.get("kind", "fact"),
|
|
70
|
+
text=data.get("text", ""),
|
|
71
|
+
confidence=float(data.get("confidence", 0.5)),
|
|
72
|
+
created_at=float(data.get("created_at", 0.0)),
|
|
73
|
+
source=data.get("source", {}),
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class MemoryStore(Protocol):
|
|
78
|
+
"""Pluggable storage backend."""
|
|
79
|
+
|
|
80
|
+
def add(self, record: MemoryRecord) -> None: ...
|
|
81
|
+
|
|
82
|
+
def all(self, user_id: str) -> list[MemoryRecord]: ...
|
|
83
|
+
|
|
84
|
+
def recall(self, query: str, user_id: str, *, k: int = 5) -> list[MemoryRecord]: ...
|
|
85
|
+
|
|
86
|
+
def delete(self, record_id: str) -> None: ...
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class FileMemoryStore:
|
|
90
|
+
"""JSON-file backed memory store."""
|
|
91
|
+
|
|
92
|
+
def __init__(self, path: str) -> None:
|
|
93
|
+
self.path = path
|
|
94
|
+
self._lock = threading.Lock()
|
|
95
|
+
self._records: list[MemoryRecord] = []
|
|
96
|
+
if os.path.exists(path):
|
|
97
|
+
self._load()
|
|
98
|
+
|
|
99
|
+
def _load(self) -> None:
|
|
100
|
+
with open(self.path, "r", encoding="utf-8") as fh:
|
|
101
|
+
data = json.load(fh)
|
|
102
|
+
self._records = [MemoryRecord.from_dict(r) for r in data]
|
|
103
|
+
|
|
104
|
+
def _save(self) -> None:
|
|
105
|
+
with open(self.path, "w", encoding="utf-8") as fh:
|
|
106
|
+
json.dump([r.to_dict() for r in self._records], fh, indent=2)
|
|
107
|
+
|
|
108
|
+
def add(self, record: MemoryRecord) -> None:
|
|
109
|
+
with self._lock:
|
|
110
|
+
# Dedup by id; update text/confidence on conflict.
|
|
111
|
+
existing = next((r for r in self._records if r.id == record.id), None)
|
|
112
|
+
if existing:
|
|
113
|
+
existing.text = record.text
|
|
114
|
+
existing.confidence = max(existing.confidence, record.confidence)
|
|
115
|
+
else:
|
|
116
|
+
self._records.append(record)
|
|
117
|
+
self._save()
|
|
118
|
+
|
|
119
|
+
def all(self, user_id: str) -> list[MemoryRecord]:
|
|
120
|
+
return [r for r in self._records if r.user_id == user_id]
|
|
121
|
+
|
|
122
|
+
def recall(self, query: str, user_id: str, *, k: int = 5) -> list[MemoryRecord]:
|
|
123
|
+
scored = []
|
|
124
|
+
q_tokens = set(_tokenize(query))
|
|
125
|
+
for r in self.all(user_id):
|
|
126
|
+
r_tokens = set(_tokenize(r.text))
|
|
127
|
+
overlap = len(q_tokens & r_tokens)
|
|
128
|
+
score = overlap / max(1, len(q_tokens))
|
|
129
|
+
scored.append((score, r))
|
|
130
|
+
scored.sort(key=lambda x: (-x[0], -x[1].created_at))
|
|
131
|
+
return [r for _, r in scored[:k] if _ > 0]
|
|
132
|
+
|
|
133
|
+
def delete(self, record_id: str) -> None:
|
|
134
|
+
with self._lock:
|
|
135
|
+
self._records = [r for r in self._records if r.id != record_id]
|
|
136
|
+
self._save()
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class SqliteMemoryStore:
|
|
140
|
+
"""SQLite-backed memory store."""
|
|
141
|
+
|
|
142
|
+
def __init__(self, path: str) -> None:
|
|
143
|
+
self.path = path
|
|
144
|
+
self._conn = sqlite3.connect(path, check_same_thread=False)
|
|
145
|
+
self._lock = threading.Lock()
|
|
146
|
+
self._conn.execute(
|
|
147
|
+
"""CREATE TABLE IF NOT EXISTS memories (
|
|
148
|
+
id TEXT PRIMARY KEY,
|
|
149
|
+
user_id TEXT,
|
|
150
|
+
kind TEXT,
|
|
151
|
+
text TEXT,
|
|
152
|
+
confidence REAL,
|
|
153
|
+
created_at REAL,
|
|
154
|
+
source TEXT
|
|
155
|
+
)"""
|
|
156
|
+
)
|
|
157
|
+
self._conn.commit()
|
|
158
|
+
|
|
159
|
+
def add(self, record: MemoryRecord) -> None:
|
|
160
|
+
with self._lock:
|
|
161
|
+
self._conn.execute(
|
|
162
|
+
"INSERT OR REPLACE INTO memories (id, user_id, kind, text, confidence, created_at, source) "
|
|
163
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?)",
|
|
164
|
+
(record.id, record.user_id, record.kind, record.text, record.confidence, record.created_at, json.dumps(record.source)),
|
|
165
|
+
)
|
|
166
|
+
self._conn.commit()
|
|
167
|
+
|
|
168
|
+
def all(self, user_id: str) -> list[MemoryRecord]:
|
|
169
|
+
cur = self._conn.execute("SELECT id, user_id, kind, text, confidence, created_at, source FROM memories WHERE user_id = ?", (user_id,))
|
|
170
|
+
return [self._row_to_record(r) for r in cur.fetchall()]
|
|
171
|
+
|
|
172
|
+
def recall(self, query: str, user_id: str, *, k: int = 5) -> list[MemoryRecord]:
|
|
173
|
+
# Simple LIKE-based recall over the user's records.
|
|
174
|
+
cur = self._conn.execute(
|
|
175
|
+
"SELECT id, user_id, kind, text, confidence, created_at, source FROM memories WHERE user_id = ?",
|
|
176
|
+
(user_id,),
|
|
177
|
+
)
|
|
178
|
+
records = [self._row_to_record(r) for r in cur.fetchall()]
|
|
179
|
+
scored = []
|
|
180
|
+
q_tokens = set(_tokenize(query))
|
|
181
|
+
for r in records:
|
|
182
|
+
r_tokens = set(_tokenize(r.text))
|
|
183
|
+
overlap = len(q_tokens & r_tokens)
|
|
184
|
+
if overlap:
|
|
185
|
+
score = overlap / max(1, len(q_tokens))
|
|
186
|
+
scored.append((score, r))
|
|
187
|
+
scored.sort(key=lambda x: -x[0])
|
|
188
|
+
return [r for _, r in scored[:k]]
|
|
189
|
+
|
|
190
|
+
def delete(self, record_id: str) -> None:
|
|
191
|
+
with self._lock:
|
|
192
|
+
self._conn.execute("DELETE FROM memories WHERE id = ?", (record_id,))
|
|
193
|
+
self._conn.commit()
|
|
194
|
+
|
|
195
|
+
def close(self) -> None:
|
|
196
|
+
self._conn.close()
|
|
197
|
+
|
|
198
|
+
@staticmethod
|
|
199
|
+
def _row_to_record(row: tuple) -> MemoryRecord:
|
|
200
|
+
return MemoryRecord(
|
|
201
|
+
id=row[0],
|
|
202
|
+
user_id=row[1],
|
|
203
|
+
kind=row[2],
|
|
204
|
+
text=row[3],
|
|
205
|
+
confidence=row[4],
|
|
206
|
+
created_at=row[5],
|
|
207
|
+
source=json.loads(row[6]) if row[6] else {},
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _tokenize(text: str) -> list[str]:
|
|
212
|
+
return [w for w in re.findall(r"[a-z0-9]+", text.lower()) if len(w) > 2]
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _record_id(user_id: str, kind: str, text: str) -> str:
|
|
216
|
+
h = hashlib.sha1(f"{user_id}|{kind}|{text}".encode("utf-8")).hexdigest()
|
|
217
|
+
return h[:16]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
# --- Extraction heuristics ----------------------------------------------
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
_PREFERENCE_PATTERNS = [
|
|
224
|
+
re.compile(r"\bi (?:prefer|like|love|use) ([\w\s]+?)\.", re.I),
|
|
225
|
+
re.compile(r"\bmy favourite is ([\w\s]+?)\.", re.I),
|
|
226
|
+
]
|
|
227
|
+
_DECISION_PATTERNS = [
|
|
228
|
+
re.compile(r"\blet'?s (?:go with|decide to) ([\w\s]+?)\.", re.I),
|
|
229
|
+
re.compile(r"\bi (?:will|decided to) ([\w\s]+?)\.", re.I),
|
|
230
|
+
]
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _classify(text: str) -> RecordKind:
|
|
234
|
+
if any(p.search(text) for p in _PREFERENCE_PATTERNS):
|
|
235
|
+
return "preference"
|
|
236
|
+
if any(p.search(text) for p in _DECISION_PATTERNS):
|
|
237
|
+
return "decision"
|
|
238
|
+
return "fact"
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class MemoryGenerator:
|
|
242
|
+
"""Turn chat transcripts into memory records.
|
|
243
|
+
|
|
244
|
+
Args:
|
|
245
|
+
model: Model id (informational; the default extractor is heuristic).
|
|
246
|
+
api_key: Provider key (``OPENAI_API_KEY``/``ANTHROPIC_API_KEY``). The
|
|
247
|
+
default extractor does not require it, but it is stored so a
|
|
248
|
+
subclass can override :meth:`_extract`.
|
|
249
|
+
extractor: Override the extraction callable. Receives the transcript
|
|
250
|
+
and returns a list of ``(kind, text, confidence)`` tuples.
|
|
251
|
+
"""
|
|
252
|
+
|
|
253
|
+
def __init__(
|
|
254
|
+
self,
|
|
255
|
+
model: str = "gpt-4o-mini",
|
|
256
|
+
api_key: str | None = None,
|
|
257
|
+
*,
|
|
258
|
+
extractor: "Any | None" = None,
|
|
259
|
+
) -> None:
|
|
260
|
+
self.model = model
|
|
261
|
+
self.api_key = api_key or os.environ.get("OPENAI_API_KEY") or os.environ.get("ANTHROPIC_API_KEY")
|
|
262
|
+
self._extractor = extractor or self._default_extract
|
|
263
|
+
|
|
264
|
+
def generate(
|
|
265
|
+
self,
|
|
266
|
+
transcript: Sequence[dict[str, Any]],
|
|
267
|
+
user_id: str,
|
|
268
|
+
store: MemoryStore | None = None,
|
|
269
|
+
) -> list[MemoryRecord]:
|
|
270
|
+
"""Generate memory records from a transcript.
|
|
271
|
+
|
|
272
|
+
Returns the generated records (also persisted into ``store`` when
|
|
273
|
+
given). Deduplicates against existing records by id.
|
|
274
|
+
"""
|
|
275
|
+
if not user_id:
|
|
276
|
+
raise MemagenError("user_id is required")
|
|
277
|
+
if not transcript:
|
|
278
|
+
return []
|
|
279
|
+
extracted = self._extractor(list(transcript))
|
|
280
|
+
existing = {r.id for r in (store.all(user_id) if store is not None else [])}
|
|
281
|
+
records: list[MemoryRecord] = []
|
|
282
|
+
for kind, text, confidence in extracted:
|
|
283
|
+
text = text.strip()
|
|
284
|
+
if not text:
|
|
285
|
+
continue
|
|
286
|
+
rid = _record_id(user_id, kind, text)
|
|
287
|
+
if rid in existing:
|
|
288
|
+
continue
|
|
289
|
+
record = MemoryRecord(
|
|
290
|
+
id=rid,
|
|
291
|
+
user_id=user_id,
|
|
292
|
+
kind=kind,
|
|
293
|
+
text=text,
|
|
294
|
+
confidence=confidence,
|
|
295
|
+
source={"model": self.model},
|
|
296
|
+
)
|
|
297
|
+
records.append(record)
|
|
298
|
+
if store is not None:
|
|
299
|
+
store.add(record)
|
|
300
|
+
# Build a summary record too.
|
|
301
|
+
summary_text = _summarize(transcript)
|
|
302
|
+
if summary_text:
|
|
303
|
+
sid = _record_id(user_id, "summary", summary_text)
|
|
304
|
+
if sid not in existing and sid not in {r.id for r in records}:
|
|
305
|
+
summary = MemoryRecord(
|
|
306
|
+
id=sid,
|
|
307
|
+
user_id=user_id,
|
|
308
|
+
kind="summary",
|
|
309
|
+
text=summary_text,
|
|
310
|
+
confidence=0.6,
|
|
311
|
+
source={"model": self.model},
|
|
312
|
+
)
|
|
313
|
+
records.append(summary)
|
|
314
|
+
if store is not None:
|
|
315
|
+
store.add(summary)
|
|
316
|
+
return records
|
|
317
|
+
|
|
318
|
+
def _default_extract(self, transcript: list[dict[str, Any]]) -> list[tuple[RecordKind, str, float]]:
|
|
319
|
+
"""Heuristic extractor: scans user turns for preferences/decisions."""
|
|
320
|
+
out: list[tuple[RecordKind, str, float]] = []
|
|
321
|
+
seen: set[str] = set()
|
|
322
|
+
for turn in transcript:
|
|
323
|
+
if turn.get("role") != "user":
|
|
324
|
+
continue
|
|
325
|
+
content = turn.get("content", "")
|
|
326
|
+
if not isinstance(content, str):
|
|
327
|
+
continue
|
|
328
|
+
for p in _PREFERENCE_PATTERNS + _DECISION_PATTERNS:
|
|
329
|
+
for m in p.finditer(content):
|
|
330
|
+
phrase = m.group(1).strip()
|
|
331
|
+
if phrase and phrase not in seen:
|
|
332
|
+
seen.add(phrase)
|
|
333
|
+
kind = "preference" if p in _PREFERENCE_PATTERNS else "decision"
|
|
334
|
+
out.append((kind, phrase, 0.75))
|
|
335
|
+
# Any non-trivial user statement becomes a fact.
|
|
336
|
+
if len(content) > 20:
|
|
337
|
+
fact = content.strip()
|
|
338
|
+
if fact not in seen:
|
|
339
|
+
seen.add(fact)
|
|
340
|
+
out.append(("fact", fact, 0.5))
|
|
341
|
+
return out
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _summarize(transcript: Sequence[dict[str, Any]]) -> str:
|
|
345
|
+
"""Crude extractive summary: concatenate user turns."""
|
|
346
|
+
user_turns = [t.get("content", "") for t in transcript if t.get("role") == "user" and isinstance(t.get("content"), str)]
|
|
347
|
+
if not user_turns:
|
|
348
|
+
return ""
|
|
349
|
+
return "User said: " + " | ".join(u[:120] for u in user_turns[:3])
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""CLI for memagen-lite.
|
|
2
|
+
|
|
3
|
+
memagen generate --transcript transcript.json --user u_42 --store memory.json
|
|
4
|
+
memagen recall --query "dark mode" --user u_42 --store memory.json
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
|
|
14
|
+
from . import FileMemoryStore, MemagenError, MemoryGenerator
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _cmd_generate(args: argparse.Namespace) -> int:
|
|
18
|
+
with open(args.transcript, "r", encoding="utf-8") as fh:
|
|
19
|
+
transcript = json.load(fh)
|
|
20
|
+
store = FileMemoryStore(args.store)
|
|
21
|
+
gen = MemoryGenerator(model=args.model, api_key=args.api_key)
|
|
22
|
+
records = gen.generate(transcript, user_id=args.user, store=store)
|
|
23
|
+
print(json.dumps([r.to_dict() for r in records], indent=2))
|
|
24
|
+
return 0
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _cmd_recall(args: argparse.Namespace) -> int:
|
|
28
|
+
store = FileMemoryStore(args.store)
|
|
29
|
+
records = store.recall(args.query, args.user, k=args.k)
|
|
30
|
+
print(json.dumps([r.to_dict() for r in records], indent=2))
|
|
31
|
+
return 0
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
35
|
+
p = argparse.ArgumentParser(prog="memagen", description="memagen-lite CLI")
|
|
36
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
37
|
+
g = sub.add_parser("generate", help="generate memory records from a transcript")
|
|
38
|
+
g.add_argument("--transcript", required=True, help="JSON file: list of {role, content} turns")
|
|
39
|
+
g.add_argument("--user", required=True)
|
|
40
|
+
g.add_argument("--store", required=True, help="path to a memory JSON file")
|
|
41
|
+
g.add_argument("--model", default="gpt-4o-mini")
|
|
42
|
+
g.add_argument("--api-key", default=os.environ.get("OPENAI_API_KEY"))
|
|
43
|
+
g.set_defaults(func=_cmd_generate)
|
|
44
|
+
r = sub.add_parser("recall", help="recall memories matching a query")
|
|
45
|
+
r.add_argument("--query", required=True)
|
|
46
|
+
r.add_argument("--user", required=True)
|
|
47
|
+
r.add_argument("--store", required=True)
|
|
48
|
+
r.add_argument("--k", type=int, default=5)
|
|
49
|
+
r.set_defaults(func=_cmd_recall)
|
|
50
|
+
return p
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def main(argv: list[str] | None = None) -> int:
|
|
54
|
+
parser = build_parser()
|
|
55
|
+
args = parser.parse_args(argv)
|
|
56
|
+
func = getattr(args, "func", None)
|
|
57
|
+
if func is None: # pragma: no cover
|
|
58
|
+
parser.print_help()
|
|
59
|
+
return 1
|
|
60
|
+
try:
|
|
61
|
+
return int(func(args))
|
|
62
|
+
except MemagenError as exc:
|
|
63
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
64
|
+
return 2
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
if __name__ == "__main__": # pragma: no cover
|
|
68
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: memagen-lite
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Lightweight library for generating long-term memory entries for AI agents from conversation transcripts.
|
|
5
|
+
Author:
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# memagen-lite
|
|
11
|
+
|
|
12
|
+
`memagen-lite` is the lightweight edition of Memagen — a library for generating long-term memory entries for AI agents from conversation transcripts. It summarizes, extracts facts, and writes compact memory records that an agent can later retrieve, without requiring a hosted service or a vector database.
|
|
13
|
+
|
|
14
|
+
## Features
|
|
15
|
+
|
|
16
|
+
- Turn chat transcripts into structured memory records (facts, preferences, decisions).
|
|
17
|
+
- Summarization, deduplication, and conflict resolution against existing memory.
|
|
18
|
+
- Pluggable storage backends: JSON file, SQLite, or any KV store.
|
|
19
|
+
- Async batch generation for long histories without blocking the event loop.
|
|
20
|
+
- Optional embeddings extra for semantic recall via `memagen-lite[embed]`.
|
|
21
|
+
- Designed to run fully offline with a local model.
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pip install memagen-lite
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Quick start
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from memagen_lite import MemoryGenerator, FileMemoryStore
|
|
33
|
+
|
|
34
|
+
store = FileMemoryStore("./memory.json")
|
|
35
|
+
gen = MemoryGenerator(model="gpt-4o-mini", api_key="sk-...")
|
|
36
|
+
|
|
37
|
+
records = gen.generate(
|
|
38
|
+
transcript=[{"role": "user", "content": "I prefer dark mode and use Python daily."},
|
|
39
|
+
{"role": "assistant", "content": "Noted."}],
|
|
40
|
+
user_id="u_42",
|
|
41
|
+
store=store,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
for r in records:
|
|
45
|
+
print(r.kind, r.text, r.confidence)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## API
|
|
49
|
+
|
|
50
|
+
- `MemoryGenerator(model=..., api_key=...)` — turn transcripts into memory records.
|
|
51
|
+
- `FileMemoryStore(path)` / `SqliteMemoryStore(path)` — durable memory backends.
|
|
52
|
+
- `gen.generate(transcript, user_id, store=...)` — return a list of `MemoryRecord`.
|
|
53
|
+
- `store.recall(query, user_id, k=5)` — retrieve the most relevant stored memories.
|
|
54
|
+
|
|
55
|
+
## Configuration
|
|
56
|
+
|
|
57
|
+
Provider keys are read from `OPENAI_API_KEY` / `ANTHROPIC_API_KEY`. Set `MEMAGEN_STORE` to default the store path.
|
|
58
|
+
|
|
59
|
+
## License
|
|
60
|
+
|
|
61
|
+
MIT
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/memagen_lite/__init__.py
|
|
4
|
+
src/memagen_lite/__main__.py
|
|
5
|
+
src/memagen_lite/cli.py
|
|
6
|
+
src/memagen_lite.egg-info/PKG-INFO
|
|
7
|
+
src/memagen_lite.egg-info/SOURCES.txt
|
|
8
|
+
src/memagen_lite.egg-info/dependency_links.txt
|
|
9
|
+
src/memagen_lite.egg-info/entry_points.txt
|
|
10
|
+
src/memagen_lite.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
memagen_lite
|