-
Notifications
You must be signed in to change notification settings - Fork 0
feat(memory): add an artificial memory #44
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+519
−23
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| """Inspect conversation memories: current strength, decay projection, fate. | ||
|
|
||
| Usage: | ||
| python -m src.modules.rag.memory.memory_inspect | ||
| python -m src.modules.rag.memory.memory_inspect --user-id <id> | ||
| """ | ||
| import argparse | ||
| from datetime import datetime, timedelta | ||
|
|
||
| try: | ||
| from .qdrant_utils import make_qdrant_client | ||
| except ImportError: | ||
| from qdrant_utils import make_qdrant_client | ||
|
|
||
| HALF_LIFE_DAYS = 5.0 | ||
| DELETE_BELOW, CONSOLIDATE_BELOW = 0.05, 0.30 | ||
|
|
||
|
|
||
| def strength(payload: dict, at: datetime | None = None) -> float: | ||
| """Query-independent strength: recency * importance (matches maintenance).""" | ||
| at = at or datetime.now() | ||
| imp = payload.get("importance", 3) | ||
| half = max(HALF_LIFE_DAYS * (imp / 5.0), 0.5) | ||
| try: | ||
| last = datetime.fromisoformat(payload.get("last_accessed") or payload["created_at"]) | ||
| age = (at - last).total_seconds() / 86400.0 | ||
| except Exception: | ||
| age = 0.0 | ||
| return (0.5 ** (max(age, 0) / half)) * (imp / 10.0) | ||
|
|
||
|
|
||
| def fate(s: float) -> str: | ||
| if s < DELETE_BELOW: | ||
| return "DELETE" | ||
| if s < CONSOLIDATE_BELOW: | ||
| return "CONSOLIDATE" | ||
| return "KEEP" | ||
|
|
||
|
|
||
| def main(): | ||
| ap = argparse.ArgumentParser() | ||
| ap.add_argument("--qdrant-url", default="http://localhost:6333") | ||
| ap.add_argument("--collection", default="conversations") | ||
| ap.add_argument("--user-id", default=None) | ||
| args = ap.parse_args() | ||
|
|
||
| qdrant = make_qdrant_client(args.qdrant_url) | ||
| points, offset = [], None | ||
| while True: | ||
| batch, offset = qdrant.scroll(collection_name=args.collection, limit=200, | ||
| offset=offset, with_payload=True, with_vectors=False) | ||
| points.extend(batch) | ||
| if offset is None: | ||
| break | ||
|
|
||
| now = datetime.now() | ||
| rows = [] | ||
| for p in points: | ||
| pl = p.payload | ||
| if pl.get("type") == "maintenance_marker": | ||
| print(f"[marker] last maintenance run: {pl.get('last_run')}\n") | ||
| continue | ||
| if args.user_id and pl.get("_user_id") != args.user_id: | ||
| continue | ||
| s_now = strength(pl, now) | ||
| rows.append({ | ||
| "text": pl.get("text", "")[:60].replace("\n", " "), | ||
| "type": pl.get("type", "?"), | ||
| "imp": pl.get("importance", "?"), | ||
| "acc": pl.get("access_count", 0), | ||
| "age_d": round((now - datetime.fromisoformat( | ||
| pl.get("last_accessed") or pl["created_at"])).total_seconds() / 86400, 1), | ||
| "now": round(s_now, 3), | ||
| "+5d": round(strength(pl, now + timedelta(days=5)), 3), | ||
| "+15d": round(strength(pl, now + timedelta(days=15)), 3), | ||
| "fate": fate(s_now), | ||
| }) | ||
|
|
||
| rows.sort(key=lambda r: r["now"], reverse=True) | ||
| hdr = f"{'strength':>8} {'+5d':>6} {'+15d':>6} {'imp':>3} {'acc':>3} {'age':>5} {'fate':<12} text" | ||
| print(hdr) | ||
| print("-" * len(hdr)) | ||
| for r in rows: | ||
| print(f"{r['now']:>8} {r['+5d']:>6} {r['+15d']:>6} {r['imp']:>3} " | ||
| f"{r['acc']:>3} {r['age_d']:>5} {r['fate']:<12} {r['text']}") | ||
| print(f"\n{len(rows)} memories") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| """Periodic memory maintenance: decay-based pruning + consolidation. | ||
|
|
||
| Run every N days (cron/systemd timer): | ||
| python -m src.modules.rag.memory_maintenance | ||
| Strong memories are kept, weak ones are merged into a consolidated memory, | ||
| dead ones are deleted. Decay itself is computed lazily at query time in | ||
| rag.py; this job only prunes and compresses. | ||
| """ | ||
| import argparse | ||
| import json | ||
| import uuid | ||
| from collections import defaultdict | ||
| from datetime import datetime | ||
|
|
||
| import httpx | ||
| from qdrant_client.models import Distance, PointIdsList, PointStruct, VectorParams | ||
|
|
||
| try: | ||
| from .qdrant_utils import make_qdrant_client | ||
| except ImportError: | ||
| from qdrant_utils import make_qdrant_client | ||
|
|
||
| DELETE_BELOW = 0.05 | ||
| CONSOLIDATE_BELOW = 0.30 | ||
| HALF_LIFE_DAYS = 5.0 | ||
|
|
||
|
|
||
| def strength(payload: dict) -> float: | ||
| """Query-independent strength: recency * importance (no relevance term).""" | ||
| importance = payload.get("importance", 3) | ||
| half_life = max(HALF_LIFE_DAYS * (importance / 5.0), 0.5) | ||
| try: | ||
| last = datetime.fromisoformat(payload.get("last_accessed") or payload["created_at"]) | ||
| age_days = (datetime.now() - last).total_seconds() / 86400.0 | ||
| except Exception: | ||
| age_days = 0.0 | ||
| recency = 0.5 ** (age_days / half_life) | ||
| return recency * (importance / 10.0) | ||
|
|
||
|
|
||
| def embed(client: httpx.Client, url: str, model: str, text: str) -> list[float]: | ||
| r = client.post(f"{url}/v1/embeddings", json={"model": model, "input": text}) | ||
| r.raise_for_status() | ||
| return r.json()["data"][0]["embedding"] | ||
|
|
||
|
|
||
| def llm(client: httpx.Client, url: str, model: str, prompt: str) -> str: | ||
| r = client.post(f"{url}/api/chat", json={ | ||
| "model": model, "stream": False, | ||
| "messages": [{"role": "user", "content": prompt}], | ||
| "options": {"num_predict": 300}, | ||
| }) | ||
| r.raise_for_status() | ||
| return r.json()["message"]["content"] | ||
|
|
||
|
|
||
| def main(): | ||
| ap = argparse.ArgumentParser() | ||
| ap.add_argument("--qdrant-url", default="http://localhost:6333") | ||
| ap.add_argument("--collection", default="conversations") | ||
| ap.add_argument("--ollama-url", default="http://localhost:11434") | ||
| ap.add_argument("--embedding-model", default="bge-large-en-v1.5-gguf-Q4_K_M") | ||
| ap.add_argument("--llm-model", default="mistral:7b") | ||
| ap.add_argument("--dry-run", action="store_true") | ||
| args = ap.parse_args() | ||
|
|
||
| qdrant = make_qdrant_client(args.qdrant_url) | ||
| http = httpx.Client(timeout=180.0) | ||
|
|
||
| points, offset = [], None | ||
| while True: | ||
| batch, offset = qdrant.scroll(collection_name=args.collection, limit=200, | ||
| offset=offset, with_payload=True, with_vectors=False) | ||
| points.extend(batch) | ||
| if offset is None: | ||
| break | ||
| print(f"{len(points)} memories in '{args.collection}'") | ||
|
|
||
| to_delete, weak_by_user = [], defaultdict(list) | ||
| for p in points: | ||
| s = strength(p.payload) | ||
| if s < DELETE_BELOW: | ||
| to_delete.append(p) | ||
| elif s < CONSOLIDATE_BELOW: | ||
| weak_by_user[p.payload.get("_user_id", "anonymous")].append(p) | ||
| print(f"delete: {len(to_delete)}, consolidate candidates: {sum(map(len, weak_by_user.values()))}") | ||
|
|
||
| if args.dry_run: | ||
| return | ||
|
|
||
| for user, weak in weak_by_user.items(): | ||
| if len(weak) < 3: | ||
| continue # not worth merging yet; keep decaying | ||
| texts = [p.payload["text"] for p in weak] | ||
| merged = llm(http, args.ollama_url, args.llm_model, | ||
| "These are old memories about conversations with the same person. " | ||
| "Merge them into a single 3-5 sentence memory keeping only durable " | ||
| "facts, preferences and recurring themes. Drop one-off small talk.\n\n" | ||
| + "\n---\n".join(texts)).strip() | ||
| vec = embed(http, args.ollama_url, args.embedding_model, merged) | ||
| now = datetime.now().isoformat() | ||
| imp = min(max(p.payload.get("importance", 3) for p in weak) + 1, 10) | ||
| qdrant.upsert(collection_name=args.collection, points=[PointStruct( | ||
| id=str(uuid.uuid4()), vector=vec, payload={ | ||
| "text": merged, "_user_id": user, "type": "conversation_consolidated", | ||
| "created_at": now, "last_accessed": now, "access_count": 0, | ||
| "importance": imp, | ||
| })]) | ||
| to_delete.extend(weak) | ||
| print(f"[{user}] consolidated {len(weak)} → 1 (importance={imp})") | ||
|
|
||
| if to_delete: | ||
| qdrant.delete(collection_name=args.collection, | ||
| points_selector=PointIdsList(points=[p.id for p in to_delete])) | ||
| print(f"deleted {len(to_delete)} points") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
du coup on doit lancer le cron en parralele ? je pense qu'il faudrait voir avec mister pommier pour pouvoir le lancer avec huri
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Non on ne le lance pas a coté il travaille tout seul dans son coin